text:
var util = require('util'); // util.inherits
var net = require('net');

var handshake = require('./handshake');
//var xevents = require('./xevents');

var EventEmitter = require('events').EventEmitter;
var PackStream = require('./unpackstream');
var hexy = require('./hexy').hexy;

var Buffer = require('buffer').Buffer;
// add 'unpack' method for buffer
require('./unpackbuffer').addUnpack(Buffer);

var os = require('os');

var xerrors = require('./xerrors');
var coreRequests = require('./corereqs');
var stdatoms = require('./stdatoms');
var em = require('./eventmask').eventMask;

function XClient(displayNum, screenNum, options)
{
    EventEmitter.call(this);
    this.options = options ? options : {};

    // TODO: this is probably not used
    this.core_requests = {};
    this.ext_requests = {};

    this.displayNum = displayNum;
    this.screenNum = screenNum;
}
util.inherits(XClient, EventEmitter);

XClient.prototype.init = function(stream)
{
    this.stream = stream;

    this.authHost = stream.remoteAddress;
    // Node v0.10.x does not have stream.remoteFamily, so dig in to find it
    this.authFamily = stream._getpeername ? stream._getpeername().family : stream.remoteFamily;
    if (!this.authHost || this.authHost === '127.0.0.1' || this.authHost === '::1') {
      this.authHost = os.hostname();
      this.authFamily = null;
    }

    var pack_stream = new PackStream();

    // data received from stream is dispached to
    // read requests set by calls to .unpack and .unpackTo
    //stream.pipe(pack_stream);

    // pack_stream write requests are buffered and
    // flushed to stream as result of call to .flush
    // TODO: listen for drain event and flush automatically
    //pack_stream.pipe(stream);
    var client = this;
    pack_stream.on('data', function( data ) {
        //console.error(hexy(data, {prefix: 'from packer '}));
        //for (var i=0; i < data.length; ++i)
        //   console.log('<<< ' + data[i]);
        stream.write(data);
    });
    stream.on('data', function( data ) {
        //console.error(hexy(data, {prefix: 'to unpacker '}));
        //for (var i=0; i < data.length; ++i)
        //   console.log('>>> ' + data[i]);
        pack_stream.write(data);
    });
    stream.on('end', function() {
        client.emit('end');
    });

    this.pack_stream = pack_stream;

    this.rsrc_id = 0; // generated for each new resource
    var cli = this;
    if (cli.options.debug) {
      this.seq_num_ = 0;
      this.seq2stack = {}; // debug: map seq_num to stack at the moment request was issued
      Object.defineProperty(cli, "seq_num", {
        set : function(v) {
          cli.seq_num_ = v;
          var err = new Error();
          Error.captureStackTrace(err, arguments.callee);
          err.timestamp = Date.now();
          cli.seq2stack[client.seq_num] = err;
        },
        get: function() {
	  return cli.seq_num_;
        }
      });
    } else {
      this.seq_num = 0;
    }

    // in/out packets indexed by sequence ID
    this.replies = {};
    this.atoms = stdatoms;
    this.atom_names = (function() {
        var names = {};
        Object.keys(stdatoms).forEach(function(key) {
            names[stdatoms[key]] = key;
        });

        return names;
    })();

    this.eventMask = em;

    this.event_consumers = {}; // maps window id to eventemitter TODO: bad name
    this.eventParsers = {};
    this.errorParsers = {};
    this._extensions = {};

    this.importRequestsFromTemplates(this, coreRequests);

    this.startHandshake();
    this._closing = false;
    this._unusedIds = [];
}

// TODO: close() = set 'closing' flag, watch it in replies and writeQueue, terminate if empty
XClient.prototype.terminate = function()
{
    this.stream.end();
}

// GetAtomName used as cheapest non-modifying request with reply
// 3 - id for shortest standard atom, "ARC"
XClient.prototype.ping = function(cb) {
   var start = Date.now();
   this.GetAtomName(3, function(err, str) {
      if (err) return cb(err);
      return cb(null, Date.now() - start);
   });
}

XClient.prototype.close = function(cb) {
    var cli = this;
    cli.ping(function(err) {
      if (err) return cb(err);
      cli.terminate();
      if (cb) cb();
    });
    cli._closing = true;
}

XClient.prototype.importRequestsFromTemplates = function(target, reqs)
{
    var client = this;
    this.pending_atoms = {};
    for (var r in reqs)
    {
        // r is request name
        target[r] = (function(reqName) {

            var reqFunc = function req_proxy() {

            if (client._closing)
               throw new Error('client is in closing state');

            // simple overflow handling (this means that currently there is no way to have more than 65535 requests in the queue
            // TODO: edge cases testing
            if (client.seq_num == 65535)
               client.seq_num = 0;
            else
               client.seq_num++;

            // is it fast?
            var args = Array.prototype.slice.call(req_proxy.arguments);

            var callback = args.length > 0 ? args[args.length - 1] : null;
            if (callback && callback.constructor.name != 'Function')
                callback = null;

            // TODO: see how much we can calculate in advance (not in each request)
            var reqReplTemplate = reqs[reqName];
            var reqTemplate  = reqReplTemplate[0];
            var templateType = typeof reqTemplate;

            if (templateType == 'object')
                templateType = reqTemplate.constructor.name;

            if (templateType == 'function')
            {
                 if (reqName === 'InternAtom') {
                     var value = req_proxy.arguments[1];
                     if (client.atoms[value]) {
                         -- client.seq_num;
                         return setImmediate(function() {
                             callback(undefined, client.atoms[value]);
                         });
                     } else {
                         client.pending_atoms[client.seq_num] = value;
                     }
                 }

                 // call template with input arguments (not including callback which is last argument TODO currently with callback. won't hurt)
                 //reqPack = reqTemplate.call(args);
                 var reqPack = reqTemplate.apply(this, req_proxy.arguments);
                 var format = reqPack[0];
                 var requestArguments = reqPack[1];

                 if (callback)
                     this.replies[this.seq_num] = [reqReplTemplate[1], callback];

                 client.pack_stream.pack(format, requestArguments);
                 var b = client.pack_stream.write_queue[0];
                 client.pack_stream.flush();

            } else if (templateType == 'Array'){
                 if (reqName === 'GetAtomName') {
                     var atom = req_proxy.arguments[0];
                     if (client.atom_names[atom]) {
                         -- client.seq_num;
                         return setImmediate(function() {
                             callback(undefined, client.atom_names[atom]);
                         });
                     } else {
                         client.pending_atoms[client.seq_num] = atom;
                     }
                 }

                 var format = reqTemplate[0];
                 var requestArguments = [];

                 for (var a = 0; a < reqTemplate[1].length; ++a)
                     requestArguments.push(reqTemplate[1][a]);
                 for (var a in args)
                     requestArguments.push(args[a]);

                 if (callback)
                     this.replies[this.seq_num] = [reqReplTemplate[1], callback];

                 client.pack_stream.pack(format, requestArguments);
                 client.pack_stream.flush();
            } else {
                 throw 'unknown request format - ' + templateType;
            }
        }
        return reqFunc;
        })(r);
    }
}

XClient.prototype.AllocID = function()
{
  if (this._unusedIds.length > 0) {
    return this._unusedIds.pop();
  }
  // TODO: handle overflow (XCMiscGetXIDRange from XC_MISC ext)
  this.display.rsrc_id++;
  return (this.display.rsrc_id << this.display.rsrc_shift) + this.display.resource_base;
};

XClient.prototype.ReleaseID = function(id) {
  this._unusedIds.push(id);
};

// TODO: move core events unpackers to corereqs.js
XClient.prototype.unpackEvent = function(type, seq, extra, code, raw, headerBuf)
{
    var event = {}; // TODO: constructor & base functions
    // Remove the most significant bit. See Chapter 1, Event Format section in X11 protocol
    // specification
    type = type & 0x7F;
    event.type = type;
    event.seq = seq;

    var extUnpacker = this.eventParsers[type];
    if (extUnpacker)
    {
        return extUnpacker(type, seq, extra, code, raw);
    }

    if (type == 2 || type == 3 || type == 4 || type == 5 || type == 6) { // motion event
        var values = raw.unpack('LLLssssSC');
        //event.raw = values;
        // TODO: use unpackTo???
        event.name = [,,'KeyPress', 'KeyRelease', 'ButtonPress', 'ButtonRelease', 'MotionNotify'][type]
        event.time = extra;
        event.keycode = code;
        event.root = values[0];
        event.wid = values[1];
        event.child = values[2];
        event.rootx = values[3];
        event.rooty = values[4];
        event.x = values[5];
        event.y = values[6];
        event.buttons = values[7];
        event.sameScreen = values[8];
    } else if (type == 7 || type == 8) { //EnterNotify || LeaveNotify
        event.name = type === 7 ? 'EnterNotify' : 'LeaveNotify';
        var values = raw.unpack('LLLssssSC');
        event.root = values[0]
        event.wid = values[1]
        event.child = values[2];
        event.rootx = values[3];
        event.rooty = values[4];
        event.x = values[5];
        event.y = values[6];
        event.values = values

    } else if (type == 12) { // Expose
        var values = raw.unpack('SSSSS');
        event.name = 'Expose'
        event.wid = extra;
        event.x = values[0];
        event.y = values[1];
        event.width = values[2];
        event.height = values[3];
        event.count = values[4]; // TODO: ???
    } else if (type == 16) { // CreateNotify
        var values = raw.unpack('LssSSSc');
        event.name = 'CreateNotify'
        event.parent = extra;
        event.wid = values[0];
        event.x = values[1];
        event.y = values[2];
        event.width = values[3];
        event.height = values[4];
        event.borderWidth = values[5];
        event.overrideRedirect = values[6] ? true : false;
        // x, y, width, height, border
    } else if (type == 17) { // destroy notify
        var values = raw.unpack('L');
        event.name = 'DestroyNotify'
        event.event = extra;
        event.wid = values[0];
    } else if (type == 18) { // UnmapNotify
        var values = raw.unpack('LC');
        event.name = 'UnmapNotify'
        event.event = extra;
        event.wid = values[0];
        event.fromConfigure = values[1] ? true : false;
    } else if (type == 19) { // MapNotify
        var values = raw.unpack('LC');
        event.name = 'MapNotify'
        event.event = extra;
        event.wid = values[0];
        event.overrideRedirect = values[1] ? true : false;
    } else if (type == 20) {
        var values = raw.unpack('L');
        event.name = 'MapRequest'
        event.parent = extra;
        event.wid = values[0];
    } else if (type == 22) {
        var values = raw.unpack('LLssSSSC');
        event.name = 'ConfigureNotify';
        event.wid = extra;
        // TODO rename
        event.wid1 = values[0];
        event.aboveSibling = values[1];
        event.x = values[2];
        event.y = values[3];
        event.width = values[4];
        event.height = values[5];
        event.borderWidth = values[6];
        event.overrideRedirect = values[7];
    } else if (type == 23) {
        var values = raw.unpack('LLssSSSS');
        event.name = 'ConfigureRequest';
        event.stackMode = code;
        event.parent = extra;
        event.wid = values[0];
        event.sibling = values[1];
        event.x = values[2]
        event.y = values[3]
        event.width = values[4]
        event.height = values[5]
        event.borderWidth = values[6];
        //
        // The value-mask indicates which components were specified in
        // the request. The value-mask and the corresponding values are reported as given
        // in the request. The remaining values are filled in from the current geometry of the
        // window, except in the case of sibling and stack-mode, which are reported as None
        // and Above (respectively) if not given in the request.
        event.mask = values[6];
        // 322, [ 12582925, 0, 0, 484, 316, 1, 12, 0
        //console.log([extra, code, values]);
    } else if (type == 28) {// PropertyNotify
        event.name = 'PropertyNotify';
        var values = raw.unpack('LLC');
        event.wid = extra;
        event.atom = values[0];
        event.time = values[1];
        event.state = values[2];
    } else if (type == 29) {// SelectionClear
        event.name = 'SelectionClear';
        event.time = extra;
        var values = raw.unpack('LL');
        event.owner = values[0];
        event.selection = values[1];
    } else if (type == 30) {// SelectionRequest
        event.name = 'SelectionRequest';
        // TODO check this
        event.time = extra;
        var values = raw.unpack('LLLLL');
        event.owner = values[0];
        event.requestor = values[1];
        event.selection = values[2];
        event.target = values[3];
        event.property = values[4];
    } else if (type == 31) {// SelectionNotify
        event.name = 'SelectionNotify';
        // TODO check this
        event.time = extra;
        var values = raw.unpack('LLLL');
        event.requestor = values[0];
        event.selection = values[1];
        event.target = values[2];
        event.property = values[3];
    } else if (type == 33) {// ClientMessage
        event.name = 'ClientMessage';
        event.format = code;
        event.wid = extra;
        event.message_type = raw.unpack('L')[0];
        var format = (code === 32) ? 'LLLLL' : (code === 16) ? 'SSSSSSSSSS' : 'CCCCCCCCCCCCCCCCCCCC';
        event.data = raw.unpack(format, 4);
    } else if (type == 34) {
        event.name = 'MappingNotify';
        event.request = headerBuf[4];
        event.firstKeyCode = headerBuf[5];
        event.count = headerBuf[6];
    }
    return event;
}

XClient.prototype.expectReplyHeader = function()
{
    // TODO: move error parsers to corereqs.js

    var client = this;
    client.pack_stream.get( 8, function(headerBuf) {
            var res = headerBuf.unpack('CCSL');
            var type = res[0];
            var seq_num = res[2];
            var bad_value = res[3];

            if (type == 0)
            {
                var error_code = res[1];
                var error = new Error();
                error.error = error_code;
                error.seq = seq_num;
                if (client.options.debug) {
                  error.longstack = client.seq2stack[error.seq]
                  console.log(client.seq2stack[error.seq].stack);
                }

                // unpack error packet (32 bytes for all error types, 8 of them in CCSL header)
                client.pack_stream.get(24, function(buf) {

		    var res = buf.unpack('SC');
	   	    error.message = xerrors.errorText[error_code];
		    error.badParam = bad_value;
		    error.minorOpcode = res[0];
		    error.majorOpcode = res[1];

	            var extUnpacker = client.errorParsers[error_code];
                    if (extUnpacker) {
                      extUnpacker(error, error_code, seq_num, bad_value, buf);
                    }

                    var handler = client.replies[seq_num];
                    if (handler) {
                        var callback = handler[1];
                        var handled = callback(error);
                        if (!handled)
                            client.emit('error', error);
                        // TODO: should we delete seq2stack and reply even if there is no handler?
			if (client.options.debug)
                          delete client.seq2stack[seq_num];
                        delete client.replies[seq_num];
                    } else
                        client.emit('error', error);
                    client.expectReplyHeader();
                } );
                return;
            } else if (type > 1)
            {
                client.pack_stream.get(24, function(buf) {
                    var extra = res[3];
                    var code = res[1];
                    var ev = client.unpackEvent(type, seq_num, extra, code, buf, headerBuf);

                    // raw event 32-bytes packet (primarily for use in SendEvent);
                    // TODO: Event::pack based on event parameters, inverse to unpackEvent
                    ev.rawData = new Buffer(32);
                    headerBuf.copy(ev.rawData);
                    buf.copy(ev.rawData, 8);

                    client.emit('event', ev);
                    var ee = client.event_consumers[ev.wid];
                    if (ee) {
                       ee.emit('event', ev);
                    }
                    if (ev.parent) {
                       ee = client.event_consumers[ev.parent];
                       if (ee)
                         ee.emit('child-event', ev);
                    }
                    client.expectReplyHeader();
                } );
                return;
            }

            var opt_data = res[1];
            var length_total = res[3];            // in 4-bytes units, _including_ this header
            var bodylength = 24 + length_total*4; // 24 is rest if 32-bytes header

            client.pack_stream.get( bodylength, function( data ) {

                var handler = client.replies[seq_num];
                if (handler) {
                    var unpack = handler[0];
                    if (client.pending_atoms[seq_num]) {
                        opt_data = seq_num;
                    }

                    var result = unpack.call(client, data, opt_data);
                    var callback = handler[1];
                    callback(null, result);
                    // TODO: add multiple replies flag and delete handler only after last reply (eg ListFontsWithInfo)
                    delete client.replies[seq_num];
                }
                // wait for new packet from server
                client.expectReplyHeader();
            });
        }
    );
}

XClient.prototype.startHandshake = function() {
    var client = this;

    handshake.writeClientHello(this.pack_stream, this.displayNum, this.authHost, this.authFamily);
    handshake.readServerHello(this.pack_stream, function(err, display)
    {
        if (err) {
            client.emit('error', err);
            return;
        }
        client.expectReplyHeader();
        client.display = display;
        display.client = client;
        client.emit('connect', display);
    });
}

XClient.prototype.require = function(extName, callback)
{
   var self = this;
   var ext = this._extensions[extName];
   if (ext) {
       return process.nextTick(function() {
           callback(null, ext);
       });
   }

   ext = require('./ext/' + extName);
   ext.requireExt(this.display, function(err, _ext) {
       if (err) {
           return callback(err);
       }

       self._extensions[extName] = _ext;
       callback(null, _ext);
   });
};

module.exports.createClient = function(options, initCb)
{
    if (typeof options === 'function') {
        initCb = options;
        options = {};
    }

    if (!options) options = {};

    var display = options.display;
    if (!display)
        display = (process.env.DISPLAY) ? process.env.DISPLAY : ':0';

    var displayMatch = display.match(/^(?:[^:]*?\/)?(.*):(\d+)(?:.(\d+))?$/);
    if (!displayMatch)
       throw new Error("Cannot parse display");

    var host = displayMatch[1];

    var displayNum = displayMatch[2];
    if (!displayNum)
        displayNum = 0;
    var screenNum = displayMatch[3];
    if (!screenNum)
        screenNum = 0;

    // open stream
    var stream;
    var connected = false;
    var cbCalled = false;
    var socketPath;

    // try local socket on non-windows platforms
    if ( ['cygwin', 'win32', 'win64'].indexOf(process.platform) < 0 )
    {
        if (process.platform == 'darwin' || process.platform == 'mac')
        {
            // socket path on OSX is /tmp/launch-(some id)/org.x:0
            if (display[0] == '/')
            {
                socketPath = display;
            }
        } else if(!host)
            socketPath = '/tmp/.X11-unix/X' + displayNum;
    }
    var client = new XClient(displayNum, screenNum, options);

    var connectStream = function() {
        if (socketPath) {
            stream = net.createConnection(socketPath);
        } else {
            stream = net.createConnection(6000 + parseInt(displayNum), host);
        }
        stream.on('connect', function() {
            connected = true;
            client.init(stream);
        });
        stream.on('error', function(err) {
            if (!connected && socketPath && err.code === 'ENOENT') {
                // Retry connection with TCP on localhost
                socketPath = null;
                host = 'localhost';
                connectStream();
            } else if (initCb && !cbCalled) {
                cbCalled = true;
                initCb(err);
            } else {
                client.emit('error', err);
            }
        });
    };
    connectStream();
    if (initCb)
    {
        client.on('connect', function(display) {
            // opt-in BigReq
            if (!options.disableBigRequests) {
                client.require('big-requests', function(err, BigReq) {
                    if (err)
                        return initCb(err)
                    BigReq.Enable(function(err, maxLen) {
                        display.max_request_length = maxLen;
	                cbCalled = true;
                        initCb(undefined, display);
                    });
                });
            } else {
	        cbCalled = true;
                initCb(undefined, display);
            }
        });
    }
    return client;
}


text:
package com.cwainner.chris.recipecentral;

import android.os.Build;
import android.widget.TextView;

import com.cwainner.chris.recipecentral.ui.AboutActivity;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;

import static org.junit.Assert.*;

@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP)
@RunWith(RobolectricGradleTestRunner.class)

public class AboutActivityTest {
    private AboutActivity activity;

    @Before
    public void setup() {
        activity = Robolectric.setupActivity(AboutActivity.class);
    }

    @Test
    public void validateAboutHeader(){
        TextView aboutHeaderView = (TextView) activity.findViewById(R.id.aboutHeader);
        assertTrue("About".equals(aboutHeaderView.getText().toString()));
    }

    @Test
    public void validateAboutText(){
        TextView aboutTextView = (TextView) activity.findViewById(R.id.aboutText);
        String aboutTextContent = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi egestas, ante sit amet facilisis auctor, risus arcu faucibus justo, at tempor odio est ut est. Sed sodales augue a egestas suscipit. Curabitur malesuada tellus dolor, quis laoreet ipsum suscipit tristique. Sed vel ex iaculis, sollicitudin ipsum ac, maximus augue. Phasellus ut dui sed sapien vulputate dapibus. Suspendisse sed neque nec dolor pulvinar iaculis. Suspendisse lorem nisi, tristique a sapien at, porta blandit eros. Nam ut tincidunt mauris, id sollicitudin nulla. Mauris sit amet tincidunt nulla. Etiam elit velit, rutrum sit amet velit in, placerat commodo augue. Curabitur vitae rhoncus velit. In porttitor dictum cursus. Mauris eu fermentum dolor. Phasellus laoreet, metus ut malesuada convallis, elit arcu porta urna, condimentum porttitor magna turpis eget dolor.";
        assertTrue(aboutTextContent.equals(aboutTextView.getText().toString()));
    }
}

redpajama_set_name: RedPajamaGithub


text:
#if !defined(lint) && !defined(DOS)
static char rcsid[] = "$Id: init.c 769 2007-10-24 00:15:40Z hubert@u.washington.edu $";
#endif

/*======================================================================
     init.c
     Routines for pine start up and initialization
  ====*/

#include "../pith/headers.h"
#include "../pith/init.h"
#include "../pith/conf.h"
#include "../pith/status.h"
#include "../pith/folder.h"

/*
 * Internal prototypes
 */
int	 compare_sm_files(const qsort_t *, const qsort_t *);

/*----------------------------------------------------------------------
    Sets  login, full_username and home_dir

   Args: ps -- The Pine structure to put the user name, etc in

  Result: sets the fullname, login and home_dir field of the pine structure
          returns 0 on success, -1 if not.
  ----*/

int
init_username(struct pine *ps)
{
    char *expanded;
    int	  rv;

    rv       = 0;
    expanded = NULL;
#if defined(DOS) || defined(OS2)
    if(ps->COM_USER_ID)
      expanded = expand_variables(tmp_20k_buf, SIZEOF_20KBUF,
				  ps->COM_USER_ID, 0);

    if(!expanded && ps->vars[V_USER_ID].post_user_val.p)
      expanded = expand_variables(tmp_20k_buf, SIZEOF_20KBUF,
				  ps->vars[V_USER_ID].post_user_val.p, 0);

    if(!expanded && ps->vars[V_USER_ID].main_user_val.p)
      expanded = expand_variables(tmp_20k_buf, SIZEOF_20KBUF,
				  ps->vars[V_USER_ID].main_user_val.p, 0);

    if(!expanded)
      ps->blank_user_id = 1;

    ps->VAR_USER_ID = cpystr(expanded ? expanded : "");
#else
    ps->VAR_USER_ID = cpystr(ps->ui.login);
    if(!ps->VAR_USER_ID[0]){
        fprintf(stderr, "Who are you? (Unable to look up login name)\n");
        rv = -1;
    }
#endif

    expanded = NULL;
    if(ps->vars[V_PERSONAL_NAME].is_fixed){
	if(ps->FIX_PERSONAL_NAME){
            expanded = expand_variables(tmp_20k_buf, SIZEOF_20KBUF,
					ps->FIX_PERSONAL_NAME, 0);
	}
	if(ps->vars[V_PERSONAL_NAME].main_user_val.p ||
	   ps->vars[V_PERSONAL_NAME].post_user_val.p){
	    ps_global->give_fixed_warning = 1;
	    ps_global->fix_fixed_warning = 1;
	}
	else if(ps->COM_PERSONAL_NAME)
	  ps_global->give_fixed_warning = 1;
    }
    else{
	if(ps->COM_PERSONAL_NAME)
	  expanded = expand_variables(tmp_20k_buf, SIZEOF_20KBUF,
				      ps->COM_PERSONAL_NAME, 0);

	if(!expanded && ps->vars[V_PERSONAL_NAME].post_user_val.p)
	  expanded = expand_variables(tmp_20k_buf, SIZEOF_20KBUF,
			      ps->vars[V_PERSONAL_NAME].post_user_val.p, 0);

	if(!expanded && ps->vars[V_PERSONAL_NAME].main_user_val.p)
	  expanded = expand_variables(tmp_20k_buf, SIZEOF_20KBUF,
			      ps->vars[V_PERSONAL_NAME].main_user_val.p, 0);
    }

    if(!expanded){
	expanded = ps->ui.fullname;
#if defined(DOS) || defined(OS2)
	ps->blank_personal_name = 1;
#endif
    }

    ps->VAR_PERSONAL_NAME = cpystr(expanded ? expanded : "");

    dprint((1, "Userid: %s\nFullname: \"%s\"\n",
               ps->VAR_USER_ID, ps->VAR_PERSONAL_NAME));
    return(rv);
}

/*----------------------------------------------------------------------
    Sets  home_dir

   Args: ps -- The Pine structure to put the user name, etc in

  Result: sets the home_dir field of the pine structure
          returns 0 on success, -1 if not.
  ----*/

int
init_userdir(struct pine *ps)
{
    char fld_dir[MAXPATH+1];

    if(strlen(ps->home_dir) + strlen(ps->VAR_MAIL_DIRECTORY)+2 > MAXPATH){
        printf(_("Folders directory name is longer than %d\n"), MAXPATH);
        printf(_("Directory name: \"%s/%s\"\n"),ps->home_dir,
               ps->VAR_MAIL_DIRECTORY);
        return(-1);
    }
#if defined(DOS) || defined(OS2)
    if(ps->VAR_MAIL_DIRECTORY[1] == ':'){
	strncpy(fld_dir, ps->VAR_MAIL_DIRECTORY, sizeof(fld_dir)-1);
	fld_dir[sizeof(fld_dir)-1] = '\0';
    }
    else
#endif
    build_path(fld_dir, ps->home_dir, ps->VAR_MAIL_DIRECTORY, sizeof(fld_dir));
    ps->folders_dir = cpystr(fld_dir);

    return(0);
}

/*----------------------------------------------------------------------
        Fetch the hostname of the current system and put it in pine struct

   Args: ps -- The pine structure to put the hostname, etc in

  Result: hostname, localdomain, userdomain and maildomain are set

** Pine uses the following set of names:
  hostname -    The fully-qualified hostname.  Obtained with
		gethostbyname() which reads /etc/hosts or does a DNS
		lookup.  This may be blank.
  localdomain - The domain name without the host.  Obtained from the
		above hostname if it has a "." in it.  Removes first
		segment.  If hostname has no "." in it then the hostname
		is used.  This may be blank.
  userdomain -  Explicitly configured domainname.  This is read out of the
		global pine.conf or user's .pinerc.  The user's entry in the
		.pinerc overrides.

** Pine has the following uses for such names:

  1. On outgoing messages in the From: line
	Uses userdomain if there is one.  If not uses, uses
	hostname unless Pine has been configured to use localdomain.

  2. When expanding/fully-qualifying unqualified addresses during
     composition
	(same as 1)

  3. When expanding/fully-qualifying unqualified addresses during
     composition when a local entry in the password file exists for
     name.
        If no userdomain is given, then this lookup is always done
	and the hostname is used unless Pine's been configured to
	use the localdomain.  If userdomain is defined, it is used,
	but no local lookup is done.  We can't assume users on the
	local host are valid in the given domain (and, for simplicity,
	have chosen to ignore the cases userdomain matches localdomain
	or localhost).  Setting user-lookup-even-if-domain-mismatch
	feature will tell pine to override this behavior and perform
	the local lookup anyway.  The problem of a global "even-if"
	set and a .pinerc-defined user-domain of something odd causing
	the local lookup, but this will only effect the personal name,
	and is not judged to be a significant problem.

  4. In determining if an address is that of the current pine user for
     formatting index and filtering addresses when replying
	If a userdomain is specified the address must match the
	userdomain exactly.  If a userdomain is not specified or the
	userdomain is the same as the hostname or domainname, then
	an address will be considered the users if it matches either
	the domainname or the hostname.  Of course, the userid must
	match too.

  5. In Message ID's
	The fully-qualified hostname is always users here.

** Setting the domain names
  To set the domain name for all Pine users on the system to be
different from what Pine figures out from DNS, set the domain name in
the "user-domain" variable in pine.conf.  To set the domain name for an
individual user, set the "user-domain" variable in his .pinerc.
The .pinerc setting overrides any other setting.
 ----*/
int
init_hostname(struct pine *ps)
{
    char hostname[MAX_ADDRESS+1], domainname[MAX_ADDRESS+1];

    getdomainnames(hostname, sizeof(hostname)-1,
		   domainname, sizeof(domainname)-1);

    if(ps->hostname)
      fs_give((void **)&ps->hostname);

    ps->hostname = cpystr(hostname);

    if(ps->localdomain)
      fs_give((void **)&ps->localdomain);

    ps->localdomain = cpystr(domainname);
    ps->userdomain  = NULL;

    if(ps->VAR_USER_DOMAIN && ps->VAR_USER_DOMAIN[0]){
        ps->maildomain = ps->userdomain = ps->VAR_USER_DOMAIN;
    }else{
#if defined(DOS) || defined(OS2)
	if(ps->VAR_USER_DOMAIN)
	  ps->blank_user_domain = 1;	/* user domain set to null string! */

        ps->maildomain = ps->localdomain[0] ? ps->localdomain : ps->hostname;
#else
        ps->maildomain = strucmp(ps->VAR_USE_ONLY_DOMAIN_NAME, "yes")
			  ? ps->hostname : ps->localdomain;
#endif
    }

    /*
     * Tell c-client what domain to use when completing unqualified
     * addresses it finds in local mailboxes.  Remember, it won't
     * affect what's to the right of '@' for unqualified addresses in
     * remote folders...
     */
    mail_parameters(NULL, SET_LOCALHOST, (void *) ps->maildomain);
    if(F_OFF(F_QUELL_MAILDOMAIN_WARNING, ps) && !strchr(ps->maildomain, '.')){
	snprintf(tmp_20k_buf, SIZEOF_20KBUF, _("Incomplete maildomain \"%s\"."),
		ps->maildomain);
	init_error(ps, SM_ORDER | SM_DING, 3, 5, tmp_20k_buf);
	strncpy(tmp_20k_buf,
	       _("Return address in mail you send may be incorrect."), SIZEOF_20KBUF);
	tmp_20k_buf[SIZEOF_20KBUF-1] = '\0';
	init_error(ps, SM_ORDER | SM_DING, 3, 5, tmp_20k_buf);
    }

    dprint((1,"User domain name being used \"%s\"\n",
               ps->userdomain == NULL ? "" : ps->userdomain));
    dprint((1,"Local Domain name being used \"%s\"\n",
               ps->localdomain ? ps->localdomain : "?"));
    dprint((1,"Host name being used \"%s\"\n",
               ps->hostname ? ps->hostname : "?"));
    dprint((1,
	       "Mail Domain name being used (by c-client too) \"%s\"\n",
               ps->maildomain ? ps->maildomain : "?"));

    if(!ps->maildomain || !ps->maildomain[0]){
#if defined(DOS) || defined(OS2)
	if(ps->blank_user_domain)
	  return(0);		/* prompt for this in send.c:dos_valid_from */
#endif
        fprintf(stderr, _("No host name or domain name set\n"));
        return(-1);
    }
    else
      return(0);
}

/*----------------------------------------------------------------------
  Make sure the default save folders exist in the default
  save context.
  ----*/
void
init_save_defaults(void)
{
    CONTEXT_S  *save_cntxt;

    if(!ps_global->VAR_DEFAULT_FCC ||
       !*ps_global->VAR_DEFAULT_FCC ||
       !ps_global->VAR_DEFAULT_SAVE_FOLDER ||
       !*ps_global->VAR_DEFAULT_SAVE_FOLDER)
      return;

    if(!(save_cntxt = default_save_context(ps_global->context_list)))
      save_cntxt = ps_global->context_list;

    if(!(folder_exists(save_cntxt, ps_global->VAR_DEFAULT_FCC) & FEX_ISFILE))
      context_create(save_cntxt, NULL, ps_global->VAR_DEFAULT_FCC);

    if(!(folder_exists(save_cntxt, ps_global->VAR_DEFAULT_SAVE_FOLDER) &
								 FEX_ISFILE))
      context_create(save_cntxt, NULL, ps_global->VAR_DEFAULT_SAVE_FOLDER);

    free_folder_list(save_cntxt);
}

/*----------------------------------------------------------------------
      Put sent-mail files in date order

   Args: a, b  -- The names of two files.  Expects names to be sent-mail-mmm-yy
                  Other names will sort in order and come before those
                  in above format.
 ----*/
int
compare_sm_files(const qsort_t *aa, const qsort_t *bb)
{
    struct sm_folder *a = (struct sm_folder *)aa,
                     *b = (struct sm_folder *)bb;

    if(a->month_num == -1 && b->month_num == -1 && a->name && b->name)
      return(strucmp(a->name, b->name));
    if(a->month_num == -1)      return(-1);
    if(b->month_num == -1)      return(1);

    return(a->month_num - b->month_num);
}

/*----------------------------------------------------------------------
      Create an ordered list of sent-mail folders and their month numbers

   Args: dir -- The directory to find the list of files in

 Result: Pointer to list of files is returned.

This list includes all files that start with "sent-mail", but not "sent-mail"
itself.
  ----*/
struct sm_folder *
get_mail_list(CONTEXT_S *list_cntxt, char *folder_base)
{
    register struct sm_folder *sm  = NULL;
    struct sm_folder          *sml = NULL;
    char                      *filename;
    int                        i, folder_base_len;
    int                        max_files;
    char		       searchname[MAXPATH+1];

    if((folder_base_len = strlen(folder_base)) == 0 || !list_cntxt){
	sml = (struct sm_folder *) fs_get(sizeof(struct sm_folder));
	memset((void *)sml, 0, sizeof(struct sm_folder));
        return(sml);
    }

#ifdef	DOS
    if(*list_cntxt->context != '{'){	/* NOT an IMAP collection! */
	snprintf(searchname, sizeof(searchname), "%4.4s*", folder_base);
	folder_base_len = strlen(searchname) - 1;
    }
    else
#endif
    snprintf(searchname, sizeof(searchname), "%.*s*", sizeof(searchname)-2, folder_base);

    build_folder_list(NULL, list_cntxt, searchname, NULL, BFL_FLDRONLY);

    max_files = MIN(MAX(0, folder_total(FOLDERS(list_cntxt))), 5000);
    sml = sm = (struct sm_folder *) fs_get(sizeof(struct sm_folder)*(max_files+1));
    memset((void *)sml, 0, sizeof(struct sm_folder) * (max_files+1));

    for(i = 0; i < folder_total(FOLDERS(list_cntxt)); i++){
	filename = folder_entry(i, FOLDERS(list_cntxt))->name;
#ifdef	DOS
        if(struncmp(filename, folder_base, folder_base_len) == 0
           && strucmp(filename, folder_base)){

	if(*list_cntxt->context != '{'){
	    int j;
	    for(j = 0; j < 4; j++)
	      if(!isdigit((unsigned char)filename[folder_base_len + j]))
		break;

	   if(j < 4)		/* not proper date format! */
	     continue;		/* keep trying */
	}
#else
#ifdef OS2
        if(strnicmp(filename, folder_base, folder_base_len) == 0
           && stricmp(filename, folder_base)){
#else
        if(strncmp(filename, folder_base, folder_base_len) == 0
#ifndef _WINDOWS
	   && filename[folder_base_len] != list_cntxt->dir->delim
#endif
           && strcmp(filename, folder_base)){
#endif
#endif
	    sm->name = cpystr(filename);
#ifdef	DOS
	    if(*list_cntxt->context != '{'){ /* NOT an IMAP collection! */
		sm->month_num  = (sm->name[folder_base_len] - '0') * 10;
		sm->month_num += sm->name[folder_base_len + 1] - '0';
	    }
	    else
#endif
            sm->month_num = month_num(sm->name + (size_t)folder_base_len + 1);
            sm++;
            if(sm >= &sml[max_files])
               break; /* Too many files, ignore the rest ; shouldn't occur */
        }
    }

    /* anything to sort?? */
    if(sml->name && *(sml->name) && (sml+1)->name && *((sml+1)->name)){
	qsort(sml,
	      sm - sml,
	      sizeof(struct sm_folder),
	      compare_sm_files);
    }

    return(sml);
}

int
check_prune_time(time_t *now, struct tm **tm_now)
{
    char tmp[50];

    *now = time((time_t *) 0);
    *tm_now = localtime(now);

    /*
     * If the last time we did this is blank (as if pine's run for
     * first time), don't go thru list asking, but just note it for
     * the next time...
     */
    if(ps_global->VAR_LAST_TIME_PRUNE_QUESTION == NULL){
	ps_global->last_expire_year = (*tm_now)->tm_year;
	ps_global->last_expire_month = (*tm_now)->tm_mon;
	snprintf(tmp, sizeof(tmp), "%d.%d", ps_global->last_expire_year,
		ps_global->last_expire_month + 1);
	set_variable(V_LAST_TIME_PRUNE_QUESTION, tmp, 1, 1, Main);
	return(0);
    }

    if(ps_global->last_expire_year != -1 &&
      ((*tm_now)->tm_year <  ps_global->last_expire_year ||
       ((*tm_now)->tm_year == ps_global->last_expire_year &&
        (*tm_now)->tm_mon <= ps_global->last_expire_month)))
      return(0);

    return(1);
}

int
first_run_of_month(void)
{
    time_t     now;
    struct tm *tm_now;

    now = time((time_t *) 0);
    tm_now = localtime(&now);

    if(ps_global->last_expire_year == -1 ||
      (tm_now->tm_year <  ps_global->last_expire_year ||
       (tm_now->tm_year == ps_global->last_expire_year &&
        tm_now->tm_mon <= ps_global->last_expire_month)))
      return(0);

    return(1);
}

int
first_run_of_year(void)
{
    time_t     now;
    struct tm *tm_now;

    now = time((time_t *) 0);
    tm_now = localtime(&now);

    if(ps_global->last_expire_year == -1 ||
      (tm_now->tm_year <=  ps_global->last_expire_year))
      return(0);

    return(1);
}

/*
 * prune_move_folder - rename folder in context and delete old copy
 * Returns -1 if unsuccessful.
 */
int
prune_move_folder(char *oldpath, char *newpath, CONTEXT_S *prune_cntxt)
{
    char spath[MAXPATH+1];

    strncpy(spath, oldpath, sizeof(spath)-1);
    spath[sizeof(spath)-1] = '\0';

    /*--- User says OK to rename ---*/
    dprint((5, "rename \"%s\" to \"%s\"\n",
	   spath ? spath : "?", newpath ? newpath : "?"));
    q_status_message1(SM_ORDER, 1, 3,
		      /* TRANSLATORS: arg is a filename */
		      _("Renaming \"%s\" at start of month"),
		      pretty_fn(spath ? spath : "?"));

    if(!context_rename(prune_cntxt, NULL, spath, newpath)){
        q_status_message2(SM_ORDER | SM_DING, 3, 4,
			  /* TRANSLATORS: 1st arg is filename, 2nd is error message */
			  _("Error renaming \"%s\": %s"),
                          pretty_fn(spath ? spath : "?"),
			  error_description(errno));
        dprint((1, "Error renaming %s to %s: %s\n",
                   spath ? spath : "?", newpath ? newpath : "?",
		   error_description(errno)));
        display_message('x');
        return -1;
    }

    context_create(prune_cntxt, NULL, spath);

    return 0;
}


text:
<?php
require_once(dirname(__FILE__) . "/../Base/MixpanelBase.php");

/**
 * Provides some base methods for use by a Consumer implementation
 */
abstract class ConsumerStrategies_AbstractConsumer extends Base_MixpanelBase {

    /**
     * Creates a new AbstractConsumer
     * @param array $options
     */
    function __construct($options = array()) {

        parent::__construct($options);

        if ($this->_debug()) {
            $this->_log("Instantiated new Consumer");
        }

    }

    /**
     * Encode an array to be persisted
     * @param array $params
     * @return string
     */
    protected function _encode($params) {
        return base64_encode(json_encode($params));
    }

    /**
     * Handles errors that occur in a consumer
     * @param $code
     * @param $msg
     */
    protected function _handleError($code, $msg) {
        if (isset($this->_options['error_callback'])) {
            $handler = $this->_options['error_callback'];
            call_user_func($handler, $code, $msg);
        }

        if ($this->_debug()) {
            $arr = debug_backtrace();
            $class = get_class($arr[0]['object']);
            $line = $arr[0]['line'];
            error_log ( "[ $class - line $line ] : " . print_r($msg, true) );
        }
    }

    /**
     * Persist a batch of messages in whatever way the implementer sees fit
     * @param array $batch an array of messages to consume
     * @return boolean success or fail
     */
    abstract function persist($batch);
}


text:
import React from 'react';
import { Icon } from '../Icon/Icon';
import { IconName } from '../../types/icon';
import { css, cx } from '@emotion/css';

// @ts-ignore
import RCCascader from 'rc-cascader';
import { CascaderOption } from '../Cascader/Cascader';
import { onChangeCascader, onLoadDataCascader } from '../Cascader/optionMappings';
import { stylesFactory, useTheme2 } from '../../themes';
import { GrafanaTheme2 } from '../../../data';
import './ButtonCascader.less'

export interface ButtonCascaderProps {
  options: CascaderOption[];
  children: string;
  icon?: IconName;
  disabled?: boolean;
  value?: string[];
  fieldNames?: { label: string; value: string; children: string };
  loadData?: (selectedOptions: CascaderOption[]) => void;
  onChange?: (value: string[], selectedOptions: CascaderOption[]) => void;
  onPopupVisibleChange?: (visible: boolean) => void;
  className?: string;
}

const getStyles = stylesFactory((theme: GrafanaTheme2) => {
  return {
    popup: css`
      label: popup;
      z-index: ${theme.zIndex.dropdown};
    `,
    icons: {
      right: css`
        margin: 1px 0 0 4px;
      `,
      left: css`
        margin: -1px 4px 0 0;
      `,
    },
  };
});

export const ButtonCascader: React.FC<ButtonCascaderProps> = (props) => {
  const { onChange, className, loadData, icon, ...rest } = props;
  const theme = useTheme2();
  const styles = getStyles(theme);

  return (
    <RCCascader
      onChange={onChangeCascader(onChange)}
      loadData={onLoadDataCascader(loadData)}
      popupClassName={styles.popup}
      {...rest}
      expandIcon={null}
    >
      <button className={cx('gf-form-label', className)} disabled={props.disabled}>
        {icon && <Icon name={icon} className={styles.icons.left} />}
        {props.children}
        <Icon name="angle-down" className={styles.icons.right} />
      </button>
    </RCCascader>
  );
};

ButtonCascader.displayName = 'ButtonCascader';


text:
namespace pythonic
{
  namespace numpy
  {
    namespace random
    {
      template <size_t S, class P>
      types::ndarray<long, S> choice(long max,
                                     types::array<long, S> const &shape,
                                     bool replace, P const &p);

      template <class P>
      types::ndarray<long, 1> choice(long max, long size, bool replace, P &&p);

      template <class T>
      auto choice(long max, T &&size)
          -> decltype(randint(0, max, std::forward<T>(size)));

      long choice(long max);

      template <class T>
      typename T::dtype choice(T const &a);

      template <class T, size_t S>
      types::ndarray<typename T::dtype, S>
      choice(T const &a, types::array<long, S> const &shape);

      template <class T>
      types::ndarray<typename T::dtype, 1> choice(T &&a, long size);

      template <class T, size_t S, class P>
      types::ndarray<typename T::dtype, S>
      choice(T const &a, types::array<long, S> const &shape, bool replace,
             P const &p);

      template <class T, class P>
      types::ndarray<typename T::dtype, 1> choice(T &&a, long size,
                                                  bool replace, P &&p);

      PROXY_DECL(pythonic::numpy::random, choice);
    }
  }
}

#endif


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Distrubute Social Network</title>

    <link href="{{url_for('static',filename='css/bootstrap.min.css')}}" rel="stylesheet">
     <link href="{{url_for('static',filename='css/main.css')}}" rel="stylesheet">
     <link href="{{url_for('static',filename='css/admin.css')}}" rel="stylesheet">

     <link href="{{url_for('static',filename='css/struct.css')}}" rel="stylesheet">
     <link href="{{url_for('static',filename='css/permission.css')}}" rel="stylesheet">

Panel heading without title

#

Author Name

  All Authors

    <SELECT id="all_author" SIZE="8" MULTIPLE>
      <OPTION SELECTED> Apples
      <OPTION> Bananas
      <OPTION> Oranges
      <OPTION> Watermelon
      <OPTION> Kiwi
      <OPTION> Cantaloupe
      <OPTION> Strawberries
    </SELECT>

    <button type="button" class="btn btn-default btn-xs"id="delete_author">

    </button>
    <button type="button" class="btn btn-default btn-xs"id="add_author">

    </button>

Post

Firends

  <SELECT id="post_group" SIZE="8" MULTIPLE></select>
  <SELECT id="friend_group" SIZE="8" MULTIPLE></select>

.right


text:
programming-for-funsies
=======================

Repo to store work / solutions for random programming challenges. (e.g /r/dailyprogrammer and codingforinterviews)


text:
import com.hazelcast.config.EventJournalConfig;
import com.hazelcast.config.SerializerConfig;
import com.hazelcast.jet.Jet;
import com.hazelcast.jet.JetInstance;
import com.hazelcast.jet.aggregate.AggregateOperation;
import com.hazelcast.jet.aggregate.AggregateOperation1;
import com.hazelcast.jet.config.JetConfig;
import com.hazelcast.jet.datamodel.TimestampedEntry;
import com.hazelcast.jet.function.DistributedBiConsumer;
import com.hazelcast.jet.function.DistributedComparator;
import com.hazelcast.jet.pipeline.Pipeline;
import com.hazelcast.jet.pipeline.Sinks;
import com.hazelcast.jet.pipeline.Sources;
import com.hazelcast.map.journal.EventJournalMapEvent;
import serializer.PriorityQueueSerializer;
import tradegenerator.Trade;
import tradegenerator.TradeGenerator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;

import static com.hazelcast.jet.aggregate.AggregateOperations.allOf;
import static com.hazelcast.jet.aggregate.AggregateOperations.linearTrend;
import static com.hazelcast.jet.function.DistributedFunctions.alwaysTrue;
import static com.hazelcast.jet.impl.util.Util.checkSerializable;
import static com.hazelcast.jet.pipeline.JournalInitialPosition.START_FROM_CURRENT;
import static com.hazelcast.jet.pipeline.WindowDefinition.sliding;
import static com.hazelcast.jet.pipeline.WindowDefinition.tumbling;

/**
 * This sample shows how to cascade aggregations. It first calculates the
 * linear trend of each stock's price over time, then finds 5 stocks
 * with the highest price growth and 5 stocks with the highest price drop.
 *

 * It uses two windowing aggregations. First one uses a sliding window (to
 * smoothen the input) and the second one uses a tumbling window with length
 * equal to the sliding step of the first aggregation.
 *

 * Since the trade price is generated randomly, the trend tends to be pretty
 * close to 0. The more trades are accumulated into the window the closer to 0
 * the trend is.
 *
 *
Serialization

 *
 * This sample also demonstrates the use of Hazelcast serialization. The class
 * {@link java.util.PriorityQueue} is not supported by Hazelcast serialization
 * out of the box, so Java serialization would be used. We add a custom
 * serializer to the config.
 */
public class TopNStocks {

    private static final int JOB_DURATION = 60;
    private static final String TRADES = "trades";

    public static void main(String[] args) {
        System.setProperty("hazelcast.logging.type", "log4j");

        JetConfig config = new JetConfig();
        // add custom serializer for PriorityQueue
        config.getHazelcastConfig().getSerializationConfig().addSerializerConfig(
                new SerializerConfig()
                        .setImplementation(new PriorityQueueSerializer())
                        .setTypeClass(PriorityQueue.class));
        // enable event journal for trades map
        config.getHazelcastConfig().addEventJournalConfig(new EventJournalConfig()
                .setMapName(TRADES)
                .setEnabled(true));

        JetInstance[] instances = new JetInstance[2];
        Arrays.parallelSetAll(instances, i -> Jet.newJetInstance(config));
        try {
            instances[0].newJob(buildPipeline());
            // the Trades will be inserted to the map, from where they are picked up by the mapJournal source
            TradeGenerator.generate(500, instances[0].getMap(TRADES), 6_000, JOB_DURATION);
        } finally {
            Jet.shutdownAll();
        }
    }

    private static Pipeline buildPipeline() {
        Pipeline p = Pipeline.create();

        DistributedComparator<TimestampedEntry<String, Double>> comparingValue =
                DistributedComparator.comparing(TimestampedEntry<String, Double>::getValue);
        // Calculate two operations in single step: top-n largest and top-n smallest values
        AggregateOperation1<TimestampedEntry<String, Double>, ?, TopNResult> aggrOpTopN = allOf(
                topNAggregation(5, comparingValue),
                topNAggregation(5, comparingValue.reversed()),
                TopNResult::new);

        p.drawFrom(Sources.<Trade, Integer, Trade>mapJournal(
                TRADES, alwaysTrue(), EventJournalMapEvent::getNewValue, START_FROM_CURRENT))
         .addTimestamps(Trade::getTime, 1_000)
         .groupingKey(Trade::getTicker)
         .window(sliding(10_000, 1_000))
         // aggregate to create trend for each ticker
         .aggregate(linearTrend(Trade::getTime, Trade::getPrice))
         .window(tumbling(1_000))
         // 2nd aggregation: choose top-N trends from previous aggregation
         .aggregate(aggrOpTopN)
         .drainTo(Sinks.logger());

        return p;
    }

    public static <T> AggregateOperation1<T, ?, List<T>> topNAggregation(
            int n, DistributedComparator<? super T> comparator
    ) {
        checkSerializable(comparator, "comparator");
        DistributedComparator<? super T> comparatorReversed = comparator.reversed();
        DistributedBiConsumer<PriorityQueue<T>, T> accumulateFn = (PriorityQueue<T> a, T i) -> {
            if (a.size() == n) {
                if (comparator.compare(i, a.peek()) <= 0) {
                    // the new item is smaller or equal to the smallest in queue
                    return;
                }
                a.poll();
            }
            a.offer(i);
        };
        return AggregateOperation
                .withCreate(() -> new PriorityQueue<T>(n, comparator))
                .andAccumulate(accumulateFn)
                .andCombine((a1, a2) -> {
                    for (T t : a2) {
                        accumulateFn.accept(a1, t);
                    }
                })
                .andExportFinish(a -> {
                    ArrayList<T> res = new ArrayList<>(a);
                    res.sort(comparatorReversed);
                    return res;
                });
    }

    public static final class TopNResult {
        private final List<TimestampedEntry<String, Double>> topIncrease;
        private final List<TimestampedEntry<String, Double>> topDecrease;

        public TopNResult(List<TimestampedEntry<String, Double>> topIncrease,
                          List<TimestampedEntry<String, Double>> topDecrease) {
            this.topIncrease = topIncrease;
            this.topDecrease = topDecrease;
        }

        public List<TimestampedEntry<String, Double>> getTopIncrease() {
            return topIncrease;
        }

        public List<TimestampedEntry<String, Double>> getTopDecrease() {
            return topDecrease;
        }

        @Override
        public String toString() {
            return "TopNResult{" +
                    "topIncrease=" + topIncrease +
                    ", topDecrease=" + topDecrease +
                    '}';
        }
    }
}


text:
PATH=${PATH}

# Kills software updating service that consumes large amounts of bandwidth.
kill-agent() {
	launchctl unload /System/Library/LaunchAgents/com.apple.nsurlsessiond.plist
}

kill-daemon() {
	launchctl unload /System/Library/LaunchDaemons/com.apple.nsurlstoraged.plist
	launchctl unload /System/Library/LaunchDaemons/com.apple.nsurlsessiond.plist
}

if [[ "$(id -u)" == "0" ]]; then
	kill-agent
	kill-daemon
else
	echo "This must be run as root"
fi
exit 0


text:
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/param.h>
#include <sys/queue.h>
#include <libprocstat.h>

#include <osquery/core/core.h>
#include <osquery/core/tables.h>
#include <osquery/logger/logger.h>
#include <osquery/tables/system/freebsd/procstat.h>

namespace osquery {
namespace tables {

// Heavily inspired by procstat(1) on FreeBSD.
std::pair<std::string, int>& sockaddr_to_pair(struct sockaddr_storage* sstor) {
  char buffer[INET6_ADDRSTRLEN] = {0};
  struct sockaddr_in6* sin6 = nullptr;
  struct sockaddr_in* sin = nullptr;
  struct sockaddr_un* sun = nullptr;

  static std::pair<std::string, int> addr;
  switch (sstor->ss_family) {
    case AF_LOCAL:
      sun = (struct sockaddr_un*) sstor;
      addr = std::make_pair(std::string(sun->sun_path), 0);
      break;
    case AF_INET:
      sin = (struct sockaddr_in*) sstor;
      addr = std::make_pair(std::string(inet_ntoa(sin->sin_addr)),
                            ntohs(sin->sin_port));
      break;
    case AF_INET6:
      sin6 = (struct sockaddr_in6*) sstor;
      inet_ntop(AF_INET6, &sin6->sin6_addr, buffer, sizeof(buffer));
      addr = std::make_pair(std::string(buffer), ntohs(sin6->sin6_port));
      break;
    default:
      addr = std::make_pair(std::string(""), 0);
      break;
  }

  return addr;
}

void genSockets(struct procstat* pstat,
                struct kinfo_proc* proc,
                QueryData &results) {
  Row r;
  struct filestat_list* files = nullptr;
  struct filestat* file = nullptr;
  struct sockstat sock;
  int error;
  std::pair<std::string, int> addr;

  files = procstat_getfiles(pstat, proc, 0);
  if (files == nullptr) {
    return;
  }

  STAILQ_FOREACH(file, files, next) {
    // Skip files that aren't sockets.
    if (file->fs_type != PS_FST_TYPE_SOCKET) {
      continue;
    }

    error = procstat_get_socket_info(pstat, file, &sock, nullptr);
    if (error != 0) {
      continue;
    }

    r["pid"] = INTEGER(proc->ki_pid);
    r["socket"] = INTEGER(file->fs_fd);
    r["family"] = INTEGER(sock.dom_family);
    r["protocol"] = INTEGER(sock.proto);

    addr = sockaddr_to_pair(&(sock.sa_local));
    r["local_address"] = TEXT(addr.first);
    r["local_port"] = INTEGER(addr.second);

    addr = sockaddr_to_pair(&(sock.sa_peer));
    r["remote_address"] = TEXT(addr.first);
    r["remote_port"] = INTEGER(addr.second);

    results.push_back(r);
  }

  procstat_freefiles(pstat, files);
}

QueryData genOpenSockets(QueryContext &context) {
  QueryData results;
  struct kinfo_proc* procs = nullptr;
  struct procstat* pstat = nullptr;

  auto cnt = getProcesses(context, &pstat, &procs);

  for (size_t i = 0; i < cnt; i++) {
    genSockets(pstat, &procs[i], results);
  }

  procstatCleanup(pstat, procs);

  return results;
}
}
}


text:
"""Table definitions for the FERC Form 1 data group."""
from typing import Any, Dict

from pudl.metadata.codes import CODE_METADATA

RESOURCE_METADATA: Dict[str, Dict[str, Any]] = {
    "accumulated_depreciation_ferc1": {
        "description": "Balances and changes to FERC Accumulated Provision for Depreciation.",
        "schema": {
            "fields": [
                "utility_id_ferc1",
                "report_year",
                "record_id",
                "line_id",
                "total",
                "electric_plant",
                "future_plant",
                "leased_plant",
            ],
            "primary_key": ["utility_id_ferc1", "report_year", "line_id"],
        },
        "sources": ["ferc1"],
        "etl_group": "ferc1_disabled",
        "field_namespace": "ferc1",
    },
    "ferc_accounts": {
        "description": "Account numbers from the FERC Uniform System of Accounts for Electric Plant, which is defined in Code of Federal Regulations (CFR) Title 18, Chapter I, Subchapter C, Part 101. (See e.g. https://www.law.cornell.edu/cfr/text/18/part-101).",
        "schema": {
            "fields": ["ferc_account_id", "ferc_account_description"],
            "primary_key": ["ferc_account_id"],
        },
        "sources": ["ferc1"],
        "etl_group": "static_ferc1",
        "field_namespace": "ferc1",
    },
    "ferc_depreciation_lines": {
        "description": "PUDL assigned FERC Form 1 line identifiers and long descriptions from FERC Form 1 page 219, Accumulated Provision for Depreciation of Electric Utility Plant (Account 108).",
        "schema": {
            "fields": ["line_id", "ferc_account_description"],
            "primary_key": ["line_id"],
            "foreign_key_rules": {"fields": [["line_id"]]},
        },
        "sources": ["ferc1"],
        "etl_group": "static_ferc1",
        "field_namespace": "ferc1",
    },
    "fuel_ferc1": {
        "description": "Annual fuel cost and quanitiy for steam plants with a capacity of 25+ MW, internal combustion and gas-turbine plants of 10+ MW, and all nuclear plants. As reported on page 402 of FERC Form 1 and extracted from the f1_fuel table in FERC's FoxPro Database.",
        "schema": {
            "fields": [
                "record_id",
                "utility_id_ferc1",
                "report_year",
                "plant_name_ferc1",
                "fuel_type_code_pudl",
                "fuel_units",
                "fuel_consumed_units",
                "fuel_mmbtu_per_unit",
                "fuel_cost_per_unit_burned",
                "fuel_cost_per_unit_delivered",
                "fuel_cost_per_mmbtu",
            ],
        },
        "sources": ["ferc1"],
        "etl_group": "ferc1",
        "field_namespace": "ferc1",
    },
    "plant_in_service_ferc1": {
        "description": "Balances and changes to FERC Electric Plant in Service accounts, as reported on FERC Form 1. Data originally from the f1_plant_in_srvce table in FERC's FoxPro database. Account numbers correspond to the FERC Uniform System of Accounts for Electric Plant, which is defined in Code of Federal Regulations (CFR) Title 18, Chapter I, Subchapter C, Part 101. (See e.g. https://www.law.cornell.edu/cfr/text/18/part-101). Each FERC respondent reports starting and ending balances for each account annually. Balances are organization wide, and are not broken down on a per-plant basis. End of year balance should equal beginning year balance plus the sum of additions, retirements, adjustments, and transfers.",
        "schema": {
            "fields": [
                "utility_id_ferc1",
                "report_year",
                "amount_type",
                "record_id",
                "distribution_acct360_land",
                "distribution_acct361_structures",
                "distribution_acct362_station_equip",
                "distribution_acct363_storage_battery_equip",
                "distribution_acct364_poles_towers",
                "distribution_acct365_overhead_conductors",
                "distribution_acct366_underground_conduit",
                "distribution_acct367_underground_conductors",
                "distribution_acct368_line_transformers",
                "distribution_acct369_services",
                "distribution_acct370_meters",
                "distribution_acct371_customer_installations",
                "distribution_acct372_leased_property",
                "distribution_acct373_street_lighting",
                "distribution_acct374_asset_retirement",
                "distribution_total",
                "electric_plant_in_service_total",
                "electric_plant_purchased_acct102",
                "electric_plant_sold_acct102",
                "experimental_plant_acct103",
                "general_acct389_land",
                "general_acct390_structures",
                "general_acct391_office_equip",
                "general_acct392_transportation_equip",
                "general_acct393_stores_equip",
                "general_acct394_shop_equip",
                "general_acct395_lab_equip",
                "general_acct396_power_operated_equip",
                "general_acct397_communication_equip",
                "general_acct398_misc_equip",
                "general_acct399_1_asset_retirement",
                "general_acct399_other_property",
                "general_subtotal",
                "general_total",
                "hydro_acct330_land",
                "hydro_acct331_structures",
                "hydro_acct332_reservoirs_dams_waterways",
                "hydro_acct333_wheels_turbines_generators",
                "hydro_acct334_accessory_equip",
                "hydro_acct335_misc_equip",
                "hydro_acct336_roads_railroads_bridges",
                "hydro_acct337_asset_retirement",
                "hydro_total",
                "intangible_acct301_organization",
                "intangible_acct302_franchises_consents",
                "intangible_acct303_misc",
                "intangible_total",
                "major_electric_plant_acct101_acct106_total",
                "nuclear_acct320_land",
                "nuclear_acct321_structures",
                "nuclear_acct322_reactor_equip",
                "nuclear_acct323_turbogenerators",
                "nuclear_acct324_accessory_equip",
                "nuclear_acct325_misc_equip",
                "nuclear_acct326_asset_retirement",
                "nuclear_total",
                "other_acct340_land",
                "other_acct341_structures",
                "other_acct342_fuel_accessories",
                "other_acct343_prime_movers",
                "other_acct344_generators",
                "other_acct345_accessory_equip",
                "other_acct346_misc_equip",
                "other_acct347_asset_retirement",
                "other_total",
                "production_total",
                "rtmo_acct380_land",
                "rtmo_acct381_structures",
                "rtmo_acct382_computer_hardware",
                "rtmo_acct383_computer_software",
                "rtmo_acct384_communication_equip",
                "rtmo_acct385_misc_equip",
                "rtmo_total",
                "steam_acct310_land",
                "steam_acct311_structures",
                "steam_acct312_boiler_equip",
                "steam_acct313_engines",
                "steam_acct314_turbogenerators",
                "steam_acct315_accessory_equip",
                "steam_acct316_misc_equip",
                "steam_acct317_asset_retirement",
                "steam_total",
                "transmission_acct350_land",
                "transmission_acct352_structures",
                "transmission_acct353_station_equip",
                "transmission_acct354_towers",
                "transmission_acct355_poles",
                "transmission_acct356_overhead_conductors",
                "transmission_acct357_underground_conduit",
                "transmission_acct358_underground_conductors",
                "transmission_acct359_1_asset_retirement",
                "transmission_acct359_roads_trails",
                "transmission_total",
            ],
            "primary_key": ["utility_id_ferc1", "report_year", "amount_type"],
        },
        "sources": ["ferc1"],
        "etl_group": "ferc1",
        "field_namespace": "ferc1",
    },
    "plants_ferc1": {
        "description": "FERC 1 Plants and their associated manually assigned PUDL Plant IDs",
        "schema": {
            "fields": ["utility_id_ferc1", "plant_name_ferc1", "plant_id_pudl"],
            "primary_key": ["utility_id_ferc1", "plant_name_ferc1"],
            "foreign_key_rules": {
                "fields": [
                    ["utility_id_ferc1", "plant_name_ferc1"],
                ],
            },
        },
        "sources": ["ferc1"],
        "etl_group": "glue",
        "field_namespace": "ferc1",
    },
    "plants_hydro_ferc1": {
        "description": "Hydroelectric generating plant statistics for large plants. Large plants have an installed nameplate capacity of more than 10 MW. As reported on FERC Form 1, pages 406-407, and extracted from the f1_hydro table in FERC's FoxPro database.",
        "schema": {
            "fields": [
                "record_id",
                "utility_id_ferc1",
                "report_year",
                "plant_name_ferc1",
                "project_num",
                "plant_type",
                "construction_type",
                "construction_year",
                "installation_year",
                "capacity_mw",
                "peak_demand_mw",
                "plant_hours_connected_while_generating",
                "net_capacity_favorable_conditions_mw",
                "net_capacity_adverse_conditions_mw",
                "avg_num_employees",
                "net_generation_mwh",
                "capex_land",
                "capex_structures",
                "capex_facilities",
                "capex_equipment",
                "capex_roads",
                "asset_retirement_cost",
                "capex_total",
                "capex_per_mw",
                "opex_operations",
                "opex_water_for_power",
                "opex_hydraulic",
                "opex_electric",
                "opex_generation_misc",
                "opex_rents",
                "opex_engineering",
                "opex_structures",
                "opex_dams",
                "opex_plant",
                "opex_misc_plant",
                "opex_total",
                "opex_per_mwh",
            ],
        },
        "sources": ["ferc1"],
        "etl_group": "ferc1",
        "field_namespace": "ferc1",
    },
    "plants_pumped_storage_ferc1": {
        "description": "Generating plant statistics for hydroelectric pumped storage plants with an installed nameplate capacity of 10+ MW. As reported on page 408 of FERC Form 1 and extracted from the f1_pumped_storage table in FERC's FoxPro Database.",
        "schema": {
            "fields": [
                "record_id",
                "utility_id_ferc1",
                "report_year",
                "plant_name_ferc1",
                "project_num",
                "construction_type",
                "construction_year",
                "installation_year",
                "capacity_mw",
                "peak_demand_mw",
                "plant_hours_connected_while_generating",
                "plant_capability_mw",
                "avg_num_employees",
                "net_generation_mwh",
                "energy_used_for_pumping_mwh",
                "net_load_mwh",
                "capex_land",
                "capex_structures",
                "capex_facilities",
                "capex_wheels_turbines_generators",
                "capex_equipment_electric",
                "capex_equipment_misc",
                "capex_roads",
                "asset_retirement_cost",
                "capex_total",
                "capex_per_mw",
                "opex_operations",
                "opex_water_for_power",
                "opex_pumped_storage",
                "opex_electric",
                "opex_generation_misc",
                "opex_rents",
                "opex_engineering",
                "opex_structures",
                "opex_dams",
                "opex_plant",
                "opex_misc_plant",
                "opex_production_before_pumping",
                "opex_pumping",
                "opex_total",
                "opex_per_mwh",
            ],
        },
        "sources": ["ferc1"],
        "etl_group": "ferc1",
        "field_namespace": "ferc1",
    },
    "plants_small_ferc1": {
        "description": "Generating plant statistics for steam plants with less than 25 MW installed nameplate capacity and internal combustion plants, gas turbine-plants, conventional hydro plants, and pumped storage plants with less than 10 MW installed nameplate capacity. As reported on FERC Form 1 pages 410-411, and extracted from the FERC FoxPro database table f1_gnrt_plant.",
        "schema": {
            "fields": [
                "record_id",
                "utility_id_ferc1",
                "report_year",
                "plant_name_clean",
                "plant_name_ferc1",
                "plant_type",
                "ferc_license_id",
                "construction_year",
                "capacity_mw",
                "peak_demand_mw",
                "net_generation_mwh",
                "total_cost_of_plant",
                "capex_per_mw",
                "opex_total",
                "opex_fuel",
                "opex_maintenance",
                "fuel_type",
                "fuel_cost_per_mmbtu",
            ],
        },
        "sources": ["ferc1"],
        "etl_group": "ferc1",
        "field_namespace": "ferc1",
    },
    "plants_steam_ferc1": {
        "description": "Generating plant statistics for steam plants with a capacity of 25+ MW, internal combustion and gas-turbine plants of 10+ MW, and all nuclear plants. As reported on page 402 of FERC Form 1 and extracted from the f1_gnrt_plant table in FERC's FoxPro Database.",
        "schema": {
            "fields": [
                "record_id",
                "utility_id_ferc1",
                "report_year",
                "plant_id_ferc1",
                "plant_name_ferc1",
                "plant_type",
                "construction_type",
                "construction_year",
                "installation_year",
                "capacity_mw",
                "peak_demand_mw",
                "plant_hours_connected_while_generating",
                "plant_capability_mw",
                "water_limited_capacity_mw",
                "not_water_limited_capacity_mw",
                "avg_num_employees",
                "net_generation_mwh",
                "capex_land",
                "capex_structures",
                "capex_equipment",
                "capex_total",
                "capex_per_mw",
                "opex_operations",
                "opex_fuel",
                "opex_coolants",
                "opex_steam",
                "opex_steam_other",
                "opex_transfer",
                "opex_electric",
                "opex_misc_power",
                "opex_rents",
                "opex_allowances",
                "opex_engineering",
                "opex_structures",
                "opex_boiler",
                "opex_plants",
                "opex_misc_steam",
                "opex_production_total",
                "opex_per_mwh",
                "asset_retirement_cost",
            ],
        },
        "sources": ["ferc1"],
        "etl_group": "ferc1",
        "field_namespace": "ferc1",
    },
    "power_purchase_types_ferc1": {
        "description": "Coding table defining different types of electricity power purchases.",
        "schema": {
            "fields": ["code", "label", "description"],
            "primary_key": ["code"],
            "foreign_key_rules": {"fields": [["purchase_type_code"]]},
        },
        "encoder": CODE_METADATA["power_purchase_types_ferc1"],
        "sources": ["ferc1"],
        "etl_group": "static_ferc1",
        "field_namespace": "ferc1",
    },
    "purchased_power_ferc1": {
        "description": "Purchased Power (Account 555) including power exchanges (i.e. transactions involving a balancing of debits and credits for energy, capacity, etc.) and any settlements for imbalanced exchanges. Reported on pages 326-327 of FERC Form 1. Extracted from the f1_purchased_pwr table in FERC's FoxPro database.",
        "schema": {
            "fields": [
                "record_id",
                "utility_id_ferc1",
                "report_year",
                "seller_name",
                "purchase_type_code",
                "tariff",
                "billing_demand_mw",
                "non_coincident_peak_demand_mw",
                "coincident_peak_demand_mw",
                "purchased_mwh",
                "received_mwh",
                "delivered_mwh",
                "demand_charges",
                "energy_charges",
                "other_charges",
                "total_settlement",
            ]
        },
        "sources": ["ferc1"],
        "etl_group": "ferc1",
        "field_namespace": "ferc1",
    },
    "utilities_ferc1": {
        "description": "This table maps the manually assigned PUDL utility ID to a FERC respondent ID, enabling a connection between the FERC and EIA data sets. It also stores the utility name associated with the FERC respondent ID. Those values originate in the f1_respondent_id table in FERC's FoxPro database, which is stored in a file called F1_1.DBF. This table is generated from a spreadsheet stored in the PUDL repository: src/package_data/glue/pudl_id_mapping.xlsx",
        "schema": {
            "fields": ["utility_id_ferc1", "utility_name_ferc1", "utility_id_pudl"],
            "primary_key": ["utility_id_ferc1"],
            "foreign_key_rules": {"fields": [["utility_id_ferc1"]]},
        },
        "sources": ["ferc1"],
        "etl_group": "glue",
        "field_namespace": "ferc1",
    },
}
"""
FERC Form 1 resource attributes by PUDL identifier (``resource.name``).

Keys are in alphabetical order.

See :func:`pudl.metadata.helpers.build_foreign_keys` for the expected format of
``foreign_key_rules``.
"""


text:
package i5.las2peer.tools;

import static org.junit.Assert.*;

import org.junit.Test;

public class SimpleToolsTest {

	@Test
	public void testJoin() {
		assertEquals ( "", SimpleTools.join ( null, "abc"));
		assertEquals ( "", SimpleTools.join( new Object[0], "dkefde"));

		assertEquals ( "a, b, c", SimpleTools.join( new Object[]{"a",  'b', "c"}, ", " ));

		assertEquals ("10.20.30", SimpleTools.join( new Integer[]{10,20,30}, ".") );
	}

	@Test
	public void testRepeat () {
		assertEquals ( "", SimpleTools.repeat( "", 11));
		assertEquals ( "", SimpleTools.repeat( "adwdw", 0));
		assertEquals ( "", SimpleTools.repeat( "adwdw", -10));

		assertNull ( SimpleTools.repeat( null,  100 ));

		assertEquals ( "xxxx", SimpleTools.repeat("x",  4));

		assertEquals ( "101010", SimpleTools.repeat(10,  3));
	}

}


text:
import { LyThemeModule } from './theme.module';

describe('LyThemeModule', () => {
  let themeModule: LyThemeModule;

  beforeEach(() => {
    themeModule = new LyThemeModule();
  });

  it('should create an instance', () => {
    expect(themeModule).toBeTruthy();
  });
});


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

package com.google.api.services.compute.model;

/**
 * Message containing what to include in the cache key for a request for Cloud CDN.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

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

  /**
   * If true, requests to different hosts will be cached separately.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Boolean includeHost;

  /**
   * Allows HTTP request headers (by name) to be used in the cache key.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<java.lang.String> includeHttpHeaders;

  /**
   * Allows HTTP cookies (by name) to be used in the cache key. The name=value pair will be used in
   * the cache key Cloud CDN generates.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<java.lang.String> includeNamedCookies;

  /**
   * If true, http and https requests will be cached separately.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Boolean includeProtocol;

  /**
   * If true, include query string parameters in the cache key according to query_string_whitelist
   * and query_string_blacklist. If neither is set, the entire query string will be included. If
   * false, the query string will be excluded from the cache key entirely.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Boolean includeQueryString;

  /**
   * Names of query string parameters to exclude in cache keys. All other parameters will be
   * included. Either specify query_string_whitelist or query_string_blacklist, not both. '&' and
   * '=' will be percent encoded and not treated as delimiters.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<java.lang.String> queryStringBlacklist;

  /**
   * Names of query string parameters to include in cache keys. All other parameters will be
   * excluded. Either specify query_string_whitelist or query_string_blacklist, not both. '&' and
   * '=' will be percent encoded and not treated as delimiters.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<java.lang.String> queryStringWhitelist;

  /**
   * If true, requests to different hosts will be cached separately.
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getIncludeHost() {
    return includeHost;
  }

  /**
   * If true, requests to different hosts will be cached separately.
   * @param includeHost includeHost or {@code null} for none
   */
  public CacheKeyPolicy setIncludeHost(java.lang.Boolean includeHost) {
    this.includeHost = includeHost;
    return this;
  }

  /**
   * Allows HTTP request headers (by name) to be used in the cache key.
   * @return value or {@code null} for none
   */
  public java.util.List<java.lang.String> getIncludeHttpHeaders() {
    return includeHttpHeaders;
  }

  /**
   * Allows HTTP request headers (by name) to be used in the cache key.
   * @param includeHttpHeaders includeHttpHeaders or {@code null} for none
   */
  public CacheKeyPolicy setIncludeHttpHeaders(java.util.List<java.lang.String> includeHttpHeaders) {
    this.includeHttpHeaders = includeHttpHeaders;
    return this;
  }

  /**
   * Allows HTTP cookies (by name) to be used in the cache key. The name=value pair will be used in
   * the cache key Cloud CDN generates.
   * @return value or {@code null} for none
   */
  public java.util.List<java.lang.String> getIncludeNamedCookies() {
    return includeNamedCookies;
  }

  /**
   * Allows HTTP cookies (by name) to be used in the cache key. The name=value pair will be used in
   * the cache key Cloud CDN generates.
   * @param includeNamedCookies includeNamedCookies or {@code null} for none
   */
  public CacheKeyPolicy setIncludeNamedCookies(java.util.List<java.lang.String> includeNamedCookies) {
    this.includeNamedCookies = includeNamedCookies;
    return this;
  }

  /**
   * If true, http and https requests will be cached separately.
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getIncludeProtocol() {
    return includeProtocol;
  }

  /**
   * If true, http and https requests will be cached separately.
   * @param includeProtocol includeProtocol or {@code null} for none
   */
  public CacheKeyPolicy setIncludeProtocol(java.lang.Boolean includeProtocol) {
    this.includeProtocol = includeProtocol;
    return this;
  }

  /**
   * If true, include query string parameters in the cache key according to query_string_whitelist
   * and query_string_blacklist. If neither is set, the entire query string will be included. If
   * false, the query string will be excluded from the cache key entirely.
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getIncludeQueryString() {
    return includeQueryString;
  }

  /**
   * If true, include query string parameters in the cache key according to query_string_whitelist
   * and query_string_blacklist. If neither is set, the entire query string will be included. If
   * false, the query string will be excluded from the cache key entirely.
   * @param includeQueryString includeQueryString or {@code null} for none
   */
  public CacheKeyPolicy setIncludeQueryString(java.lang.Boolean includeQueryString) {
    this.includeQueryString = includeQueryString;
    return this;
  }

  /**
   * Names of query string parameters to exclude in cache keys. All other parameters will be
   * included. Either specify query_string_whitelist or query_string_blacklist, not both. '&' and
   * '=' will be percent encoded and not treated as delimiters.
   * @return value or {@code null} for none
   */
  public java.util.List<java.lang.String> getQueryStringBlacklist() {
    return queryStringBlacklist;
  }

  /**
   * Names of query string parameters to exclude in cache keys. All other parameters will be
   * included. Either specify query_string_whitelist or query_string_blacklist, not both. '&' and
   * '=' will be percent encoded and not treated as delimiters.
   * @param queryStringBlacklist queryStringBlacklist or {@code null} for none
   */
  public CacheKeyPolicy setQueryStringBlacklist(java.util.List<java.lang.String> queryStringBlacklist) {
    this.queryStringBlacklist = queryStringBlacklist;
    return this;
  }

  /**
   * Names of query string parameters to include in cache keys. All other parameters will be
   * excluded. Either specify query_string_whitelist or query_string_blacklist, not both. '&' and
   * '=' will be percent encoded and not treated as delimiters.
   * @return value or {@code null} for none
   */
  public java.util.List<java.lang.String> getQueryStringWhitelist() {
    return queryStringWhitelist;
  }

  /**
   * Names of query string parameters to include in cache keys. All other parameters will be
   * excluded. Either specify query_string_whitelist or query_string_blacklist, not both. '&' and
   * '=' will be percent encoded and not treated as delimiters.
   * @param queryStringWhitelist queryStringWhitelist or {@code null} for none
   */
  public CacheKeyPolicy setQueryStringWhitelist(java.util.List<java.lang.String> queryStringWhitelist) {
    this.queryStringWhitelist = queryStringWhitelist;
    return this;
  }

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

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

}


text:
package org.gradle.test.performance.mediummonolithicjavaproject.p301;

import org.junit.Test;
import static org.junit.Assert.*;

public class Test6038 {
    Production6038 objectUnderTest = new Production6038();

    @Test
    public void testProperty0() {
        Production6035 value = new Production6035();
        objectUnderTest.setProperty0(value);
        assertEquals(value, objectUnderTest.getProperty0());
    }

    @Test
    public void testProperty1() {
        Production6036 value = new Production6036();
        objectUnderTest.setProperty1(value);
        assertEquals(value, objectUnderTest.getProperty1());
    }

    @Test
    public void testProperty2() {
        Production6037 value = new Production6037();
        objectUnderTest.setProperty2(value);
        assertEquals(value, objectUnderTest.getProperty2());
    }

    @Test
    public void testProperty3() {
        String value = "value";
        objectUnderTest.setProperty3(value);
        assertEquals(value, objectUnderTest.getProperty3());
    }

    @Test
    public void testProperty4() {
        String value = "value";
        objectUnderTest.setProperty4(value);
        assertEquals(value, objectUnderTest.getProperty4());
    }

    @Test
    public void testProperty5() {
        String value = "value";
        objectUnderTest.setProperty5(value);
        assertEquals(value, objectUnderTest.getProperty5());
    }

    @Test
    public void testProperty6() {
        String value = "value";
        objectUnderTest.setProperty6(value);
        assertEquals(value, objectUnderTest.getProperty6());
    }

    @Test
    public void testProperty7() {
        String value = "value";
        objectUnderTest.setProperty7(value);
        assertEquals(value, objectUnderTest.getProperty7());
    }

    @Test
    public void testProperty8() {
        String value = "value";
        objectUnderTest.setProperty8(value);
        assertEquals(value, objectUnderTest.getProperty8());
    }

    @Test
    public void testProperty9() {
        String value = "value";
        objectUnderTest.setProperty9(value);
        assertEquals(value, objectUnderTest.getProperty9());
    }

}


text:
. include/common.sh
. include/public.sh
. include/sysinfo.sh >/dev/null 2>&1

clear
echo -e "${GREEN}
#####################################################################
# LNMP is a bash script for the installation of Nginx + PHP + MySQL.#
# Author        Hehl <1181554113@qq.com>                            #
# Blog          Http://www.yunweijilu.com                           #
#####################################################################"

#Menu of upgrade
Menu_Upgrade(){
echo -e "${YELLOW}Please input the number which  you want upgrade?"
echo
echo -e "${YELLOW}1)${WHITE} Upgrade Nginx;"
echo -e "${YELLOW}2)${WHITE} Upgrade Mysql;"
echo -e "${YELLOW}3)${WHITE} Upgrade Php;"
echo
read -p "You select number is: " select_upgrade
case $select_upgrade in
1)
	. include/upgrade_web.sh
;;
2)
	if [ ! -d $mysql_local ];then
		echo "No Mysql Server in $mysql_local !"
		exit
	else
		. include/upgrade_db.sh
	fi
;;
3)
	. include/upgrade_php.sh
;;
*)
	echo "Error, input wrong number!"
;;
esac
}

Menu_Upgrade 2>&1 | tee ./upgrade.log


text:
<?php

namespace app\controllers;

class ProductsUsedPerAreaController extends \yii\web\Controller
{
    public function actionIndex()
    {
        return $this->render('index');
    }

}


text:
export default {
  entry: '../../dist/packages-dist/forms/@angular/forms.es5.js',
  dest: '../../dist/packages-dist/forms/bundles/forms.umd.js',
  format: 'umd',
  exports: 'named',
  moduleName: 'ng.forms',
  globals: {
    '@angular/core': 'ng.core',
    '@angular/common': 'ng.common',
    '@angular/compiler': 'ng.compiler',
    '@angular/platform-browser': 'ng.platformBrowser',
    'rxjs/Observable': 'Rx',
    'rxjs/Subject': 'Rx',
    'rxjs/observable/fromPromise': 'Rx.Observable',
    'rxjs/observable/forkJoin': 'Rx.Observable',
    'rxjs/operator/map': 'Rx.Observable.prototype'
  }
};


text:
.class public interface abstract Lorg/apache/http/HttpResponseInterceptor;
.super Ljava/lang/Object;
.source "HttpResponseInterceptor.java"

# virtual methods
.method public abstract process(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Lorg/apache/http/HttpException;,
            Ljava/io/IOException;
        }
    .end annotation
.end method


text:
<!DOCTYPE html>

    <title>Test page 1</title>

hello!

    <button id="btn-clickme">click me</button>


text:
package discovery

import (
	"github.com/apache/servicecomb-service-center/pkg/log"
	"github.com/apache/servicecomb-service-center/pkg/util"
	"github.com/apache/servicecomb-service-center/server/plugin/pkg/registry"
	"golang.org/x/net/context"
	"time"
)

type CacheIndexer struct {
	Cache Cache
}

func (i *CacheIndexer) Search(ctx context.Context, opts ...registry.PluginOpOption) (resp *Response, _ error) {
	op := registry.OpGet(opts...)
	if op.Prefix {
		resp = i.searchByPrefix(op)
	} else {
		resp = i.search(op)
	}
	return
}

func (i *CacheIndexer) search(op registry.PluginOp) *Response {
	resp := new(Response)

	key := util.BytesToStringWithNoCopy(op.Key)

	kv := i.Cache.Get(key)
	if kv != nil {
		resp.Count = 1
	}
	if kv == nil || op.CountOnly {
		return resp
	}

	resp.Kvs = []*KeyValue{kv}
	return resp
}

func (i *CacheIndexer) searchByPrefix(op registry.PluginOp) *Response {
	resp := new(Response)

	prefix := util.BytesToStringWithNoCopy(op.Key)

	resp.Count = int64(i.Cache.GetPrefix(prefix, nil))
	if resp.Count == 0 || op.CountOnly {
		return resp
	}

	t := time.Now()
	kvs := make([]*KeyValue, 0, resp.Count)
	i.Cache.GetPrefix(prefix, &kvs)
	log.LogNilOrWarnf(t, "too long to index data[%d] from cache '%s'", len(kvs), i.Cache.Name())

	resp.Kvs = kvs
	return resp
}

func NewCacheIndexer(cache Cache) *CacheIndexer {
	return &CacheIndexer{
		Cache: cache,
	}
}


text:
namespace DoremiEngine
{
    namespace AI
    {
        class PotentialFieldSubModuleImpl : public PotentialFieldSubModule
        {
        public:
            PotentialFieldSubModuleImpl(AIContext& p_aiContext);
            virtual ~PotentialFieldSubModuleImpl();
            PotentialField* CreateNewField(const float& p_width, const float& p_height, const int& p_numberOfQuadsWidth,
                                           const int& p_numberOfQuadsHeight, const DirectX::XMFLOAT3& p_center, const std::string& p_fieldName) override;
            PotentialField* CreateNewFieldFromFile(const std::string& p_fileName) override;
            bool SaveFieldToFile(const PotentialField& p_fieldToSave, const std::string& p_fileName) override;
            PotentialGroup* CreateNewPotentialGroup() override;
            PotentialFieldActor* CreateNewActor(const DirectX::XMFLOAT3& p_position, const float& p_charge, const float& p_range,
                                                const bool& p_static, const AIActorType& p_actorType) override;
            void AttachActor(PotentialField& o_field, PotentialFieldActor* p_actor) override;
            void EraseActor(PotentialFieldActor* op_actor) override;
            void EraseActor(PotentialFieldActor* op_actor, PotentialField* op_field) override;
            PotentialField* FindBestPotentialField(const DirectX::XMFLOAT3& p_position) override;
            void AddActorToEveryPotentialField(PotentialFieldActor* p_actor) override;
            std::vector<PotentialField*>& GetAllActiveFields() override { return m_fields; };
        private:
            std::vector<PotentialField*> m_fields;
            AIContext& m_context;
        };
    }
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('dbsettings', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='setting',
            name='value',
            field=models.TextField(blank=True),
            preserve_default=True,
        ),
    ]


text:
<pronoun>
	<label>lui</label>
	<gender>masculine</gender>
	<form>
		<multiplicity>singular</multiplicity>
	    <person>third</person>
	    <disjunctive/>
	</form>
</pronoun>


text:
use lib "/MG-RAST/conf";

use strict;
use warnings;
no warnings('once');

use Conf;
use JSON;
use LWP::UserAgent;
use HTTP::Request::Common;

my $shock_url  = $Conf::shock_url;
my $awe_url    = $Conf::awe_url;
my $auth_token = $Conf::pipeline_token;

my $aweid = shift @ARGV;

unless ($aweid) {
    print STDERR "Usage: \tdelete_job_and_files.pl <awe_id> \n";
    exit 1;
}

# set handels
my $agent = LWP::UserAgent->new();
$agent->timeout(3600);
my $json = JSON->new;
$json = $json->utf8();
$json->max_size(0);
$json->allow_nonref;

# get job document
my $response = undef;
my $job_doc  = undef;
eval {
    my $get = $agent->get($awe_url.'/job/'.$aweid, 'Authorization', $auth_token);
    $response = $json->decode( $get->content );
};
if ($@ || (! ref($response))) {
    print STDERR "ERROR: unable to connect to AWE server\n";
} elsif (exists($response->{error}) && $response->{error}) {
    print STDERR "ERROR: ".$response->{error}[0]."\n";
} else {
    $job_doc = $response->{data};
}

# delete job
system("curl -X DELETE -H 'Authorization: $auth_token' '$awe_url/job/$aweid?full=1'; echo");

# delete nodes
foreach my $task (@{$job_doc->{tasks}}) {
    foreach my $out (@{$task->{outputs}}) {
        if ($out->{node} && ($out->{node} ne '-')) {
            system("curl -X DELETE -H 'Authorization: $auth_token' '$shock_url/node/".$out->{node}."'; echo");
        }
    }
}

exit 0;


text:
cask "ableton-live-intro" do
  arch = MacOS.version >= :mojave ? "universal" : "intel"
  version "11.1.1"

  if MacOS.version >= :mojave
    sha256 "0ef488ed18ccb397d75c82289fdc0e6abc4d5898729b720e4b507ec9065732f5"
  else
    sha256 "91064b1551ded54c841d61d8f30a538c6f2f177d1caf2a39f823ea952093f38e"
  end

  url "https://cdn-downloads.ableton.com/channels/#{version}/ableton_live_intro_#{version}_#{arch}.dmg"
  name "Ableton Live Intro"
  desc "Sound and music editor"
  homepage "https://www.ableton.com/en/live/"

  livecheck do
    cask "ableton-live-suite"
  end

  auto_updates true
  depends_on macos: ">= :high_sierra"

  app "Ableton Live #{version.major} Intro.app"

  uninstall quit: "com.ableton.live"

  zap trash: [
    "~/Library/Application Support/Ableton",
    "~/Library/Application Support/CrashReporter/Ableton *_*.plist",
    "~/Library/Application Support/CrashReporter/Live_*.plist",
    "~/Library/Caches/Ableton",
    "~/Library/Preferences/Ableton",
    "~/Library/Preferences/com.ableton.live.plist*",
    "~/Music/Ableton",
  ]
end


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>Uses of Class com.fasterxml.jackson.jr.ob.impl.BeanPropertyReader (jackson-jr-objects 2.11.0 API)</title>
<meta name="date" content="2020-04-25">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.fasterxml.jackson.jr.ob.impl.BeanPropertyReader

Packages that use BeanPropertyReader

Package
Description

com.fasterxml.jackson.jr.ob.impl

Uses of BeanPropertyReader in com.fasterxml.jackson.jr.ob.impl

Fields in com.fasterxml.jackson.jr.ob.impl with type parameters of type BeanPropertyReader

Modifier and Type
Field and Description

protected Map<String,BeanPropertyReader>
BeanReader._propsByName

Methods in com.fasterxml.jackson.jr.ob.impl that return BeanPropertyReader

Modifier and Type
Method and Description

BeanPropertyReader
BeanReader.findProperty(String name)

BeanPropertyReader
BeanPropertyReader.withReader(ValueReader vr)

Methods in com.fasterxml.jackson.jr.ob.impl that return types with arguments of type BeanPropertyReader

Modifier and Type
Method and Description

Map<String,BeanPropertyReader>
BeanReader.propertiesByName()

Constructors in com.fasterxml.jackson.jr.ob.impl with parameters of type BeanPropertyReader

Constructor and Description

BeanPropertyReader(BeanPropertyReader src,
                  ValueReader vr)

Constructor parameters in com.fasterxml.jackson.jr.ob.impl with type arguments of type BeanPropertyReader

Constructor and Description

BeanReader(Class<?> type,
          Map<String,BeanPropertyReader> props,
          Constructor<?> defaultCtor,
          Constructor<?> stringCtor,
          Constructor<?> longCtor)

Deprecated.

BeanReader(Class<?> type,
          Map<String,BeanPropertyReader> props,
          Constructor<?> defaultCtor,
          Constructor<?> stringCtor,
          Constructor<?> longCtor,
          Set<String> ignorableNames,
          Map<String,String> aliasMapping)

Constructors used for deserialization use case

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2020 FasterXML. All rights reserved.


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Trans. Linn. Soc. London 16:285. 1830

#### Original name
null

### Remarks
null


text:
namespace FastFood.DataProcessor.Dto.Import
{
    using System.ComponentModel.DataAnnotations;

    public class EmoloyeeDto
    {

        [Required]
        [StringLength(30, MinimumLength = 3)]
        public string Name { get; set; }

        [Required]
        [Range(15, 80)]
        public int Age { get; set; }

        [Required]
        [StringLength(30, MinimumLength = 3)]
        public string Position { get; set; }
    }
}