text:
package it.larusba.integration.neo4j.jsonloader.transformer.test;

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

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.time.DurationFormatUtils;
import org.junit.Test;

import it.larusba.integration.common.document.bean.JsonDocument;
import it.larusba.integration.common.document.bean.JsonObjectDescriptor;
import it.larusba.integration.common.document.mapping.JsonMappingStrategy;
import it.larusba.integration.neo4j.jsonloader.transformer.DomainDrivenJsonTransformer;

public class NodeJsonTransformerTest {

    @Test
    public void testMini() throws Exception {
        String content = IOUtils.toString(getClass().getResourceAsStream("/json/album-mini.json"));
        String id = String.valueOf(System.currentTimeMillis());
        String type = "Album";
        List<JsonObjectDescriptor> descriptors = new ArrayList<>();
        descriptors.add(new JsonObjectDescriptor(type, Arrays.asList("id", "type"), "type"));
        JsonDocument jsonDocument = new JsonDocument(id, type, content, JsonMappingStrategy.DOMAIN_DRIVEN, descriptors);
        DomainDrivenJsonTransformer transformer = new DomainDrivenJsonTransformer();
        long start = System.currentTimeMillis();
        String transformedSet = transformer.transform(jsonDocument);
        long end = System.currentTimeMillis();
        System.out.println("---------RESULT---------");
        System.out.println(transformedSet);
        System.out.println("Time elapsed: " + DurationFormatUtils.formatDurationHMS(end - start));
    }

    @Test
    public void testFull() throws Exception {
        String content = IOUtils.toString(getClass().getResourceAsStream("/json/album.json"));
        String id = String.valueOf(System.currentTimeMillis());
        String type = "Album";
        List<JsonObjectDescriptor> descriptors = new ArrayList<>();
        descriptors.add(new JsonObjectDescriptor(type, Arrays.asList("id", "type"), "type"));
        JsonDocument jsonDocument = new JsonDocument(id, type, content, JsonMappingStrategy.DOMAIN_DRIVEN, descriptors);
        DomainDrivenJsonTransformer transformer = new DomainDrivenJsonTransformer();
        long start = System.currentTimeMillis();
        String transformedSet = transformer.transform(jsonDocument);
        long end = System.currentTimeMillis();
        System.out.println("---------RESULT---------");
        System.out.println(transformedSet);
        System.out.println("Time elapsed: " + DurationFormatUtils.formatDurationHMS(end - start));
    }
}


text:
using UnityEngine;
using System.Collections;

public class ProjectileMovement : MonoBehaviour {

  public Vector3 movementDirection;
  public Vector3 startLocation;
  public float speed;
  public float accelerationConstant;
  public int maxDistance;
  public float distance;
  public Weapon weapon;

	// Use this for initialization
	void Start () {
    maxDistance = 30;
    speed = 30;
    accelerationConstant = 1.0f;
	}

	// Update is called once per frame
	void Update () {
    transform.position = Vector3.MoveTowards(transform.position, movementDirection + transform.position, speed * Time.deltaTime);
    speed += accelerationConstant;

    distance = Vector3.Distance(startLocation, transform.position);
    if ( distance > maxDistance)
    {
      weapon.projectileCount--;
      Destroy(this.gameObject);
    }
	}

  void OnTriggerEnter(Collider other)
  {
    if (other.name == "Box Monster(Clone)")
    {
      Debug.Log("Box HIT!!!");

      GameEntity monsterEntity = other.GetComponent<GameEntity>();
      if (monsterEntity)
      {
        // TODO: Base this damage based on weapon.
        monsterEntity.takeDamage(1.0f);
      }
      else
      {
        // Destroy monster in case it doesnt have an entity.
        Destroy(other.gameObject);
      }

      weapon.projectileCount--;
      Destroy(this.gameObject);
    }
  }

}

redpajama_set_name: RedPajamaGithub


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

public abstract class Race
{
}


text:
var MeMOOC = {};

(function ($, window) {
    if (typeof MeMOOC === 'undefined') {
        MeMOOC = {};
    }
    MeMOOC.formFillIn = function (opts) {
        var defaults = {
            'dataType': 'json'
        };
        this.options = $.extend({}, defaults, (opts || {}));
        this.construct();
    };
    MeMOOC.formFillIn.prototype = {
        construct: function () {
            //cln('mCompetition.construct');
        },

        initBinds: function () {
            cln('mCompetition.initBinds');

            thet = this;

            $("#list_competition button.more")
                .off('click.list_competition_more')
                .on('click.list_competition_more', function (event) {
                    cl('list_competition_more.click');
                    var data = $(this).attr('data-page');
                    var json_data = JSON.parse(data);

                    rsmCompetition.loadMoreListCompetitions(json_data.page);

                    event.preventDefault();
                    event.stopPropagation();
                });

        },

        loadMoreListCompetitions: function (page) {
            cln('mCompetition.loadMoreListCompetitions');

            $.ajax({
                type: 'get',
                url: _SITE_URL + 'rsmobile/competitions/?page=' + page,
                //data : JSON.parse(json_data),
                beforeSend: function () {
                    rsLoadSpinner.show();
                },
                success: function (response) {
                    $('#list_competition button.more').remove();
                    $('#list_competition').append(response);
                    //location.reload();
                    rsLoadSpinner.hide();
                },
                error: function (jqXHR, textStatus, errorThrown) {// errors log
                    cle(errorThrown);
                    rsLoadSpinner.hide();
                }
            });
        },

        fb_load: function () {
            cln('fb_load');

            this.disabledBtn();

            this.fb_init();
            this.fb_loadSDK();
        },

        fb_init: function () {
            cln('fb_init');
            var that = this;

            window.fbAsyncInit = function () {

                FB.init({
                    appId: '878438892204950',
                    cookie: true,  // enable cookies to allow the server to access
                                   // the session
                    xfbml: true,  // parse social plugins on this page
                    version: 'v2.4' // use version 2.2
                });

                // Now that we've initialized the JavaScript SDK, we call
                // FB.getLoginStatus().  This function gets the state of the
                // person visiting this page and can return one of three states to
                // the callback you provide.  They can be:
                //
                // 1. Logged into your app ('connected')
                // 2. Logged into Facebook, but not your app ('not_authorized')
                // 3. Not logged into Facebook and can't tell if they are logged into
                //    your app or not.
                //
                // These three cases are handled in the callback function.

                FB.getLoginStatus(function (response) {
                    that.fb_statusChangeCallback(response);
                });

            };
        },

        fb_loadSDK: function () {
            cln('fb_loadSDK');
            // Load the SDK asynchronously
            (function (d, s, id) {
                var js, fjs = d.getElementsByTagName(s)[0];
                if (d.getElementById(id)) return;
                js = d.createElement(s);
                js.id = id;
                js.src = "//connect.facebook.net/en_US/sdk.js";
                fjs.parentNode.insertBefore(js, fjs);
            }(document, 'script', 'facebook-jssdk'));
        },

        // This is called with the results from from FB.getLoginStatus().
        fb_statusChangeCallback: function (response) {
            cln('fb_statusChangeCallback');
            this.enabledBtn('fb');
            // The response object is returned with a status field that lets the
            // app know the current login status of the person.
            // Full docs on the response object can be found in the documentation
            // for FB.getLoginStatus().
            if (response.status === 'connected') {
                // Logged into your app and Facebook.
                //this.fb_getUserData();
            } else if (response.status === 'not_authorized') {
                // The person is logged into Facebook, but not your app.
                //document.getElementById('status').innerHTML = 'Please log into this app.';
            } else {
                // The person is not logged into Facebook, so we're not sure if
                // they are logged into this app or not.
                //document.getElementById('status').innerHTML = 'Please log into Facebook.';
            }
        },

        // This function is called when someone finishes with the Login
        // Button.  See the onlogin handler attached to it in the sample
        // code below.
        fb_checkLoginState: function () {
            cln('fb_checkLoginState');
            var that = this;

            FB.getLoginStatus(function (response) {
                that.fb_statusChangeCallback(response);
            });
        },

        fb_loginSimpleBtn: function () {
            cln('fb_loginSimpleBtn');
            var that = this;
            FB.login(function (response) {
                console.log(response);
                that.fb_getUserData();
            }, {scope: 'public_profile,email'});
        },

        // Here we run a very simple test of the Graph API after login is
        // successful.  See statusChangeCallback() for when this call is made.
        fb_getUserData: function () {
            cln('fb_getUserData');
            var that = this;
            FB.api('/me', {fields: 'email,first_name,last_name,name'}, function (response) {
                console.log(response);
                if (response.email && response.name) {

                    that.formFillIn(response.email, response.name)
                }
            });
        },

        disabledBtn: function () {
            cln('disabledBtn');
            $(".formFillIn_btn").prop('disabled', true);
        },

        enabledBtn: function (v) {
            cln('enabledBtn -', v);
            if (v == 'fb') {
                $(".formFillIn_btn.button-oa2-facebook").prop('disabled', false);
            }
            else if (v == 'g') {
                $(".formFillIn_btn.button-oa2-google-oauth2").prop('disabled', false);
            }
        },

        formFillIn: function (email, name) {
            cln('formFillIn -', email, name);
            email && $("input[name='email']").val(email);
            name && $("input[name='name']").val(name);
            if (email && name) {
                $("input[name='username']").focus();
            }
        },

        g_load: function () {
            cln('g_load');

            this.g_loadFile();
            this.g_init();
        },

        g_loadFile: function () {
            cln('g_load');
            (function () {
                var po = document.createElement('script');
                po.type = 'text/javascript';
                po.async = true;
                po.src = 'https://plus.google.com/js/client:plusone.js';
                var s = document.getElementsByTagName('script')[0];
                s.parentNode.insertBefore(po, s);
            })();
        },

        g_init: function () {
            cln('g_init');
            // http://mycodde.blogspot.rs/2014/12/login-using-google-javascript-api.html
            var that = this;
            this.gpclass = (function () {

                //Defining Class Variables here
                var response = undefined;
                return {
                    //Class functions / Objects

                    mycoddeSignIn: function (response) {
                        cln('mycoddeSignIn');
                        // The user is signed in
                        if (response['access_token']) {

                            //Get User Info from Google Plus API
                            gapi.client.load('plus', 'v1', this.getUserInformation);

                        } else if (response['error']) {
                            // There was an error, which means the user is not signed in.
                            //alert('There was an error: ' + authResult['error']);
                            cle(response['error']);
                        }
                    },

                    getUserInformation: function () {
                        cln('getUserInformation');
                        var request = gapi.client.plus.people.get({'userId': 'me'});
                        request.execute(function (profile) {
                            console.log(profile);
                            var email = profile['emails'].filter(function (v) {
                                return v.type === 'account'; // Filter out the primary email
                            })[0].value;
                            var fName = profile.displayName;

                            that.formFillIn(email, fName);
                        });
                    }

                }; //End of Return
            })();

            function mycoddeSignIn(gpSignInResponse) {
                cln('mycoddeSignIn');
                this.gpclass.mycoddeSignIn(gpSignInResponse);
            }
        },

        g_mycoddeSignIn: function (gpSignInResponse) {
            cln('g_mycoddeSignIn');
            gpSignInResponse = gpSignInResponse || this.gpSignInResponse;
            this.gpclass.mycoddeSignIn(gpSignInResponse);
        },
        g_saveGpSignInResponse: function (gpSignInResponse) {
            cln('g_saveGpSignInResponse');
            this.enabledBtn('g');
            this.gpSignInResponse = gpSignInResponse;
            var v = gpSignInResponse;
            if (v && v.status && v.status.method && v.status.method != 'AUTO') {
                this.g_mycoddeSignIn(gpSignInResponse);
            }
        }

    };

})($, window);

var mmFormFillIn = new MeMOOC.formFillIn();

function g__mycoddeSignIn(gpSignInResponse) {
    console.log('ppppl', gpSignInResponse);
    mmFormFillIn.g_saveGpSignInResponse(gpSignInResponse);
}

$(document).ready(function () {
    cl("ready!");
    var pathname = window.location.pathname;

    if (pathname.indexOf('register') != -1) {

        mmFormFillIn.fb_load();
        mmFormFillIn.g_load();
    }
});


text:
package ductive.console.shell;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import org.apache.logging.log4j.CloseableThreadContext;
import org.apache.sshd.server.Command;
import org.apache.sshd.server.Environment;
import org.apache.sshd.server.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ductive.console.jline.JLineConsoleReader;
import ductive.console.jline.JLineInteractiveTerminal;
import ductive.console.sshd.SshTerminal;

public class EmbeddedShellRunner implements Command {

	private static final Logger log = LoggerFactory.getLogger(EmbeddedShellRunner.class);

	private final Executor executor;

	private OutputStream err;
	private InputStream in;
	private OutputStream out;

	private boolean closed;

	private ExitCallback callback;

	private Shell shell;

	public EmbeddedShellRunner(Shell shell) {
		executor = Executors.newSingleThreadExecutor();
		this.shell = shell;
	}

	@Override
	public void setErrorStream(OutputStream err) {
		this.err = err;
	}

	@Override
	public void setExitCallback(ExitCallback callback) {
		this.callback = callback;
	}

	@Override
	public void setInputStream(InputStream in) {
		this.in = in;
	}

	@Override
	public void setOutputStream(OutputStream out) {
		this.out = out;
	}

	@Override
	public void start(final Environment env) throws IOException {
		executor.execute(new Runnable() {
			@Override
			public void run() {
				try(CloseableThreadContext.Instance ctx = CloseableThreadContext.push("remote-shell")) {
					String user = env.getEnv().get(Environment.ENV_USER);
					ctx.put("user",user);

					JLineConsoleReader r = new JLineConsoleReader(in,out,new SshTerminal(env));
					try {
						r.setExpandEvents(false);
						JLineInteractiveTerminal terminal = new JLineInteractiveTerminal(r,DefaultTerminalSettings.INSTANCE);

						shell.execute(terminal,new TerminalUser(user));
					} finally {
						r.shutdown();
					}

					destroy();
				} catch (Exception e) {
					if(log.isWarnEnabled())
						log.warn(String.format("exception in remote console thread: %s",e));

					if(log.isDebugEnabled())
						log.debug(String.format("exception in remote console thread:"),e);

					destroy();
				}
			}
		});
	}

	@Override
	public void destroy() {
		if (!closed) {
			closed = true;
			flush(out, err);
			close(in, out, err);
			callback.onExit(0);
		}
	}

	private static void flush(OutputStream... streams) {
		for (OutputStream s : streams) {
			try {
				s.flush();
			} catch (IOException e) { /* noop */ }
		}
	}

	private static void close(Closeable... closeables) {
		for (Closeable c : closeables) {
			try {
				c.close();
			} catch (IOException e) { /* noop */ 	}
		}
	}

}


text:
package com.griddynamics.jagger.coordinator.async;

import java.io.Serializable;

/**
 * Composes several {@code AsyncCallback} instances into single one.
 *
 * @author Mairbek Khadikov
 */
public class CompositeAsyncCallback<R extends Serializable> implements AsyncCallback<R> {
	private final Iterable<AsyncCallback<R>> delegates;

	/* package */CompositeAsyncCallback(Iterable<AsyncCallback<R>> delegates) {
		this.delegates = delegates;
	}

	@Override
	public void onSuccess(R result) {
		for (AsyncCallback<R> callback : delegates) {
			callback.onSuccess(result);
		}
	}

	@Override
	public void onFailure(Throwable throwable) {
		for (AsyncCallback callback : delegates) {
			callback.onFailure(throwable);
		}
	}

}


text:
body::before {
    background-size: cover;
    background-attachment: fixed;
    content: '';
    will-change: transform;
    z-index: -1;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    position: fixed;
}
@media (max-width: 512px)  and (-webkit-min-device-pixel-ratio: 1.5),
       (max-width: 512px)  and (min-resolution: 1.5dppx),
       (max-width: 1024px) and (-webkit-max-device-pixel-ratio: 1.5),
       (max-width: 1024px) and (max-resolution: 1.5dppx) {
  body::before {
    background-image: url('images/mobileRockWall.jpg');
  }
}
@media (min-width: 513px)  and (max-width: 1024px) and (-webkit-min-device-pixel-ratio: 1.5),
       (min-width: 513px)  and (max-width: 1024px) and (min-resolution: 1.5dppx),
       (min-width: 1025px) and (max-width: 2048px) and (-webkit-max-device-pixel-ratio: 1.5),
       (min-width: 1025px) and (max-width: 2048px) and (max-resolution: 1.5dppx)  {
  body::before {
    background-image: url('images/mobileRockWall.jpg');
  }
}
@media (min-width: 1025px) and (-webkit-min-device-pixel-ratio: 1.5),
       (min-width: 1025px) and (min-resolution: 1.5dppx),
       (min-width: 2049px) and (-webkit-max-device-pixel-ratio: 1.5),
       (min-width: 2049px) and (max-resolution: 1.5dppx) {
  body::before {
    background-image: url('images/rockWall.jpg');
  }
}
body .demo-blog {
  font-family: 'Roboto', 'Helvetica', sans-serif;
}

.demo-blog .demo-blog__posts {
  max-width: 900px;
  padding: 0;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  width: 100%;
  margin: 0 auto;
  -webkit-flex-shrink: 0;
      -ms-flex-negative: 0;
          flex-shrink: 0;
}

.demo-blog.mdl-layout .mdl-layout__content {
  padding-top: 100px;
  position: relative;
  -webkit-overflow-scrolling: touch;
}
h3 {
    text-align: center;
    color: floralwhite;
}
p {
    padding-right: 10%;
}
.demo-blog .mdl-card {
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-flex-direction: column;
      -ms-flex-direction: column;
          flex-direction: column;
  -webkit-align-items: stretch;
      -ms-flex-align: stretch;
          align-items: stretch;
  min-height: 360px;
    margin-bottom: 4%;
    margin-top: 4%;
}
.demo-blog .mdl-card__title {
  padding: 16px;
  -webkit-flex-grow: 1;
      -ms-flex-positive: 1;
          flex-grow: 1;
}
.demo-blog .mdl-card__media {
  box-sizing: border-box;
  background-size: cover;
  padding: 24px;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-flex-grow: 1;
      -ms-flex-positive: 1;
          flex-grow: 1;
  -webkit-flex-direction: row;
      -ms-flex-direction: row;
          flex-direction: row;
  -webkit-align-items: flex-end;
      -ms-flex-align: end;
          align-items: flex-end;
  cursor: pointer;
}
.demo-blog .mdl-card__media a,
.demo-blog .mdl-card__title a {
  color: inherit;
}
.demo-blog .mdl-card__supporting-text {
  width: 100%;
  padding: 16px;
  min-height: 64px;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-align-items: center;
      -ms-flex-align: center;
          align-items: center;
}
.demo-blog .mdl-card__supporting-text strong {
  font-weight: 400;
}
.demo-blog .mdl-card__media ~ .mdl-card__supporting-text {
  min-height: 20px;
}
.demo-blog .mdl-card__supporting-text:not(:last-child) {
  box-sizing: border-box;
  min-height: 76px;
}
.demo-blog:not(.demo-blog--blogpost) .mdl-card__supporting-text ~ .mdl-card__supporting-text {
  border-top: 1px solid rgba(0,0,0,0.1);
}

.demo-blog .tree-pic .mdl-card__media {
  background-image: url('images/tree.jpg');
}
.demo-blog .rockWall .mdl-card__media {
  background-image: url('images/field.jpg');
}
.demo-blog .mountain .mdl-card__media {
  background-image: url('images/mountain.jpg');
}
.demo-blog .mdl-card h4.quote:before, .demo-blog .mdl-card h4.quote:after {
  display: block;
  font-size: 3em;
  margin-top: 0.5em;
}
.demo-blog .mdl-card h4.quote:before {
  content: '"';
}
.demo-blog .mdl-card h4.quote:after {
  content: '"';
}
.demo-blog--blogpost .custom-header {
  background-color: transparent;
}
.demo-blog--blogpost .demo-blog__posts > .mdl-card .mdl-card__media {
  background-image: url('images/tree.jpg');
  height: 280px;
}
.demo-blog--blogpost .comments {
  background-color: #EEE;
}
.demo-blog--blogpost .meta > * {
  -webkit-align-items: center;
      -ms-flex-align: center;
          align-items: center;
}
.demo-blog--blogpost .meta + .mdl-card__supporting-text {
  border: 0;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-flex-direction: column;
      -ms-flex-direction: column;
          flex-direction: column;
}
.demo-blog--blogpost .meta + .mdl-card__supporting-text p {
  max-width: 512px;
  margin: 16px auto;
  font-size: 16px;
  line-height: 28px;
}
.demo-blog--blogpost .demo-back {
  position: absolute;
  top: 16px;
  left: 16px;
  color: white;
  z-index: 9999;
}
.demo-blog .section-spacer {
  -webkit-flex-grow: 1;
      -ms-flex-positive: 1;
          flex-grow: 1;
}
.demo-blog .amazing .mdl-card__title {
  background-color: #263238;
}
.demo-blog .minilogo {
  width: 44px;
  height: 44px;
  background-image: url('images/avatar.png');
  background-position: center;
  background-repeat: no-repeat;
  background-size: 50%;
  border-radius: 22px;
  background-color: #F5F5F5;
}

/* Fixes for IE 10 */
.mdl-grid {
  display: -webkit-flex !important;
  display: -ms-flexbox !important;
  display: flex !important;
}
/* CSS for cards on Events page */
.event-tile {
    padding-bottom: 2%;
    padding-top: 2%;
    z-index: 100;
}
.event-text {
    padding: 2%;
    color: #263238;
    word-wrap: break-word;
}
.transbox {
    margin-left: 30%;
    background-color: #ffffff;
    border: 1px solid black;
    opacity: 0.6;
    z-index: 1;
}

.social-btn {
  background-position: center;
  background-size: contain;
  background-repeat: no-repeat;
  background-color: transparent;
  margin: 0 16px;
  width: 24px;
  height: 24px;
  cursor: pointer;
  opacity: 0.46;
  border-radius: 2px;
}
.social-btn__pinterest {
  background-image: url('images/Pinterest/Pinterest-badge-36px.png');
}
.social-btn__facebook {
  background-image: url('https://www.gstatic.com/images/icons/material/system/2x/post_facebook_black_24dp.png');
}
.social-btn__instagram {
  background-image: url('images/instagram.png');
}
.social-btn__linkedin {
    background-image: url('images/Linkedin.jpeg');
}
.social-btn__share {
  color: rgba(0, 0, 0, 0.54);
  background: transparent;
}
#share-buttons img {
    width: 35px;
    padding: 5px;
    border: 0;
    box-shadow: 0;
}

.demo-blog .mdl-mini-footer {
  margin-top: 80px;
  height: 120px;
  padding: 40px;
  -webkit-align-items: center;
      -ms-flex-align: center;
          align-items: center;
  background-color: white;
  box-sizing: border-box;
}


text:
typedef struct jobChangeInfo
{
   Qus_Job_Change_Information_t  fieldNum;
   Qus_JOBC0100_t                format;
   char                          data[31];
} jobChangeInfo_t;

// Errorcode for system API calls
Qus_EC_t errorCode;

PEGASUS_USING_PEGASUS;
PEGASUS_USING_STD;

//constructor
ServerProcess::ServerProcess() {}

//destructor
ServerProcess::~ServerProcess() {}

// no-ops
void ServerProcess::notify_parent(int id) {}
void ServerProcess::cimserver_set_process(void* p) {}
long ServerProcess::get_server_pid(void) { return 0; }
void ServerProcess::set_parent_pid(int pid) {}
int ServerProcess::get_proc(int pid) { return 0; }
int ServerProcess::cimserver_wait(void) { return 1; }
String ServerProcess::getHome(void) { return String::EMPTY; }

///////////////////////////////////////////////////////////////////////
// cimserver_fork()
//
// The iSeries qycmctlcimCimomServer.C (QYCMCTLCIM program) code has
// already checked that the CIMOM server is not already running prior
// to calling the CIMOM server (QYCMCIMOM) and telling it to start itself.
// Therefore, no check is made in this method to ensure the CIMOM server
// is not already running.
//
// Note: This code was written because fork( ) is not supported on OS/400.
///////////////////////////////////////////////////////////////////////
int ServerProcess::cimserver_fork(void)
{
  // First migrate the server configuration settings into the planned file.
  CIMRepositoryUpdate400 obj;
  obj.preserveConfigSettings();

  // TODO:  This is here for now until we can move it into initialize.  Right now it doesn't run because qycmsetupr won't work in a multi-threaded environment.  See issue #AD2
  obj.doIt();

#pragma convert(37)
  char rc5[3] = "05"; // rc5 means the CIMOM Server failed to start
  char cppServ[10] = "QYCMCIMOM";
  ycmJob cppJob(YCMJOB_SRVNAME_10, YCMJOB_SRVUSER_10);

  // Submit the server job (QYCMCIMOM).  The job is submitted with the
  // daemon=false parameter to avoid an infinite loop of jobs being
  // submitted by this code!
  if (YCMJOB_SUBMIT_FAILED == cppJob.submit(YCMJOB_SRVR_PGM,
                        YCMJOB_QSYS_LIB,
                        "daemon=false",
                        YCMJOB_JOBD,
                        YCMJOB_QSYS_LIB,
                        YCMJOB_CCSID_37,
                        YCMJOB_THREAD_YES))
  {  // QYCMCIMOM Server Failed on Submit Job
#pragma convert(0)

      //l10n
      //Logger::put(Logger::ERROR_LOG, System::CIMSERVER, Logger::SEVERE,
         //"cimserver_os400::cimserver_fork() - SBMJOB failed to start the QYCMCIMOM server program!!");
    Logger::put_l(Logger::ERROR_LOG, System::CIMSERVER, Logger::SEVERE,
                "src.Server.cimserver_os400.FAILED_TO_START_SERVER",
                "$0 failed to start the $1 server program!!",
                "cimserver_os400::cimserver_fork() - SBMJOB",
                "QYCMCIMOM");

     char chData[sizeof(rc5)+sizeof(cppServ)];
     strcpy((char *)&chData,rc5);
     strcat(chData,cppServ);

#pragma convert(37)
     ycmMessage message("CPDDF80",
                        chData,
            strlen(chData),
                        "cimserver_os400::cimserver_fork()",
                        ycmCTLCIMID,
            utf8);
     message.joblogIt(UserError,ycmMessage::Diagnostic);
#pragma convert(0)

     // save the job log
     system ("QSYS/CHGJOB JOB(*) LOG(4 00 *SECLVL)");

     return(-1);    // -1 indicates to QYCMCIMOM that the server failed to start
  }

  // The QYCMCIMOM job was submitted with daemon=false.  This job can now exit.
  // This is similiar to what the unix version of this code does - the parent exits
  // after the fork( )
  return(0);
}

////////////////////////////////////////////////////
//  CancelHandler
////////////////////////////////////////////////////
void CancelHandler (_CNL_Hndlr_Parms_T *cancelParms)
{  // make sure a job log gets saved too
   system ("QSYS/CHGJOB JOB(*) LOG(4 00 *SECLVL)");
}

////////////////////////////////////////////////////
// iSeries-specific function to initialize the server.
// Does the following:
//    -- Sets the server type to QIBM_CIMOM
//       so that iNavigator can start/stop it.
//    -- Swaps the job user to QSYS.
//    -- Changes the authority of QYCMJOBD
//    -- Calls the upgrade utility
////////////////////////////////////////////////////
int ServerProcess::cimserver_initialize(void)
{
    SQLHENV    henv; // SQL environment variable
    long       attr; // SQL attribute to be set

   // setup cancel handler to make sure job log gets saved if we exit abnormally
   // TODO:  this is currently commented out because it causes build errors -
   //        it compiles just fine though.  Hopefully this problem will be fixed
   //        (it's a known problem) and we can uncomment this #pragma.
//   #pragma cancel_handler (CancelHandler, NULL)
    try {

#pragma convert(37)
   //////////////////////////////////////////
   // Change Job API call
   // Change the server type to QICM_CIMOM
   //////////////////////////////////////////
   jobChangeInfo_t chg = {1,
                          46,
                          1911,
                          'C',
                          0X40,0X40,0X40,30,
                          "QIBM_CIMOM                    ",
                         };

   // Initialize the error code structure to signal exceptions
   errorCode.Bytes_Provided = 0;

   // Call CHGJOB API with Server Type field
   EPTCALL(QWTCHGJB, ("*                         ",
            "                ",
            "JOBC0200",
            &chg,
            &errorCode), OFF, OFF);
#pragma convert(0)

   ////////////////////////////////////////////////////
   // Change authority to the qypsjobd job description
   ////////////////////////////////////////////////////
   system("QSYS/GRTOBJAUT OBJ(QSYS/QYCMJOBD) OBJTYPE(*JOBD) USER(*PUBLIC) AUT(*EXCLUDE)");

   SQLAllocEnv(&henv);  // Allocating SQL environment variable
   attr = SQL_TRUE;     // Set SQL attribute to true

   // Set the SQL server mode to true.
   // This will allow multiple connections to the same data source.
   SQLSetEnvAttr(henv,SQL_ATTR_SERVER_MODE, &attr,0);

   //--------------------------------------------------
   // Create server SSL certificate and private key
   // if they do not already exist.
   //--------------------------------------------------

   // Check if SSL is enabled on either the wbem-https or
   // wbem-exp-https ports.
   ConfigManager * configManager = ConfigManager::getInstance();
   Boolean enableHttpsConnection = String::equal(
        configManager->getCurrentValue("enableHttpsConnection"), "true");
   Boolean enableSSLExportClientVerification = String::equal(
        configManager->getCurrentValue("enableSSLExportClientVerification"), "true");
   if (enableHttpsConnection || enableSSLExportClientVerification)
   {
       // Initialize the OS400 OpenSSL wrapper.
       // This checks if the OpenSSL LPO is installed.
       // It also activates the OpenSSL *SRVPGM and gets exports.
       SSL_OS400_Init();

       // Create the certificate if needed
       // Get the location of the certificate
       String certPath;
       certPath = ConfigManager::getHomedPath(
            configManager->getCurrentValue("sslCertificateFilePath"));

       // Get the location of the private key
       String keyPath;
       keyPath = ConfigManager::getHomedPath(
            configManager->getCurrentValue("sslKeyFilePath"));

       SSL_CreateCert_OS400(keyPath, certPath);
   }
  }
  catch (Exception & e)
  {
      //l10n
      Logger::put(Logger::ERROR_LOG, System::CIMSERVER, Logger::SEVERE,
		  e.getMessage());
      return(-1);
  }
  catch (...)
  {
      //l10n
      //Logger::put(Logger::ERROR_LOG, System::CIMSERVER, Logger::SEVERE,
          //"cimerver_os400::cimserver_os400_setup() - caught unknown exception\n");
        Logger::put_l(Logger::ERROR_LOG, System::CIMSERVER, Logger::SEVERE,
            "src.Server.cimserver_os400.CAUGHT_UNKNOWN_EXCEPTION",
            "$0 caught unknown exception\n",
            "cimerver_os400::cimserver_os400_setup() -");

      return(-1);
  }

// TODO:  add this back in when we fix the problem with setupr not working in a multi-threaded environment.
  // Call into the upgrade utility.  This will perform any necessary upgrade step that need to be done.  The upgrade program keys off of marker files which are created on install.  This means that in most cases, nothing will be done unless the server is starting for the first time after an install.
//  CIMRepositoryUpdate400 obj;
//  obj.doIt();

   // TODO:  this is currently commented out because it causes build errors -
   //        it compiles just fine though.  Hopefully this problem will be fixed
   //        (it's a known problem) and we can uncomment this #pragma.
//  #pragma disable_handler

    return(0);
}

///////////////////////////////////////////////////////////////////////
// cimserver_kill()
//
// The iSeries qycmctlcimCimomServer.C (QYCMCTLCIM program) code has
// already checked that the CIMOM server is already running prior to
// calling the CIMOM server (QYCMCIMOM) and telling it to shutdown.
// However, a check is still made in this method because we have to
// find the job number in order to kill the job.
//
// For iSeries, this method is called regardless of whether we took
// errors trying to connect to the server - if the CIMOM server job
// is anywhere on the system, in any state, this method will find it
// and kill it dead!!
//
// NEVER call this method unless the server is unable to be shut down
// gracefully.
///////////////////////////////////////////////////////////////////////
int ServerProcess::cimserver_kill(int id)
{  // Need to kill the server
#pragma convert(37)
  char rc2[3] = "02"; // CIMOM server failed to end
  char cppServ[10] = "QYCMCIMOM";

  // Construct a ycmJob object
  ycmJob cppJob(YCMJOB_SRVNAME_10, YCMJOB_SRVUSER_10);
  // Find the QYCMCIMOM job
  char cppStatus  = cppJob.find(YCMJOB_ALL_NUMBERS);

  if (cppStatus == YCMJOB_FOUND)       // CIMOM Server is Running
  {
    if (cppJob.end((char *)cppJob.getNumber().c_str(), 'C', 30) == YCMJOB_END_FAILED)
    {

      char chData[sizeof(rc2)+sizeof(cppServ)];
      strcpy((char *)&chData,rc2);
      strcat(chData,cppServ);

      ycmMessage message("CPDDF81",
                         chData,
             strlen(chData),
                         "cimserver_os400::cimserver_kill()",
                         ycmCTLCIMID,
             utf8);
      message.joblogIt(UserError,ycmMessage::Diagnostic);

#pragma convert(0)

      //l10n
      //Logger::put(Logger::ERROR_LOG, System::CIMSERVER, Logger::SEVERE,
          //"cimserver_os400::cimserver_kill - FAILED to end the QYCMCIMOM job!!");
    Logger::put_l(Logger::ERROR_LOG, System::CIMSERVER, Logger::SEVERE,
            "src.Server.cimserver_os400.FAILED_TO_END_JOB",
            "$0 FAILED to end the $1 job!!",
            "cimserver_os400::cimserver_kill -",
            "QYCMCIMOM");

      return -1; // Note: this return code is ignored by the CIMOM server.
    }
  }
  // The case of the job not found is already handled in QYCMCTLCIM program
    return(0);
}

////////////////////////////////////////////////////
//  Checks if the QYCMCIMOM server job is running.
////////////////////////////////////////////////////
Boolean ServerProcess::isCIMServerRunning(void)
{
#pragma convert(37)
  // Construct a ycmJob object
  ycmJob cppJob(YCMJOB_SRVNAME_10, YCMJOB_SRVUSER_10);

  // Find the QYCMCIMOM job
  char cppStatus  = cppJob.find(YCMJOB_ALL_NUMBERS);

  if (cppStatus == YCMJOB_FOUND)       // CIMOM Server is Running
  {
      return true;
  }

  return false;
#pragma convert(0)
}

////////////////////////////////////////////////////
//  Setup a fifo for process communication
////////////////////////////////////////////////////
int init_fifo(const char * fifo_name){
    int fifo = -1;
    struct stat FIFO_STAT;

    // Need to convert the fifo name to ebcdic because
    // that is what stat and open want.
    char tmp[256];
    strcpy(tmp, fifo_name);
    AtoE(tmp);

    int stat_rc = stat( tmp, &FIFO_STAT );

    // check if the FIFO already exists
    if( S_ISFIFO( FIFO_STAT.st_mode ) ){
    // prep FIFO, on this end we only want to write to it,
    // set its I/O mode to not block on any reads
    fifo = open(tmp, O_RDWR | O_NONBLOCK);
    }
    return fifo;
}

////////////////////////////////////////////////////
//  Sends return code back to caller before exiting...
////////////////////////////////////////////////////
void ServerProcess::cimserver_exitRC(int rc){
    int fifo = init_fifo(QYCMSSERV_FIFO);

    if( fifo != -1 ){
    char rc_tmp[3];
    memset(rc_tmp, 0, 3);
    sprintf(rc_tmp,"%d",rc);
    AtoE(rc_tmp);  // qycmctlcim wants ebcdic
    write(fifo,rc_tmp,strlen(rc_tmp));
    }

    exit(rc);
}

////////////////////////////////////////////////////
// Platform specific run
////////////////////////////////////////////////////
int ServerProcess::platform_run( int argc, char** argv, Boolean shutdownOption )
{
    return cimserver_run( argc, argv, shutdownOption );
}


text:
#include "inet/routing/extras/dymo/dymo_um_omnet.h"
#include "inet/linklayer/common/Ieee802Ctrl.h"

namespace inet {

namespace inetmanet {

//#define GARBAGE_COLLECT
#ifndef DYMO_USE_STL
void NS_CLASS packet_queue_init(void)
{

    INIT_DLIST_HEAD(&PQ.head);
    PQ.len = 0;

#ifdef GARBAGE_COLLECT
    /* Set up garbage collector */
    timer_init(&PQ.garbage_collect_timer, &NS_CLASS packet_queue_timeout, &PQ);

    timer_set_timeout(&PQ.garbage_collect_timer, GARBAGE_COLLECT_TIME);
#endif
}

void NS_CLASS packet_queue_destroy(void)
{
    int count = 0;
    dlist_head_t *pos, *tmp;
    if (!dlist_empty(&PQ.head))
    {
       dlist_for_each_safe(pos, tmp, &PQ.head)
       {
           struct q_pkt *qp = (struct q_pkt *)pos;
           dlist_del(pos);

           delete  qp->p;

           free(qp);
           count++;
           PQ.len--;
       }
    }
    dlog(LOG_INFO, 0, __FUNCTION__, "Dropped %d buffered packets", count);
    //  DEBUG(LOG_INFO, 0, "Destroyed %d buffered packets!", count);
}

/* Garbage collect packets which have been queued for too long... */
int NS_CLASS packet_queue_garbage_collect(void)
{
    int count = 0;
    dlist_head_t *pos, *tmp;
    struct timeval now;

    gettimeofday(&now, NULL);

    dlist_for_each_safe(pos, tmp, &PQ.head)
    {
        struct q_pkt *qp = (struct q_pkt *)pos;
        if (timeval_diff(&now, &qp->q_time) > MAX_QUEUE_TIME)
        {

            dlist_del(pos);
            //icmpAccess.get()->sendErrorMessage(qp->p, ICMP_DESTINATION_UNREACHABLE, 0);
            //drop(qp->p);
            sendICMP(qp->p);
            free(qp);
            count++;
            PQ.len--;
        }
    }

    if (count)
    {
        dlog(LOG_DEBUG, 0, __FUNCTION__, "Dropped %d buffered packets", count);
    }

    return count;
}
/* Buffer a packet in a FIFO queue. Implemented as a linked list,
   where we add elements at the end and remove at the beginning.... */

void NS_CLASS packet_queue_add(cPacket * p, struct in_addr dest_addr)
{
    struct q_pkt *qp;
    cPacket *dgram;

    if (p->getControlInfo())
        delete p->removeControlInfo();

    if (PQ.len >= MAX_QUEUE_LENGTH)
    {
        dlog(LOG_DEBUG, 0, __FUNCTION__, "Max queue length reached,"
             " removing first packet");
        if (!dlist_empty(&PQ.head))
        {
            qp = (struct q_pkt *)PQ.head.next;

            dlist_del(PQ.head.next);
            dgram = qp->p;
            sendICMP(dgram);
            //drop(dgram);
            //icmpAccess.get()->sendErrorMessage(dgram, ICMP_DESTINATION_UNREACHABLE, ICMP_AODV_QUEUE_FULL);
            free(qp);
            PQ.len--;
        }
    }

    qp = (struct q_pkt *) malloc(sizeof(struct q_pkt));

    if (qp == NULL)
    {
        throw cRuntimeError("Dymo packet queue, Malloc failed!\n");
        exit(-1);
    }

    qp->p = p;

    qp->dest_addr = dest_addr;
    qp->inTransit = false;

    gettimeofday(&qp->q_time, NULL);
    INIT_DLIST_ELEM(&qp->l);
    dlist_add_tail(&qp->l, &PQ.head);
    PQ.len++;
}

int NS_CLASS packet_queue_set_verdict(struct in_addr dest_addr, int verdict)
{
    int count = 0;
    rtable_entry_t *rt;
    dlist_head_t *pos, *tmp;
    struct in_addr gw_addr;

    double delay = 0;
#define ARP_DELAY 0.005
    if (verdict == PQ_ENC_SEND)
    {
        gw_addr.s_addr = gateWayAddress->getInt();
        rt = rtable_find(gw_addr);
    }
    else
        rt = rtable_find(dest_addr);

    dlist_for_each_safe(pos, tmp, &PQ.head)
    {
        struct q_pkt *qp = (struct q_pkt *)pos;
        if (qp->dest_addr.s_addr == dest_addr.s_addr)
        {
            dlist_del(pos);
            switch (verdict)
            {
            case PQ_ENC_SEND:
                if (isInMacLayer())
                {
                    //drop(qp->p);
                    sendICMP(qp->p);
                }
                else if (dynamic_cast <IPv4Datagram *> (qp->p))
                {
                    /* Apparently, the link layer implementation can't handle
                        * a burst of packets. So to keep ARP happy, buffered
                        * packets are sent with ARP_DELAY seconds between
                        * sends. */
                    qp->p = pkt_encapsulate(dynamic_cast <IPv4Datagram *> (qp->p), *gateWayAddress);
                    // now Ip layer decremented again
                    // sendDelayed(qp->p, delay, "to_ip_from_network");
                    sendDelayed(qp->p, delay, "to_ip");
                    delay += ARP_DELAY;
                }
                else
                {
                    //drop(qp->p);
                    sendICMP(qp->p);
                }
                break;
            case PQ_SEND:
                if (!rt)
                    return -1;
                if (qp->inTransit)
                {
                    // drop(qp->p);
                    sendICMP(qp->p);
                }
                else
                {
                    /* Apparently, the link layer implementation can't handle
                     * a burst of packets. So to keep ARP happy, buffered
                     * packets are sent with ARP_DELAY seconds between
                     * sends. */
                    // now Ip layer decremented again
                    if (isInMacLayer())
                    {
                        Ieee802Ctrl *ctrl = new Ieee802Ctrl();
                        L3Address nextHop;
                        int iface;
                        double cost;
                        getNextHop(dest_addr.s_addr, nextHop, iface, cost);
                        ctrl->setDest(MACAddress(nextHop.getLo()));
                        //TODO ctrl->setEtherType(...);
                        qp->p->setControlInfo(ctrl);
                    }
                    sendDelayed(qp->p, delay, "to_ip");
                    delay += ARP_DELAY;
                }
                break;
            case PQ_DROP:
                // drop(qp->p);
                sendICMP(qp->p);
                // icmpAccess.get()->sendErrorMessage(qp->p, ICMP_DESTINATION_UNREACHABLE, 0);
                break;
            }
            free(qp);
            count++;
            PQ.len--;
        }
    }
    /* Update rt timeouts. must be in Dymo?*/
    /*
    rtable_entry_t *next_hop_rt, *inet_rt = NULL;
    if (rt && rt->state == VALID && (verdict == PQ_SEND || verdict == PQ_ENC_SEND)) {
        if (dest_addr.s_addr != DEV_IFINDEX(rt->ifindex).ipaddr.s_addr) {
            if (verdict == PQ_ENC_SEND && inet_rt)
                rtable_update_timeout(inet_rt);

            rtable_update_timeout(rt);
            next_hop_rt = rtable_find(rt->next_hop);
            if (next_hop_rt && next_hop_rt->state == VALID &&
                next_hop_rt->dest_addr.s_addr != rt->dest_addr.s_addr)
                rtable_update_timeout(next_hop_rt, ACTIVE_ROUTE_TIMEOUT);
        }
    }
    */
    return count;
}
#else
void NS_CLASS packet_queue_init(void)
{

    PQ.pkQueue.clear();

#ifdef GARBAGE_COLLECT
    /* Set up garbage collector */
    timer_init(&PQ.garbage_collect_timer, &NS_CLASS packet_queue_timeout, &PQ);

    timer_set_timeout(&PQ.garbage_collect_timer, GARBAGE_COLLECT_TIME);
#endif
}

void NS_CLASS packet_queue_destroy(void)
{
    int count = 0;
    while (!PQ.pkQueue.empty())
    {
        struct q_pkt *qp = PQ.pkQueue.back();
        PQ.pkQueue.pop_back();
        delete  qp->p;
        free(qp);
        count++;
    }
    dlog(LOG_INFO, 0, __FUNCTION__, "Dropped %d buffered packets", count);
    //  DEBUG(LOG_INFO, 0, "Destroyed %d buffered packets!", count);
}

/* Garbage collect packets which have been queued for too long... */
int NS_CLASS packet_queue_garbage_collect(void)
{
    int count = 0;
    struct timeval now;
    gettimeofday(&now, NULL);
    for (unsigned int i = 0; i < PQ.pkQueue.size();)
    {
        struct q_pkt *qp = PQ.pkQueue[i];
        if (timeval_diff(&now, &qp->q_time) > MAX_QUEUE_TIME)
        {

            PQ.pkQueue.erase(PQ.pkQueue.begin()+i);
            sendICMP(qp->p);
            free(qp);
            count++;
        }
        else
            i++;
    }

    if (count)
    {
        dlog(LOG_DEBUG, 0, __FUNCTION__, "Dropped %d buffered packets", count);
    }

    return count;
}
/* Buffer a packet in a FIFO queue. Implemented as a linked list,
   where we add elements at the end and remove at the beginning.... */

void NS_CLASS packet_queue_add(cPacket * p, struct in_addr dest_addr)
{
    struct q_pkt *qp;
    cPacket *dgram;

    if (p->getControlInfo())
        delete p->removeControlInfo();

    if (PQ.pkQueue.size() >= MAX_QUEUE_LENGTH)
    {
        dlog(LOG_DEBUG, 0, __FUNCTION__, "Max queue length reached,"
             " removing first packet");
        qp = PQ.pkQueue.front();
        PQ.pkQueue.erase(PQ.pkQueue.begin());
        dgram = qp->p;
        sendICMP(dgram);
        free(qp);
    }

    qp = (struct q_pkt *) malloc(sizeof(struct q_pkt));

    if (qp == NULL)
    {
        throw cRuntimeError("Dymo packet queue, Malloc failed!\n");
        exit(-1);
    }

    qp->p = p;

    qp->dest_addr = dest_addr;
    qp->inTransit = false;

    gettimeofday(&qp->q_time, NULL);
    PQ.pkQueue.push_back(qp);

}

int NS_CLASS packet_queue_set_verdict(struct in_addr dest_addr, int verdict)
{
    int count = 0;
    rtable_entry_t *rt;
    struct in_addr gw_addr;

    double delay = 0;
#define ARP_DELAY 0.005
    if (verdict == PQ_ENC_SEND)
    {
        gw_addr.s_addr = L3Address(*gateWayAddress);
        rt = rtable_find(gw_addr);
    }
    else
        rt = rtable_find(dest_addr);

    std::vector<L3Address> list;
    if (isInMacLayer())
    {
        std::vector<MACAddress> listMac;
        getApList(dest_addr.s_addr.toMAC(), listMac);
        while (!listMac.empty())
        {
            list.push_back(L3Address(listMac.back()));
            listMac.pop_back();
        }
    }
    else
    {
        std::vector<IPv4Address> listIp;
        getApListIp(dest_addr.s_addr.toIPv4(), listIp);
        while (!listIp.empty())
        {
            list.push_back(L3Address(listIp.back()));
            listIp.pop_back();
        }
    }
    while (!list.empty())
    {
        struct in_addr dest_addr;
        dest_addr.s_addr = list.back();
        list.pop_back();
        for (unsigned int i=0; i < PQ.pkQueue.size();)
        {
            struct q_pkt *qp = PQ.pkQueue[i];
            if (qp->dest_addr.s_addr == dest_addr.s_addr)
            {
                PQ.pkQueue.erase(PQ.pkQueue.begin()+i);
                switch (verdict)
                {
                    case PQ_ENC_SEND:
                        if (isInMacLayer())
                        {
                            //drop(qp->p);
                            sendICMP(qp->p);
                        }
                        else if (dynamic_cast <IPv4Datagram *> (qp->p))
                        {
                            /* Apparently, the link layer implementation can't handle
                             * a burst of packets. So to keep ARP happy, buffered
                             * packets are sent with ARP_DELAY seconds between
                             * sends. */
                            qp->p = pkt_encapsulate(dynamic_cast <IPv4Datagram *> (qp->p), *gateWayAddress);
                            // now Ip layer decremented again
                            // sendDelayed(qp->p, delay, "to_ip_from_network");
                            sendDelayed(qp->p, delay, "to_ip");
                            delay += ARP_DELAY;
                        }
                        else
                        {
                            //drop(qp->p);
                            sendICMP(qp->p);
                        }
                        break;
                    case PQ_SEND:
                        if (!rt)
                            return -1;
                        if (qp->inTransit)
                        {
                            // drop(qp->p);
                            sendICMP(qp->p);
                        }
                        else
                        {
                            /* Apparently, the link layer implementation can't handle
                             * a burst of packets. So to keep ARP happy, buffered
                             * packets are sent with ARP_DELAY seconds between
                             * sends. */
                            // now Ip layer decremented again
                            if (isInMacLayer())
                            {
                                Ieee802Ctrl *ctrl = new Ieee802Ctrl();
                                L3Address nextHop;
                                int iface;
                                double cost;
                                getNextHop(dest_addr.s_addr, nextHop, iface, cost);
                                ctrl->setDest(nextHop.toMAC());
                                //TODO ctrl->setEtherType(...);
                                qp->p->setControlInfo(ctrl);
                            }
                            sendDelayed(qp->p, delay, "to_ip");
                            delay += ARP_DELAY;
                        }
                        break;
                    case PQ_DROP:
                        // drop(qp->p);
                        sendICMP(qp->p);
                        // icmpAccess.get()->sendErrorMessage(qp->p, ICMP_DESTINATION_UNREACHABLE, 0);
                        break;
                }
                free(qp);
                count++;
            }
            else
                i++;
        }
    }
        /* Update rt timeouts. must be in Dymo?*/
    /*
    rtable_entry_t *next_hop_rt, *inet_rt = NULL;
    if (rt && rt->state == VALID && (verdict == PQ_SEND || verdict == PQ_ENC_SEND)) {
        if (dest_addr.s_addr != DEV_IFINDEX(rt->ifindex).ipaddr.s_addr) {
            if (verdict == PQ_ENC_SEND && inet_rt)
                rtable_update_timeout(inet_rt);

            rtable_update_timeout(rt);
            next_hop_rt = rtable_find(rt->next_hop);
            if (next_hop_rt && next_hop_rt->state == VALID &&
                next_hop_rt->dest_addr.s_addr != rt->dest_addr.s_addr)
                rtable_update_timeout(next_hop_rt, ACTIVE_ROUTE_TIMEOUT);
        }
    }
    */
    return count;
}

#endif

} // namespace inetmanet

} // namespace inet


text:
Praseodymium, Pr

External links

Praseodymium - Wikipedia

Praseodymium - WebElements


text:
<?xml version='1.0' encoding='utf-8'?>
<project name='bee example' basedir="."  level='log'>

	<npm g="true">coffee-script</npm>

	<!-- custom plugin -->
	<taskdef file="greeting.js"/>

	<!-- npm plugin -->
	<taskdef npm="bee-less,bee-min"/>

	<description>
		This is an bee project
	</description>

	<property file="external.properties"/>

	<target name="properties">
	  <echo>${key with spaces}</echo>
	  <echo>${tab}there is a tab before this p.</echo>
	  <echo>${message}</echo>
	</target>

	<target name="dir">
	  <basename file="/var/www/dir/abc.txt" property="basename" suffix=".txt"/>
	  <echo>'${basename}' should be 'abc.txt'</echo>
	  <dirname file="/var/www/dir/abc.txt" property="dirname"/>
	  <echo>'${dirname}' should be '/var/www/dir'</echo>
	  <extname file="/var/www/dir/abc.txt" property="extname"/>
	  <echo>'${extname}' should be '.txt'</echo>
	  <!--create file-->
	  <mkdir dir="blank-dir"/>
	  <touch file="touch.txt">some text</touch>
	  <loadfile file="touch.txt" property="touch-file"/>
	  <echo>touch file content:${touch-file}</echo>
	  <available dir="blank-dir" property="blank-dir"/>
	  <available file="touch.txt" property="touch-file"/>
	  <echo>[blank dir] should be exist: ${blank-dir}</echo>
	  <echo>touch.txt should be exist: ${touch-file}</echo>
	  <!--delete file-->
	  <delete target="blank-dir"/>
	  <delete target="touch.txt"/>
	  <available dir="blank-dir" property="blank-dir"/>
	  <available file="touch.txt" property="touch-file"/>
	  <echo>[blank dir] should not be exist: ${blank-dir}</echo>
	  <echo>touch.txt should not be exist: ${touch-file}</echo>
    </target>

	<target name="condition">
	  <condition property="cond" if="condition-yes">
		 <os platform="win32"/>
	  </condition>
	  <echo>is win32 platform: ${cond}</echo>
	</target>

	<target name="condition-yes">
		<echo>Windows platform</echo>
	</target>

	<target name="concat">
	  <concat destfile="combo.txt">
	    <header trimleading="yes">
	     ==========
	  Header
	  ==========
	  </header>
		<fileset dir="concat">
			<include type="glob" value="*"/>
		</fileset>
		<footer>
	       ===========
		Footer
		===========
	    </footer>
	  </concat>
	  <loadfile src="combo.txt" property="combo"/>
	  <echo>${combo}</echo>
	  <delete target="combo.txt"/>
	</target>

	<target name="replace">
	  <copy src="replace/hello.txt" dest="replace/hello-copy.txt"/>
	  <loadfile src="replace/hello.txt" property="replace-file"/>
	  <echo>before replace: </echo>
	  <echo>${replace-file}</echo>
	  <replace file="replace/hello.txt">
		<replacefilter token="@1@" value="#1#"/>
		<replacefilter token="#1#" value="?1?"/>
		<replacefilter token="\?1\?" value="!1!"/>
		<replacefilter token="!1!" value="z1z"/>
	  </replace>
	  <loadfile src="replace/hello.txt" property="replace-file"/>
	  <echo>after replace: </echo>
	  <echo>${replace-file}</echo>
	  <rename src="replace/hello-copy.txt" dest="replace/hello.txt"/>
    </target>

	<target name="sleep">
	  <tstamp property="current"/>
	  <echo>start to sleep 1 second, now: ${current}</echo>
	  <sleep>1000</sleep>
	  <tstamp property="current"/>
	  <echo>wake up, now: ${current}</echo>
	</target>

	<target name="node">
	 <node>
	 var os = require('os');
	 console.log('os platform: ' + os.platform());
	 console.log('setImmediate: ', setImmediate);
	 //global object: bee
	 console.log('bee version: ' + bee.version);
	 console.log('bee level: ' + bee.level);
	 bee.log("XXXXXXXXXXXXXXXXXXXX log");
	 bee.info("XXXXXXXXXXXXXXXXXXXX info");
	 bee.debug("XXXXXXXXXXXXXXXXXXXX debug");
	 bee.warn("XXXXXXXXXXXXXXXXXXXX warn");
	 console.log('current bee project: [' + bee.project.name + '] description: ' + bee.project.description);
	 </node>
	</target>

	<target name="exec">
	  <echo>node version: node -v</echo>
	  <exec stdout="true">node -v</exec>
	  <echo>execute node file: node exec.js</echo>
	  <exec stdout="true" stderr="true">node exec.js</exec>
	</target>

	<target name="plugin">
	  <echo>custom plugin: greeting.js</echo>
	  <greeting>hoho~</greeting>
	  <echo>npm plugin: less</echo>
	  <less src="plugin/example.less" dest="plugin/example.css"/>
	  <echo>npm plugin: datauri</echo>
	  <datauri file="plugin/example.css" destfile="plugin/example.datauri.css"/>
	  <echo>npm plugin: min css</echo>
	  <min src="plugin/example.datauri.css" dest="plugin/example.min.css"/>
	  <echo>exec: coffee -c -o plugin plugin/example.coffee</echo>
	  <exec>coffee -c -o plugin plugin/example.coffee</exec>
	  <echo>npm plugin: min js</echo>
	  <min src="plugin/example.js" dest="plugin/example.min.js"/>
	  <echo>npm plugin: min html</echo>
	  <min src="plugin/example.html" dest="plugin/example.min.html"/>
	  <echo>npm plugin: min png</echo>
	  <min src="plugin/example.png" dest="plugin/example.min.png"/>

	  <echo>==================CSS Transform: </echo>
	  <loadfile src="plugin/example.css" property="css"/>
	  <echo>${css}</echo>

	  <echo>==================CSS DataURI: </echo>
	  <loadfile src="plugin/example.datauri.css" property="css"/>
	  <echo>${css}</echo>

	  <echo>==================CSS min: </echo>
	  <loadfile src="plugin/example.min.css" property="css"/>
	  <echo>${css}</echo>

	  <echo>==================JS min: </echo>
	  <loadfile src="plugin/example.min.js" property="js"/>
	  <echo>${js}</echo>

	  <echo>==================HTML min: </echo>
	  <loadfile src="plugin/example.min.html" property="html"/>
	  <echo>${html}</echo>

	  <echo>==================Image min: </echo>
	  <node>
	  var fs = require('fs');
	  var getSize = function(file){
	    return fs.statSync(file).size;
	  }
	  console.log('size: ' + getSize('plugin/example.png') + ' bytes, after min: ' + getSize('plugin/example.min.png') + ' bytes');
	  </node>

	  <delete target="plugin/example.datauri.css"/>
	  <delete target="plugin/example.min.css"/>
	  <delete target="plugin/example.min.js"/>
	  <delete target="plugin/example.css"/>
	  <delete target="plugin/example.js"/>
	  <delete target="plugin/example.min.html"/>
	  <delete target="plugin/example.min.png"/>

	</target>

	<target name="build" depends="properties,dir,condition,concat,replace,sleep,node,exec,plugin">
	  <echo>build completed</echo>
	</target>

</project>


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bull. trimest. Soc. mycol. Fr. 44: 274 (1929)

#### Original name
Cribraria meylanii Brândza, 1929

### Remarks
null


text:
#region Licence

#endregion

using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using System.Security;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace WmcSoft.Time
{
    [Serializable]
    [XmlSchemaProvider("GetSchema")]
    [TypeConverter(typeof(TimeOfDayConverter))]
    public partial struct TimeOfDay : IXmlSerializable
    {
        class TimeOfDayConverter : TypeConverter
        {
            public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
            {
                return sourceType == typeof(string);
            }

            public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
            {
                return destinationType == typeof(InstanceDescriptor) || destinationType == typeof(string) || base.CanConvertTo(context, destinationType);
            }

            public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
            {
                if (value == null)
                    throw GetConvertFromException(value);

                if (value is string text) {
                    var d = DateTime.ParseExact(text, GetFormat(culture), culture);
                    return new TimeOfDay(d.Hour, d.Minute);
                }

                throw new ArgumentException(nameof(value));
            }

            [SecurityCritical]
            public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
            {
                if (destinationType != null && value is TimeOfDay time) {
                    if (destinationType == typeof(InstanceDescriptor)) {
                        var method = typeof(TimeOfDay).GetConstructor(new Type[] { typeof(int), typeof(int) });
                        var (h, m) = time;
                        return new InstanceDescriptor(method, new object[] { h, m });
                    }
                    if (destinationType == typeof(string)) {
                        return time.ToString(GetFormat(culture), culture);
                    }
                }
                return base.ConvertTo(context, culture, value, destinationType);
            }

            static string GetFormat(CultureInfo culture)
            {
                return culture.TwoLetterISOLanguageName == "iv" ? @"HH\:mm" : "t";
            }
        }

        public static XmlQualifiedName GetSchema(XmlSchemaSet _)
        {
            return new XmlQualifiedName("time", "http://www.w3.org/2001/XMLSchema");
        }

        XmlSchema IXmlSerializable.GetSchema()
        {
            return null;
        }

        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            var s = reader.NodeType == XmlNodeType.Element
                ? reader.ReadElementContentAsString()
                : reader.ReadContentAsString();
            if (!DateTime.TryParseExact(s, "HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime d)) {
                throw new FormatException();
            }

            this = new TimeOfDay(d.Hour, d.Minute);
        }

        void IXmlSerializable.WriteXml(XmlWriter writer)
        {
            writer.WriteString(_storage.ToString(@"hh\:mm", CultureInfo.InvariantCulture));
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SpedBr.AppTeste.Utils;

namespace SpedBr.AppTeste
{
    public partial class frmHome : Form
    {
        public frmHome()
        {
            InitializeComponent();

            InicializaFormHome();
        }

        private void InicializaFormHome()
        {
            InicializaLabels();
        }

        private void InicializaLabels()
        {
            // Label Iniciar
            var lblStartPosition = this.PointToScreen(lblDeclaracoes.Location);
            lblStartPosition = pictureBoxHomePage.PointToClient(lblStartPosition);
            lblDeclaracoes.Parent = pictureBoxHomePage;
            lblDeclaracoes.Location = lblStartPosition;
            lblDeclaracoes.BackColor = Color.Transparent;

            // Label Opção 1
            var lblOption1Position = this.PointToScreen(lblDecOption1.Location);
            lblOption1Position = pictureBoxHomePage.PointToClient(lblOption1Position);
            lblDecOption1.Parent = pictureBoxHomePage;
            lblDecOption1.Location = lblOption1Position;
            lblDecOption1.BackColor = Color.Transparent;
            lblDecOption1.Text = "Sintegra";

            // Label Opção 1 Events
            lblDecOption1.LinkClicked += (sender, args) =>
            {
                try
                {
                    //TODO: Criar form para Sintegra
                    //this.ParentForm.NovaInstanciaChildren(typeof(frmMain));
                }
                catch (Exception ex)
                {
                    FormUtils.ExibirMensagem(
                        $"Ocorreu um erro tentar abrir a janela do {lblDecOption1.Text}.{Environment.NewLine}Mensagem:{Environment.NewLine}{ex.Message}",
                        FormUtils.TipoMensagem.Erro);
                }
            };

            // Label Opção 2
            var lblOption2Position = this.PointToScreen(lblDecOption2.Location);
            lblOption2Position = pictureBoxHomePage.PointToClient(lblOption2Position);
            lblDecOption2.Parent = pictureBoxHomePage;
            lblDecOption2.Location = lblOption2Position;
            lblDecOption2.BackColor = Color.Transparent;
            lblDecOption2.Text = "SPED Fiscal";

            // Label Opção 2 Events
            lblDecOption2.LinkClicked += (sender, args) =>
            {

            };

            // Label Links
            var lblLinksPosition = this.PointToScreen(lblLinks.Location);
            lblLinksPosition = pictureBoxHomePage.PointToClient(lblLinksPosition);
            lblLinks.Parent = pictureBoxHomePage;
            lblLinks.Location = lblLinksPosition;
            lblLinks.BackColor = Color.Transparent;

            // Label Link 1
            var lblLink1Position = this.PointToScreen(lblLink1.Location);
            lblLink1Position = pictureBoxHomePage.PointToClient(lblLink1Position);
            lblLink1.Parent = pictureBoxHomePage;
            lblLink1.Location = lblLink1Position;
            lblLink1.BackColor = Color.Transparent;
            lblLink1.Text = "GitHub";

            // Label Link 1 Events
            lblLink1.LinkClicked += (sender, args) =>
            {
                Process.Start("https://github.com/samuelroliveira/SPEDBr");
            };
        }
    }
}


text:
class LogStuff
  NAMESPACE = :log

  def self.use_logstasher?
    LogStasher.enabled?
  end

  def self.get_thread_current(name)
    Thread.current[NAMESPACE] ||= {
      current_fields: {},
      current_tags: Set.new
    }
    Thread.current[NAMESPACE][name].dup
  end

  def self.set_thread_current(name, value)
    Thread.current[NAMESPACE] ||= {
      current_fields: {},
      current_tags: Set.new
    }
    Thread.current[NAMESPACE][name] = value.dup
  end

  def self.log(severity = 'info', *args, &block)
    return unless block_given?

    if use_logstasher?
      return unless LogStasher.logger.send("#{severity}?")

      msg = yield
      event = build_event(*args, msg)
      LogStasher.logger << "#{event.to_json} \n"
    else
      return unless Rails.logger.send("#{severity}?")
      Rails.logger.send(severity, &block)
    end
  end

  def self.build_event(*args, msg)
    local_fields, local_tags = compile_fields_and_tags(args)

    LogStash::Event.new('@source' => LogStasher.source,
                        '@severity' => severity,
                        'message' => msg,
                        '@tags' => get_thread_current(:current_tags).merge(local_tags),
                        '@fields' => get_thread_current(:current_fields).merge(local_fields))
  end

  # rubocop:disable Metrics/MethodLength
  def self.compile_fields_and_tags(args)
    local_fields = {}
    local_tags = Set.new
    args.each do |arg|
      case arg
      when Hash
        local_fields.merge!(arg)
      when Symbol
        local_tags.add(arg)
      when Array
        local_tags.merge(arg)
      end
    end
    [local_fields, local_tags]
  end
  # rubocop:enable Metrics/MethodLength

  ['fatal', 'error', 'warn', 'info', 'debug'].each do |severity|
    # rubocop:disable Security/Eval
    eval <<-MULTILINE, nil, __FILE__, __LINE__ + 1
      def self.#{severity}(*args, &block)                 # def fatal(*args, &block)
        self.log(:#{severity}, *args, &block )            #   self.log('fatal', *args, &block)
      end                                                 # end
    MULTILINE
    # rubocop:enable Security/Eval
  end

  def self.tag(*tags)
    original_tags = get_thread_current(:current_tags)
    current_tags = original_tags.dup + tags.flatten
    set_thread_current(:current_tags, current_tags)
    yield
    set_thread_current(:current_tags, original_tags)
  end

  def self.metadata(*pairs)
    original_fields = get_thread_current(:current_fields) || {}
    current_fields = original_fields.dup
    pairs.flatten.each do |pair|
      pair.each do |k, v|
        current_fields[k.to_sym] = v
      end
    end
    set_thread_current(:current_fields, current_fields)
    yield
    set_thread_current(:current_fields, original_fields)
  end
end


text:
<?php
namespace app\models\levels;

interface Countable
{
    public function getCount();
}


text:
* Add CSV as a new built-in format for benchmark results
* Open up API to allow users to define their own formats for benchmark results
* Increase precision to 3dp when minimum result is between 1 & 10 seconds (note: CSV ignores and uses full precision)
* Internal refactoring
* Upgrade dependencies


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

    <link rel="stylesheet" type="text/css" href="style.min.css" />
    <title>Colorpicker</title>

                HEX
                <input id="hex" type="text" value="" />

                R:
                <input id="rgb_r" type="number" value="" />
                G:
                <input id="rgb_g" type="number" value="" />
                B:
                <input id="rgb_b" type="number" value="" />

                Cancel
                Back Color
                Text Color


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>My quick daily scrummaster checklist</title>
<meta name="generator" content="Org mode" />
<meta name="author" content="John Cumming" />

<link rel="stylesheet"
                         href="/css/solarized-dark.css"
                         type="text/css"/>

John's Draft Blog | home

My quick daily scrummaster checklist

Table of Contents

Introduction

Checklist

Introduction

It's been a while since I posted on my blog and I hope it is not
feeling neglected due to my lack of attention. I have been spending a
lot of time recently planning for my wedding and of course working
hard on project work. As I prepare to have a few weeks away from work
I thought I would put together a checklist that I try to go through
mentally before each Daily Scrum.

I am sure there are many more things that could be added to the list
for your own application of scrum, but for ours, which works as it
does, with few team members (3), remote working, non-dedicated
resources and the many distractions we have, this is my quick
checklist.

Checklist

Is the backlog estimated as much as it needs to, are there any
outstanding new items that impact the delivery of the current
release that have no estimates.

Check the burndown /  burnup charts to get a quick snapshot of
progress. I keep mentioning the report to everyone, but I don't
know if anyone other than me ever bothers to view it??!!

Chase up the PO on items for Signing off.

Check that upcoming items that haven't been started have User
Acceptance Criteria ready for the team

Ensure that the items that are being worked on are In Progress
and assigned to the correct person

Check that items that are not being worked on are either
New/Approved and have no person assigned to them…. Although there
are probably some exceptions to this?

As I said, its a simple checklist that suits our team. What would be
your checklist?

Author: John Cumming

Created: 2018-07-22 Sun 17:51

Validate


text:
package net.voldrich.smscsim.spring.auto;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import net.voldrich.smscsim.server.DelayedRecord;
import net.voldrich.smscsim.server.DelayedRequestSender;
import com.cloudhopper.smpp.SmppSession;
import com.cloudhopper.smpp.pdu.PduRequest;

@Component
public class DelayedRequestSenderImpl extends DelayedRequestSender<DelayedRecord> {

	private static final Logger logger = LoggerFactory.getLogger(DelayedRequestSenderImpl.class);

	@Autowired
	private SmppSessionManager sessionManager;

	private long sendTimoutMilis = 1000;

	public DelayedRequestSenderImpl() {
		// empty constructor
	}

	@Override
	protected void handleDelayedRecord(DelayedRecord delayedRecord) throws Exception {
		SmppSession session = delayedRecord.getUsedSession(sessionManager);
		PduRequest request = delayedRecord.getRequest(sessionManager.getNextSequenceNumber());
		if (session != null && session.isBound()) {
			session.sendRequestPdu(request, sendTimoutMilis, false);
		} else {
			logger.info("Session does not exist or is not bound {}. Request not sent {}", session, request);
		}
	}

	public SmppSessionManager getSessionManager() {
		return sessionManager;
	}

	public void setSessionManager(SmppSessionManager sessionManager) {
		this.sessionManager = sessionManager;
	}

	@PostConstruct
	public void init() throws Exception {
		start();
	}

	@PreDestroy
	public void cleanUp() throws Exception {
		stop();
	}

	public long getSendTimoutMilis() {
		return sendTimoutMilis;
	}

	public void setSendTimoutMilis(long sendTimoutMilis) {
		this.sendTimoutMilis = sendTimoutMilis;
	}

}


text:
layout: docs
title: Druid adapter
permalink: /docs/druid_adapter.html
---
<!--
{% comment %}
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements.  See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
{% endcomment %}
-->

[Druid](http://druid.io/) is a fast column-oriented distributed data
store. It allows you to execute queries via a
[JSON-based query language](http://druid.io/docs/0.9.0/querying/querying.html),
in particular OLAP-style queries.
Druid can be loaded in batch mode or continuously; one of Druid's key
differentiators is its ability to
[load from a streaming source such as Kafka](http://druid.io/docs/0.9.0/ingestion/stream-ingestion.html)
and have the data available for query within milliseconds.

Calcite's Druid adapter allows you to query the data using SQL,
combining it with data in other Calcite schemas.

First, we need a
[model definition]({{ site.baseurl }}/docs/model.html).
The model gives Calcite the necessary parameters to create an instance
of the Druid adapter.

A basic example of a model file is given below:

{% highlight json %}
{
  "version": "1.0",
  "defaultSchema": "wiki",
  "schemas": [
    {
      "type": "custom",
      "name": "wiki",
      "factory": "org.apache.calcite.adapter.druid.DruidSchemaFactory",
      "operand": {
        "url": "http://localhost:8082/druid/v2/?pretty"
      },
      "tables": [
        {
          "name": "wiki",
          "factory": "org.apache.calcite.adapter.druid.DruidTableFactory",
          "operand": {
            "dataSource": "wikiticker",
            "interval": "1900-01-09T00:00:00.000Z/2992-01-10T00:00:00.000Z",
            "timestampColumn": "time",
            "dimensions": [
              "channel",
              "cityName",
              "comment",
              "countryIsoCode",
              "countryName",
              "isAnonymous",
              "isMinor",
              "isNew",
              "isRobot",
              "isUnpatrolled",
              "metroCode",
              "namespace",
              "page",
              "regionIsoCode",
              "regionName",
              "user"
            ],
            "metrics": [
              {
                "name" : "count",
                "type" : "count"
              },
              {
                "name" : "added",
                "type" : "longSum",
                "fieldName" : "added"
              },
              {
                "name" : "deleted",
                "type" : "longSum",
                "fieldName" : "deleted"
              },
              {
                "name" : "delta",
                "type" : "longSum",
                "fieldName" : "delta"
              },
              {
                "name" : "user_unique",
                "type" : "hyperUnique",
                "fieldName" : "user"
              }
            ]
          }
        }
      ]
    }
  ]
}
{% endhighlight %}

This file is stored as `druid/src/test/resources/druid-wiki-model.json`,
so you can connect to Druid via
[`sqlline`](https://github.com/julianhyde/sqlline)
as follows:

{% highlight bash %}
$ ./sqlline
sqlline> !connect jdbc:calcite:model=druid/src/test/resources/druid-wiki-model.json admin admin
sqlline> select "countryName", cast(count(*) as integer) as c
         from "wiki"
         group by "countryName"
         order by c desc limit 5;
+----------------+------------+
| countryName    |     C      |
+----------------+------------+
|                | 35445      |
| United States  | 528        |
| Italy          | 256        |
| United Kingdom | 234        |
| France         | 205        |
+----------------+------------+
5 rows selected (0.279 seconds)
sqlline>
{% endhighlight %}

That query shows the top 5 countries of origin of wiki page edits
on 2015-09-12 (the date covered by the wikiticker data set).

Now let's see how the query was evaluated:

{% highlight bash %}
sqlline> !set outputformat csv
sqlline> explain plan for
         select "countryName", cast(count(*) as integer) as c
         from "wiki"
         group by "countryName"
         order by c desc limit 5;
'PLAN'
'EnumerableInterpreter
  BindableProject(countryName=[$0], C=[CAST($1):INTEGER NOT NULL])
    BindableSort(sort0=[$1], dir0=[DESC], fetch=[5])
      DruidQuery(table=[[wiki, wiki]], groups=[{4}], aggs=[[COUNT()]])
'
1 row selected (0.024 seconds)
{% endhighlight %}

That plan shows that Calcite was able to push down the `GROUP BY`
part of the query to Druid, including the `COUNT(*)` function,
but not the `ORDER BY ... LIMIT`. (We plan to lift this restriction;
see [[CALCITE-1206](https://issues.apache.org/jira/browse/CALCITE-1206)].)

# Foodmart data set

The test VM also includes a data set that denormalizes
the sales, product and customer tables of the Foodmart schema
into a single Druid data set called "foodmart".

You can access it via the
`druid/src/test/resources/druid-foodmart-model.json` model.


text:
package org.envbuild.spring.test;

/**
 *
 * @author Salamansar
 */
public class Category {
    private Long id;
    private String name;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


text:
<?php

final class PhabricatorDashboardFulltextEngine
  extends PhabricatorFulltextEngine {

  protected function buildAbstractDocument(
    PhabricatorSearchAbstractDocument $document,
    $object) {

    $dashboard = $object;

    $document->setDocumentTitle($dashboard->getName());

    $document->addRelationship(
      $dashboard->isArchived()
        ? PhabricatorSearchRelationship::RELATIONSHIP_CLOSED
        : PhabricatorSearchRelationship::RELATIONSHIP_OPEN,
      $dashboard->getPHID(),
      PhabricatorDashboardDashboardPHIDType::TYPECONST,
      PhabricatorTime::getNow());
  }

}


text:
package main

import "github.com/junegunn/fzf/src"

var revision string

func main() {
	fzf.Run(fzf.ParseOptions(), revision)
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.camunda.bpm</groupId>
    <artifactId>camunda-parent</artifactId>
    <relativePath>../parent</relativePath>
    <version>7.11.0-SNAPSHOT</version>
  </parent>

  <groupId>org.camunda.bpm</groupId>
  <artifactId>camunda-database-settings</artifactId>
  <packaging>pom</packaging>
  <name>camunda BPM - database settings</name>
  <description>Provides general dependencies and profiles for database testing</description>

  <properties>

    <!-- database driver versions -->
    <version.h2>1.4.190</version.h2>
    <version.oracle-12>12.1.0.2</version.oracle-12>
    <version.oracle-11>11.2.0.4</version.oracle-11>
    <version.oracle-10>10.2.0.5</version.oracle-10>
    <version.oracle>${version.oracle-11}</version.oracle>
    <version.mariadb>1.1.8</version.mariadb>
    <version.mariadb.galera>1.6.3</version.mariadb.galera>
    <version.mysql>5.1.21</version.mysql>
    <version.sqlserver.oss>1.3.1</version.sqlserver.oss>
    <version.sqlserver>4.0</version.sqlserver>
    <version.db2-11.1>11.1.1.1</version.db2-11.1>
    <version.db2-10.5>10.5.0.5</version.db2-10.5>
    <version.db2-10.1>10.1.0.4</version.db2-10.1>
    <version.db2-9.7>9.7</version.db2-9.7>
    <version.db2>${version.db2-9.7}</version.db2>
    <version.postgresql>9.3-1102-jdbc4</version.postgresql>

    <!-- needed for sql script and backward compatibility checks -->
    <camunda.version.old>7.10.0</camunda.version.old>
  </properties>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>${version.h2}</version>
      </dependency>
      <dependency>
        <groupId>com.oracle.jdbc</groupId>
        <artifactId>ojdbc6</artifactId>
        <version>${version.oracle}</version>
      </dependency>
      <dependency>
        <groupId>com.oracle.jdbc</groupId>
        <artifactId>ojdbc14</artifactId>
        <version>${version.oracle-10}</version>
      </dependency>
      <dependency>
        <groupId>org.mariadb.jdbc</groupId>
        <artifactId>mariadb-java-client</artifactId>
        <version>${version.mariadb}</version>
      </dependency>
      <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${version.mysql}</version>
      </dependency>
      <dependency>
        <groupId>net.sourceforge.jtds</groupId>
        <artifactId>jtds</artifactId>
        <version>${version.sqlserver.oss}</version>
      </dependency>
      <dependency>
        <groupId>com.microsoft.sqlserver</groupId>
        <artifactId>sqljdbc4</artifactId>
        <version>${version.sqlserver}</version>
      </dependency>
      <dependency>
        <groupId>com.ibm.db2.jcc</groupId>
        <artifactId>db2jcc4</artifactId>
        <version>${version.db2}</version>
      </dependency>
      <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>${version.postgresql}</version>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>sql-maven-plugin</artifactId>
          <dependencies>
            <dependency>
              <groupId>org.mariadb.jdbc</groupId>
              <artifactId>mariadb-java-client</artifactId>
              <version>${version.mariadb}</version>
            </dependency>
            <dependency>
              <groupId>mysql</groupId>
              <artifactId>mysql-connector-java</artifactId>
              <version>${version.mysql}</version>
            </dependency>
            <dependency>
              <groupId>com.oracle.jdbc</groupId>
              <artifactId>ojdbc6</artifactId>
              <version>${version.oracle}</version>
            </dependency>
            <dependency>
              <groupId>com.oracle.jdbc</groupId>
              <artifactId>ojdbc14</artifactId>
              <version>${version.oracle-10}</version>
            </dependency>
            <dependency>
              <groupId>com.ibm.db2.jcc</groupId>
              <artifactId>db2jcc4</artifactId>
              <version>${version.db2}</version>
            </dependency>
            <dependency>
              <groupId>com.microsoft.sqlserver</groupId>
              <artifactId>sqljdbc4</artifactId>
              <version>${version.sqlserver}</version>
            </dependency>
            <dependency>
              <groupId>org.postgresql</groupId>
              <artifactId>postgresql</artifactId>
              <version>${version.postgresql}</version>
            </dependency>
            <dependency>
              <groupId>com.h2database</groupId>
              <artifactId>h2</artifactId>
              <version>${version.h2}</version>
            </dependency>
          </dependencies>
          <configuration>
            <driver>${database.driver}</driver>
            <url>${database.url}</url>
            <username>${database.username}</username>
            <password>${database.password}</password>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>

  <profiles>
    <profile>
      <id>db2</id>
      <properties>
        <database.type>db2</database.type>
        <database.driver>com.ibm.db2.jcc.DB2Driver</database.driver>
        <database.datasource.class>com.ibm.db2.jcc.DB2SimpleDataSource</database.datasource.class>
      </properties>

      <dependencies>
        <dependency>
          <groupId>com.ibm.db2.jcc</groupId>
          <artifactId>db2jcc4</artifactId>
          <scope>test</scope>
        </dependency>
      </dependencies>
    </profile>
    <profile>
      <id>db2-111</id>
      <properties>
        <version.db2>${version.db2-11.1}</version.db2>
      </properties>
    </profile>
    <profile>
      <id>db2-105</id>
      <properties>
        <version.db2>${version.db2-10.5}</version.db2>
      </properties>
    </profile>
    <profile>
      <id>db2-101</id>
      <properties>
        <version.db2>${version.db2-10.1}</version.db2>
      </properties>
    </profile>
    <profile>
      <id>db2-97</id>
      <properties>
        <version.db2>${version.db2-9.7}</version.db2>
      </properties>
    </profile>

    <profile>
      <id>h2-in-memory</id>
      <activation>
        <activeByDefault>true</activeByDefault>
      </activation>
      <properties>
        <database.url>jdbc:h2:mem:camunda;DB_CLOSE_DELAY=1000;MVCC=true;LOCK_TIMEOUT=10000;MV_STORE=false</database.url>
        <database.driver>org.h2.Driver</database.driver>
        <database.username>sa</database.username>
        <database.password />
        <hibernate.dialect>org.hibernate.dialect.H2Dialect</hibernate.dialect>
      </properties>
      <dependencies>
        <dependency>
          <groupId>com.h2database</groupId>
          <artifactId>h2</artifactId>
          <scope>test</scope>
        </dependency>
      </dependencies>
    </profile>

    <profile>
      <id>h2</id>
      <properties>
        <database.host>${project.parent.basedir}/target/h2/</database.host>
        <database.name>process-engine</database.name>
        <database.username>sa</database.username>
        <database.password>sa</database.password>
        <database.port>18080</database.port>
        <!-- This url has to consistent for the subprojects: {server}-runtime and webapp-integration-tests -->
        <database.url>jdbc:h2:${database.host}${database.name};MVCC=TRUE;AUTO_SERVER=TRUE;AUTO_SERVER_PORT=${database.port};LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE;MV_STORE=false</database.url>

        <database.type>h2</database.type>
        <database.driver>org.h2.Driver</database.driver>
        <database.datasource.class>org.h2.jdbcx.JdbcDataSource</database.datasource.class>
        <jboss.datasource.filename>h2-ds.xml</jboss.datasource.filename>
        <hibernate.dialect>org.hibernate.dialect.H2Dialect</hibernate.dialect>
      </properties>
      <dependencies>
        <dependency>
          <groupId>com.h2database</groupId>
          <artifactId>h2</artifactId>
          <scope>test</scope>
        </dependency>
      </dependencies>
    </profile>

    <profile>
      <id>mariadb</id>
      <properties>
        <database.type>mariadb</database.type>
        <database.driver>org.mariadb.jdbc.Driver</database.driver>
        <database.datasource.class>org.mariadb.jdbc.MySQLDataSource</database.datasource.class>
      </properties>

      <dependencies>
        <dependency>
          <groupId>org.mariadb.jdbc</groupId>
          <artifactId>mariadb-java-client</artifactId>
          <scope>test</scope>
        </dependency>
      </dependencies>
    </profile>
    <profile>
      <id>mariadb-galera</id>
      <properties>
        <version.mariadb>${version.mariadb.galera}</version.mariadb>
      </properties>
    </profile>

    <profile>
      <id>mysql</id>
      <properties>
        <database.type>mysql</database.type>
        <database.driver>com.mysql.jdbc.Driver</database.driver>
        <database.datasource.class>com.mysql.jdbc.jdbc2.optional.MysqlDataSource</database.datasource.class>
      </properties>

      <dependencies>
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <scope>test</scope>
        </dependency>
      </dependencies>
    </profile>

    <profile>
      <id>oracle</id>
      <properties>
        <database.type>oracle</database.type>
        <database.driver>oracle.jdbc.OracleDriver</database.driver>
        <database.datasource.class>oracle.jdbc.pool.OracleDataSource</database.datasource.class>
      </properties>
    </profile>
    <profile>
      <id>oracle-10</id>
      <dependencies>
        <dependency>
          <groupId>com.oracle.jdbc</groupId>
          <artifactId>ojdbc14</artifactId>
          <scope>test</scope>
        </dependency>
      </dependencies>
    </profile>
    <profile>
      <id>oracle-11</id>
      <properties>
        <version.oracle>${version.oracle-11}</version.oracle>
      </properties>
      <dependencies>
        <dependency>
          <groupId>com.oracle.jdbc</groupId>
          <artifactId>ojdbc6</artifactId>
          <scope>test</scope>
        </dependency>
      </dependencies>
    </profile>
    <profile>
      <id>oracle-12</id>
      <properties>
        <version.oracle>${version.oracle-12}</version.oracle>
      </properties>
      <dependencies>
        <dependency>
          <groupId>com.oracle.jdbc</groupId>
          <artifactId>ojdbc6</artifactId>
          <scope>test</scope>
        </dependency>
      </dependencies>
    </profile>

    <profile>
      <id>postgresql</id>
      <properties>
        <database.type>postgres</database.type>
        <database.driver>org.postgresql.Driver</database.driver>
        <database.datasource.class>org.postgresql.ds.PGSimpleDataSource</database.datasource.class>
        <jboss.datasource.filename>postgresql-ds.xml</jboss.datasource.filename>
        <hibernate.dialect>org.hibernate.dialect.PostgreSQLDialect</hibernate.dialect>
      </properties>

      <dependencies>
        <dependency>
          <groupId>org.postgresql</groupId>
          <artifactId>postgresql</artifactId>
          <scope>test</scope>
        </dependency>
      </dependencies>
    </profile>
    <profile>
      <id>postgresql-xa</id>
      <properties>
        <database.datasource.class>org.postgresql.xa.PGXADataSource</database.datasource.class>
        <jboss.datasource.filename>postgresql-xa-ds.xml</jboss.datasource.filename>
      </properties>
    </profile>

    <profile>
      <id>sqlserver</id>
      <properties>
        <database.type>mssql</database.type>
        <database.driver>com.microsoft.sqlserver.jdbc.SQLServerDriver</database.driver>
        <database.datasource.class>com.microsoft.sqlserver.jdbc.SQLServerDataSource</database.datasource.class>
      </properties>

      <dependencies>
        <dependency>
          <groupId>com.microsoft.sqlserver</groupId>
          <artifactId>sqljdbc4</artifactId>
          <scope>test</scope>
        </dependency>
      </dependencies>
    </profile>
  </profiles>

</project>