text:
package edu.harvard.econcs.turkserver.server;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Good factories should cache an experiment to minimize server lag,
 * using the run() method
 *
 * @author mao
 *
 * @param <T>
 */
@Deprecated
public abstract class ExpServerFactory<T> implements Runnable {

	/**
	 * Gets a new experiment.
	 *
	 * @param host
	 * @param clients
	 * @return
	 * @throws ExperimentFactoryException
	 */
	public abstract T getNewExperiment(GroupServer host, ConcurrentHashMap<String, Boolean> clients)
	throws ExperimentFactoryException;

	public abstract int getExperimentSize();

	/**
	 * Init method which can register serializers, etc
	 * @param host
	 */
	public abstract void doInit(GroupServer host);

	/**
	 * Default run method, which does nothing.
	 */
	public void run() {

	}

	public static class ExperimentFactoryException extends Exception {
		private static final long serialVersionUID = -5765011132751659410L;
	}

}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

/**
 * EventSubscription represents a subscription to a particular event. It can
 * remove its own subscription.
 */
class EventSubscription {

  /**
   * @param {EventSubscriptionVendor} subscriber the subscriber that controls
   *   this subscription.
   */
  constructor(subscriber: EventSubscriptionVendor) {
    this.subscriber = subscriber;
  }

  /**
   * Removes this subscription from the subscriber that controls it.
   */
  remove() {
    if (this.subscriber) {
      this.subscriber.removeSubscription(this);
      this.subscriber = null;
    }
  }
}

module.exports = EventSubscription;


text:
namespace ChainUtils.Protocol
{
	public class UnknowPayload : Payload
	{
		private byte[] _data = new byte[0];
		public byte[] Data
		{
			get
			{
				return _data;
			}
			set
			{
				_data = value;
			}
		}
		public override void ReadWriteCore(BitcoinStream stream)
		{
			stream.ReadWrite(ref _data);
		}
	}
}


text:
package com.linkedin.pinot.controller.api.events;

public enum SchemaEventType {
  CREATE, UPDATE, DELETE
}


text:
.. Bricks documentation master file, created by
   sphinx-quickstart on Fri Nov  7 11:30:16 2014.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to Bricks's documentation!
==================================

Bricks is a Django application that helps you to sort heterogeneous models
applying a set of criteria.

Suppose for example that your site publishes news and videos and you need
to show them on a single page mixed together and sorted by one or more criteria.

Depending on how complex your models and your criteria are, it can get pretty
tricky.

The :doc:`usage` will guide you through a complete tutorial to explain the
concepts behind Bricks and to show how simple can be to achieve that goal.

Requirements
------------

========  ======
Python 2  >= 2.7
Python 3  >= 3.4
Django    >= 1.8
========  ======

Contents
--------

.. toctree::
   :maxdepth: 2

   quickstart
   usage
   advanced_usage
   api
   changelog

Indices and tables
==================

* :ref:`genindex`
* :ref:`search`


text:
  # Create an empty array that takes a STRING
  # Break the string up by words and PUSH to the array
  # Go through each word inside the array and reverse it
  # JOIN the words back together and print the new string

# Initial Solution
def reverse_words(sentence)
  new_sentence = []
  reversed_sentence = []
  new_sentence = sentence.split(" ")
    new_sentence.each do |word|
      new_word = word.reverse
      reversed_sentence << new_word
    end
  reversed_sentence.join(" ")
end

# Refactored Solution

def reverse_words(sentence)
  reversed_sentence = []
  split_sentence = sentence.split(" ")
    split_sentence.each do |word|
      new_word = word.reverse
      reversed_sentence << new_word
    end
  reversed_sentence.join(" ")
end

=begin
Reflection
What concepts did you review in this challenge?
  The concepts that we reviewed in this challenge was taking a string and creating an array to split it up then joining it back after. This was a good challenge for me because this is something that is still pretty confusing for me.
What is still confusing to you about Ruby?
  I think just getting more comfortable with this and getting use to .split and .join. In this challenge we forgot that .split automatically creates an array.
What are you going to study to get more prepared for Phase 1?
  I am going to study all the ruby concepts a little bit more and get more familiar with it.
=end


text:
export interface AjaxOptions {
    type: string;
    url: string;
    accept?: string | undefined;
    dataType?: string | undefined;
    beforeSend?: ((xhr: XMLHttpRequest, options: AjaxOptions) => void) | undefined;
    success?: ((response: any, statusText: XMLHttpRequest['statusText'], xhr: XMLHttpRequest) => void) | undefined;
    error?: ((response: any, statusText: XMLHttpRequest['statusText'], xhr: XMLHttpRequest) => void) | undefined;
    complete?: ((xhr: XMLHttpRequest, statusText: XMLHttpRequest['statusText']) => void) | undefined;
    data?: Document | BodyInit | null | undefined;
    crossDomain?: boolean | undefined;
    withCredentials?: boolean | undefined;
}

export function ajax(options: AjaxOptions): void;
export function href(element: HTMLElement): string | undefined;
export function isCrossDomain(url: string): boolean;


text:
<?php

namespace SymphonyCms\Exceptions;

use \Exception;
use \SymphonyCms\Exceptions\GenericExceptionHandler;
use \SymphonyCms\Toolkit\Page;

/**
 * The `SymphonyErrorPageHandler` extends the `GenericExceptionHandler`
 * to allow the template for the exception to be provided from the `TEMPLATES`
 * directory
 */
class SymphonyErrorPageHandler extends GenericExceptionHandler
{
    /**
     * The render function will take a `SymphonyErrorPage` exception and
     * output a HTML page. This function first checks to see if their is a custom
     * template for this exception otherwise it reverts to using the default
     * `usererror.generic.php`
     *
     * @param Exception $e
     *  The Exception object
     * @return string
     *  An HTML string
     */
    public static function render(Exception $e)
    {
        if ($e->getTemplate() === false) {
            Page::renderStatusCode($e->getHttpStatusCode());

            if (isset($e->getAdditional()->header)) {
                header($e->getAdditional()->header);
            }

            echo '
Symphony Fatal Error

'.$e->getMessage().'
';
            exit;
        }

        include($e->getTemplate());
    }
}


text:
package dao.mapper;

import java.util.List;
import model.user.TUser;
import model.user.TUserExample;
import org.apache.ibatis.annotations.Param;

public interface TUserMapper {
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbg.generated Tue Aug 15 01:20:35 CST 2017
     */
    long countByExample(TUserExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbg.generated Tue Aug 15 01:20:35 CST 2017
     */
    int deleteByExample(TUserExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbg.generated Tue Aug 15 01:20:35 CST 2017
     */
    int deleteByPrimaryKey(Integer id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbg.generated Tue Aug 15 01:20:35 CST 2017
     */
    int insert(TUser record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbg.generated Tue Aug 15 01:20:35 CST 2017
     */
    int insertSelective(TUser record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbg.generated Tue Aug 15 01:20:35 CST 2017
     */
    List<TUser> selectByExample(TUserExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbg.generated Tue Aug 15 01:20:35 CST 2017
     */
    TUser selectByPrimaryKey(Integer id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbg.generated Tue Aug 15 01:20:35 CST 2017
     */
    int updateByExampleSelective(@Param("record") TUser record, @Param("example") TUserExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbg.generated Tue Aug 15 01:20:35 CST 2017
     */
    int updateByExample(@Param("record") TUser record, @Param("example") TUserExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbg.generated Tue Aug 15 01:20:35 CST 2017
     */
    int updateByPrimaryKeySelective(TUser record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbg.generated Tue Aug 15 01:20:35 CST 2017
     */
    int updateByPrimaryKey(TUser record);
}


text:
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";

const FUNCTIONS_REGION = "europe-west1";

admin.initializeApp();

// Since this code will be running in the Cloud Functions environment
// we call initialize Firestore without any arguments because it
// detects authentication from the environment.
const firestore = admin.firestore();

// note that we access firestore as admin and thus bypass any rules defined for it

// triggered when a movie is created
export const createMovie = functions
  .region(FUNCTIONS_REGION)
  .firestore.document("users/{userId}/movies/{movieId}")
  .onCreate((data, context) => {
    // get the user document reference for the current user
    const userDocRef = firestore.doc(`users/${context.params.userId}`);

    // encapsulate into transaction
    return firestore.runTransaction((transaction) => {
      return transaction.get(userDocRef).then((userDoc) => {
        let movies = 0;

        if (userDoc.exists) {
          const doc = userDoc.data();

          if (doc !== undefined) {
            if (!("movieCount" in doc)) {
              movies = 1;
            } else {
              movies = doc["movieCount"] + 1;
            }

            return transaction.update(userDocRef, {
              movieCount: movies,
            });
          } else {
            return;
          }
        } else {
          return transaction.set(userDocRef, {
            movieCount: ++movies,
          });
        }
      });
    });
  });

// triggered when a movie is deleted
export const deleteMovie = functions
  .region(FUNCTIONS_REGION)
  .firestore.document("users/{userId}/movies/{movieId}")
  .onDelete((data, context) => {
    // get the user document reference for the current user
    const userDocRef = firestore.doc(`users/${context.params.userId}`);

    // encapsulate into transaction
    return firestore.runTransaction((transaction) => {
      return transaction.get(userDocRef).then((counterDoc) => {
        const doc = counterDoc.data();

        if (doc !== undefined) {
          return transaction.update(userDocRef, {
            movieCount: doc["movieCount"] - 1,
          });
        }

        return;
      });
    });
  });


text:
(function(app, $, config)
{
    app.WindowView = Backbone.View.extend({

        initialize : function()
        {
            // Initialize models

            this.settings = app.model.settings;

            // Create sub views

            var user = this.user = app.model.user;

            if(user.hasRole('ADMIN'))
            {
                this.settingsView = new app.SettingsView({ el : this.$('.customer-chat-tab-content-settings-ui') });
            }

            this.chatTabView   = new app.ChatTabView  ({ el : this.$('#customer-chat-admin-chat') });
            this.operatorsView = new app.OperatorsView({ el : this.$('#customer-chat-operators-tab') });
            this.historyView   = new app.HistoryView  ({ el : this.$('#customer-chat-history') });
            this.tabsView      = new app.TabsView     ({ el : this.$('#customer-chat-admin-settings') });
            this.menuView      = new app.MenuView     ({ el : this.el, windowView : this });

            if(!user.hasRole('ADMIN'))
            {
                this.tabsView.removeTab(0);
                this.$('.customer-chat-tab-button.operators').html('Edit profile');
            }

            // -----

            // Keep update the scroller when necessary

            this.$('#customer-chat-admin-settings .customer-chat-content-messages')

                .bind('show', function()
                {
                    $(window).trigger('resize');
                })

                .not('#customer-chat-history .customer-chat-content-messages')

                .mCustomScrollbar()
            ;

            // Overwrite the standard alert() function

            window.alert = function(message)
            {
                app.view.dialogs.message('Alert', message);
            };

            // Show the window

            this.$el.animate({ opacity : 1 }, { duration : 'slow'});

            // Handle global events

            this.listenTo(app, 'history.search', this.showHistory);
        },

        showHistory : function()
        {
            // Show the settings tab

            this.menuView.showSettings();

            // Show the history tab

            this.tabsView.showTab(this.user.hasRole('OPERATOR') ? 1 : 2);
        }
    });

})(window.Application, jQuery, window.chatConfig);


text:
<form action="{% url 'blog:add' %}" method="post">
    {% csrf_token %}
    <input type="text" name="title">
    <input type="text" name="content">
    <input type="submit" value="post">
</form>


text:
'use babel'
const path = require('path')

const { buildPaths } = require('../config')
const { removeExtension, trimLeadingFolders, attachLeadingFolders } = require('../path-funcs/path-helpers')

const parallelDirs = (basePathFuncs, config) => {

  const { testSuffix } = config
  const { testInsideProject, packagePath, testPath, sourcePath } = buildPaths(config)

  const flipSrcPathToTestPath = (sourceFileWithinProject) => {
    const sourceFileMinusExt = removeExtension(basePathFuncs.sourcePathWithinSrc(sourceFileWithinProject))

    const pathPieces = [testInsideProject, sourceFileMinusExt, testSuffix, '.js']
    return path.normalize(pathPieces.join(''))
  }

  return {
    sourceFileWPToTestFileWP: (sourceFileWithinProject) => {
      return flipSrcPathToTestPath(sourceFileWithinProject)
    },

    isPathWPTestFile: (p) => {
      const trimmedPathResult = trimLeadingFolders(p, [packagePath, testPath])
      if (!trimmedPathResult.success) { return false }

      return removeExtension(trimmedPathResult.value).endsWith(testSuffix)
    },

    testFileWPToSourceFileWP: (p) => {
      const trimmedPathResult = trimLeadingFolders(p, [packagePath, testPath])
      const baseFile = removeExtension(trimmedPathResult.value).slice(0, -testSuffix.length)
      const baseFilePlusPrefix = attachLeadingFolders(baseFile, [packagePath, sourcePath])

      return `${baseFilePlusPrefix}.js`
    }
  }
}

module.exports = parallelDirs


text:
INCLUDE(ParseArguments)

FUNCTION(PROTOBUF_GENERATE)

    # argument parsing
    PARSE_ARGUMENTS(ARG "PROTOROOT;PROTOFILES;OUTPATH;INCLUDES;EXPORT_MACRO;CPP;JAVA;PYTHON;MATLAB" "DEBUG" ${ARGN})

    IF(NOT ARG_PROTOFILES)
        MESSAGE(SEND_ERROR "Error: PROTOBUF_GENERATE() called without any proto files")
        RETURN()
    ENDIF(NOT ARG_PROTOFILES)
    LIST(LENGTH ARG_PROTOROOT PROTOROOT_LENGTH)
    #IF(PROTOROOT_LENGTH GREATER 1)
    #    MESSAGE(SEND_ERROR "Error: PROTOBUF_GENERATE() called with too many protoroots, only one is allowed")
    #    RETURN()
    #ENDIF()
    LIST(LENGTH ARG_OUTPATH OUTPATH_LENGTH)
    IF(OUTPATH_LENGTH GREATER 1)
        MESSAGE(SEND_ERROR "Error: PROTOBUF_GENERATE() called with too many outpaths, only one is allowed")
        RETURN()
    ENDIF()
    LIST(LENGTH ARG_EXPORT_MACRO EXPORT_MACRO_LENGTH)
    IF(EXPORT_MACRO_LENGTH GREATER 1)
        MESSAGE(SEND_ERROR "Error: PROTOBUF_GENERATE() called with too many export macro names, only one is allowed")
        RETURN()
    ENDIF()

    # decide whether to build CPP
    LIST(LENGTH ARG_CPP CPP_LENGTH)
    IF(CPP_LENGTH EQUAL 0)
        SET(BUILD_CPP FALSE)
    ELSE()
        IF(NOT CPP_LENGTH EQUAL 2)
            MESSAGE(SEND_ERROR "Error: PROTOBUF_GENERATE() CPP argument expects two parameters SRC_VAR and HDR_VAR")
            RETURN()
        ENDIF()
        SET(BUILD_CPP TRUE)
        LIST(GET ARG_CPP 0 RESULT_CPP_SRCS)
        LIST(GET ARG_CPP 1 RESULT_CPP_HDRS)
    ENDIF()

    # decide whether to build java
    LIST(LENGTH ARG_JAVA JAVA_LENGTH)
    IF(JAVA_LENGTH EQUAL 0)
        SET(BUILD_JAVA FALSE)
    ELSE()
        IF(NOT JAVA_LENGTH EQUAL 1)
            MESSAGE(SEND_ERROR "Error: PROTOBUF_GENERATE() JAVA argument expects one parameter JAVA_VAR")
            RETURN()
        ENDIF()
        SET(BUILD_JAVA TRUE)
        LIST(GET ARG_JAVA 0 RESULT_JAVA)
    ENDIF()

    # decide whether to build PYTHON
    LIST(LENGTH ARG_PYTHON PYTHON_LENGTH)
    IF(PYTHON_LENGTH EQUAL 0)
        SET(BUILD_PYTHON FALSE)
    ELSE()
        IF(NOT PYTHON_LENGTH EQUAL 1)
            MESSAGE(SEND_ERROR "Error: PROTOBUF_GENERATE() PYTHON argument expects one parameter PYTHON_VAR")
            RETURN()
        ENDIF()
        SET(BUILD_PYTHON TRUE)
        LIST(GET ARG_PYTHON 0 RESULT_PYTHON)
    ENDIF()

    # decide whether to build MATLAB
    LIST(LENGTH ARG_MATLAB MATLAB_LENGTH)
    IF(MATLAB_LENGTH EQUAL 0)
        SET(BUILD_MATLAB FALSE)
    ELSE()
        IF(NOT MATLAB_LENGTH EQUAL 1)
            MESSAGE(SEND_ERROR "Error: PROTOBUF_GENERATE() MATLAB argument expects one parameter MATLAB_VAR")
            RETURN()
        ENDIF()
        SET(BUILD_MATLAB TRUE)
        LIST(GET ARG_MATLAB 0 RESULT_MATLAB)
    ENDIF()

    # create proper export macro for CPP if desired
    IF(EXPORT_MACRO_LENGTH EQUAL 1)
        SET(ARG_EXPORT "dllexport_decl=${ARG_EXPORT_MACRO}:")
        MESSAGE(STATUS "Enabling export macro ${ARG_EXPORT_MACRO} for CPP")
    ENDIF()

    SET(OUTPATH ${CMAKE_CURRENT_BINARY_DIR})
    IF(OUTPATH_LENGTH EQUAL 1)
        SET(OUTPATH ${ARG_OUTPATH})
    ENDIF()
    SET(PROTOROOTS ${CMAKE_CURRENT_SOURCE_DIR})
    IF(PROTOROOT_LENGTH GREATER 0)
        SET(PROTOROOTS ${ARG_PROTOROOT})
    ENDIF()

    SET(ARG_EXPORT "")
    IF(EXPORT_MACRO_LENGTH EQUAL 1)
        SET(ARG_EXPORT "dllexport_decl=${ARG_EXPORT_MACRO}:")
    ENDIF()

    # build command line for additional includes paths
    SET(INCLUDE_CMD_LINE)
    FOREACH(P ${ARG_INCLUDES})
        LIST(APPEND INCLUDE_CMD_LINE "--proto_path" ${P})
    ENDFOREACH()

    IF(ARG_DEBUG)
        MESSAGE("OUTPATH: ${OUTPATH}")
        MESSAGE("PROTOROOTS: ${PROTOROOTS}")
        MESSAGE("INCLUDE_CMD_LINE: ${INCLUDE_CMD_LINE}")
    ENDIF()

    SET(MATCHED_FILE_PATHS)
    FOREACH(PROTOFILE ${ARG_PROTOFILES})

        FILE(TO_CMAKE_PATH ${PROTOFILE} PROTOFILE)

        # ensure that the file ends with .proto
        STRING(REGEX MATCH "\\.proto$$" PROTOEND ${PROTOFILE})
        IF(NOT PROTOEND)
            MESSAGE(SEND_ERROR "Proto file '${PROTOFILE}' does not end with .proto")
        ENDIF()

        GET_FILENAME_COMPONENT(PROTO_PATH ${PROTOFILE} PATH)
        GET_FILENAME_COMPONENT(ABS_FILE ${PROTOFILE} ABSOLUTE)
        GET_FILENAME_COMPONENT(FILE_WE ${PROTOFILE} NAME_WE)

        STRING(LENGTH ${ABS_FILE} ABS_FILE_LENGTH)

        IF(ARG_DEBUG)
            MESSAGE("file ${PROTOFILE}:")
            MESSAGE("  PATH=${PROTO_PATH}")
            MESSAGE("  ABS_FILE=${ABS_FILE}")
            MESSAGE("  FILE_WE=${FILE_WE}")
            MESSAGE("  PROTOROOTS=${PROTOROOTS}")
        ENDIF()

        # find out if the file is in one of the specified proto root
        # we mimic the protoc logic here by taking the first matching proto_path
        SET(MATCH_PATH)
        FOREACH(ROOT ${PROTOROOTS})

            IF(ARG_DEBUG)
                MESSAGE("  ROOT=${ROOT}")
            ENDIF()

            FILE(RELATIVE_PATH REL_ABS ${ROOT} ${ABS_FILE})
            STRING(LENGTH ${REL_ABS} REL_LENGTH)

            IF(ARG_DEBUG)
                MESSAGE("    REL_ABS=${REL_ABS}")
                MESSAGE("    REL_LENGTH=${REL_LENGTH}")
            ENDIF()

            IF(${REL_LENGTH} GREATER 0 AND ${REL_LENGTH} LESS ${ABS_FILE_LENGTH})
                # we did not need to go directories up, hence the path is shorter
                # and this is a match... bad assumption but works
                SET(MATCH_PATH ${REL_ABS})
                SET(MATCH_ROOT ${ROOT})
                IF(ARG_DEBUG)
                    MESSAGE("  MATCH_ROOT=${MATCH_ROOT}")
                ENDIF()
                BREAK()
            ENDIF()

        ENDFOREACH()

        IF(ARG_DEBUG)
            MESSAGE("  MATCH_PATH=${MATCH_PATH}")
        ENDIF()

        IF(NOT MATCH_PATH)
            MESSAGE(SEND_ERROR "Proto file '${PROTOFILE}' is not in protoroots '${PROTOROOTS}'")
        ENDIF()
        LIST(APPEND MATCHED_FILE_PATHS ${ABS_FILE})

        # build the result file name
        FILE(RELATIVE_PATH ROOT_CLEANED_FILE ${MATCH_ROOT} ${ABS_FILE})
        IF(ARG_DEBUG)
            MESSAGE("  ROOT_CLEANED_FILE=${ROOT_CLEANED_FILE}")
        ENDIF()
        STRING(REGEX REPLACE "\\.proto$$" "" EXT_CLEANED_FILE ${ROOT_CLEANED_FILE})
        IF(ARG_DEBUG)
            MESSAGE("  EXT_CLEANED_FILE=${EXT_CLEANED_FILE}")
        ENDIF()

        SET(CPP_FILE "${OUTPATH}/${EXT_CLEANED_FILE}.pb.cc")
        SET(HDR_FILE "${OUTPATH}/${EXT_CLEANED_FILE}.pb.h")
        SET(PYTHON_FILE "${OUTPATH}/${EXT_CLEANED_FILE}_pb2.py")

        # determine the java file name
        FILE(READ ${PROTOFILE} PROTO_CONTENT)

        # first the package
        # TODO jwienke: ignore comments... see below TODO
        SET(PACKAGE_REGEX "package[\t ]+([^;\n\r]+);")
        STRING(REGEX MATCH ${PACKAGE_REGEX} PACKAGE_LINE ${PROTO_CONTENT})
        IF(ARG_DEBUG)
            MESSAGE("  PACKAGE_LINE=${PACKAGE_LINE}")
        ENDIF()
        SET(PACKAGE "")
        IF(PACKAGE_LINE)
            STRING(REGEX REPLACE ${PACKAGE_REGEX} "\\1" PACKAGE ${PACKAGE_LINE})
        ENDIF()
        STRING(REPLACE "." "/" JAVA_PACKAGE_PATH "${PACKAGE}")
        IF(ARG_DEBUG)
            MESSAGE("  PACKAGE=${PACKAGE}")
            MESSAGE("  JAVA_PACKAGE_PATH=${JAVA_PACKAGE_PATH}")
        ENDIF()

        # then the java class name

        # this is the default
        # TODO jwienke: how to integrate that this line must not start with //?
        #               cmake regex are strange, because ^ and $ match beginning
        #               and end of file and not of each line
        SET(JAVA_CLASS_REGEX "option[\t ]+java_outer_classname[\t ]+=[\t ]+\"([^\"]+)\"")
        STRING(REGEX MATCH ${JAVA_CLASS_REGEX} JAVA_CLASS_LINE ${PROTO_CONTENT})
        IF(ARG_DEBUG)
            MESSAGE("  JAVA_CLASS_LINE=${JAVA_CLASS_LINE}")
        ENDIF()
        SET(JAVA_CLASS ${FILE_WE})
        IF(JAVA_CLASS_LINE)
            STRING(REGEX REPLACE ${JAVA_CLASS_REGEX} "\\1" JAVA_CLASS ${JAVA_CLASS_LINE})
            # Now that we have the real java class name, this must be replaced
            # in the original file name proposal. However, the subpath in the
            # file system is also part of EXT_CLEANED_FILE. Hence, we need to
            # do some replace logic again...
        ENDIF()
        IF(ARG_DEBUG)
            MESSAGE("  JAVA_CLASS=${JAVA_CLASS}")
        ENDIF()

        # finally deduce the real java name
        SET(JAVA_FILE "${OUTPATH}/${JAVA_PACKAGE_PATH}/${JAVA_CLASS}.java")

        IF(ARG_DEBUG)
            MESSAGE("  CPP_FILE=${CPP_FILE}")
            MESSAGE("  HDR_FILE=${HDR_FILE}")
            MESSAGE("  JAVA_FILE=${JAVA_FILE}")
            MESSAGE("  PYTHON_FILE=${PYTHON_FILE}")
        ENDIF()

        # generate and use a list of protoroot arguments to pass to protoc
        SET(ROOT_ARGS)
        FOREACH(ROOT ${PROTOROOTS})
            LIST(APPEND ROOT_ARGS "--proto_path" ${ROOT})
        ENDFOREACH()

        IF(BUILD_CPP)
            LIST(APPEND CPP_SRCS "${CPP_FILE}")
            LIST(APPEND CPP_HDRS "${HDR_FILE}")

            ADD_CUSTOM_COMMAND(
                OUTPUT "${CPP_FILE}"
                       "${HDR_FILE}"
                COMMAND ${CMAKE_COMMAND} -E make_directory ${OUTPATH}
                COMMAND ${PROTOBUF_PROTOC_EXECUTABLE}
                ARGS "--cpp_out=${ARG_EXPORT}${OUTPATH}" ${ROOT_ARGS} ${INCLUDE_CMD_LINE} "${ABS_FILE}"
                DEPENDS ${ABS_FILE}
                COMMENT "Running C++ protocol buffer compiler on ${ABS_FILE} with root ${MATCH_ROOT}, generating: ${CPP_FILE}"
                VERBATIM)
        ENDIF()

        IF(BUILD_JAVA)
            LIST(APPEND JAVA_FILES "${JAVA_FILE}")

            ADD_CUSTOM_COMMAND(
                OUTPUT "${JAVA_FILE}"
                COMMAND ${CMAKE_COMMAND} -E make_directory ${OUTPATH}
                COMMAND ${PROTOBUF_PROTOC_EXECUTABLE}
                ARGS "--java_out=${OUTPATH}" ${ROOT_ARGS} ${INCLUDE_CMD_LINE} "${ABS_FILE}"
                DEPENDS ${ABS_FILE}
                COMMENT "Running Java protocol buffer compiler on ${ABS_FILE} with root ${MATCH_ROOT}, generating: ${JAVA_FILE}"
                VERBATIM)
        ENDIF()

        IF(BUILD_PYTHON)
            LIST(APPEND PYTHON_FILES "${PYTHON_FILE}")

            ADD_CUSTOM_COMMAND(
                OUTPUT "${PYTHON_FILE}"
                COMMAND ${CMAKE_COMMAND} -E make_directory ${OUTPATH}
                COMMAND ${PROTOBUF_PROTOC_EXECUTABLE}
                ARGS "--python_out=${OUTPATH}" ${ROOT_ARGS} ${INCLUDE_CMD_LINE} "${ABS_FILE}"
                DEPENDS ${ABS_FILE}
                COMMENT "Running Python protocol buffer compiler on ${ABS_FILE} with root ${MATCH_ROOT}, generating: ${PYTHON_FILE}"
                VERBATIM)
        ENDIF()

    ENDFOREACH()

    IF(BUILD_CPP)
        SET_SOURCE_FILES_PROPERTIES(${${CPP_SRCS}} ${${CPP_HDRS}} PROPERTIES GENERATED TRUE)
        SET(${RESULT_CPP_SRCS} ${CPP_SRCS} PARENT_SCOPE)
        SET(${RESULT_CPP_HDRS} ${CPP_HDRS} PARENT_SCOPE)
    ENDIF()

    IF(BUILD_JAVA)
        SET_SOURCE_FILES_PROPERTIES(${${JAVA_FILES}} PROPERTIES GENERATED TRUE)
        SET(${RESULT_JAVA} ${JAVA_FILES} PARENT_SCOPE)
    ENDIF()

    IF(BUILD_PYTHON)
        SET_SOURCE_FILES_PROPERTIES(${${PYTHON_FILES}} PROPERTIES GENERATED TRUE)
        SET(${RESULT_PYTHON} ${PYTHON_FILES} PARENT_SCOPE)
    ENDIF()

    IF(BUILD_MATLAB)
        ADD_CUSTOM_COMMAND(
            OUTPUT ${OUTPATH}
            COMMAND ${CMAKE_COMMAND} -E make_directory ${OUTPATH}
            COMMAND ${PROTOBUF_PROTOC_EXECUTABLE}
            ARGS "--matlab_out=${OUTPATH}" ${ROOT_ARGS} ${INCLUDE_CMD_LINE} ${MATCHED_FILE_PATHS}
            DEPENDS ${MATCHED_FILE_PATHS}
            COMMENT "Running Matlab protocol buffer compiler to generate files in ${OUTPATH}"
            VERBATIM)
    ENDIF()

    IF(BUILD_MATLAB)
        SET(${RESULT_MATLAB} ${OUTPATH} PARENT_SCOPE)
    ENDIF()

ENDFUNCTION()

MACRO(PROTOBUF_GENERATE_CPP SRCS HDRS)
    PROTOBUF_GENERATE(${ARGN} CPP ${SRCS} ${HDRS})
ENDMACRO()

FIND_PATH(PROTOBUF_INCLUDE_DIR NAMES google/protobuf/service.h
          HINTS "${PROTOBUF_ROOT}/include"
          DOC "The Google Protocol Buffers Headers")

# Google's provided vcproj files generate libraries with a "lib"
# prefix on Windows
IF(WIN32)
    SET(PROTOBUF_ORIG_FIND_LIBRARY_PREFIXES "${CMAKE_FIND_LIBRARY_PREFIXES}")
    SET(CMAKE_FIND_LIBRARY_PREFIXES "lib" "")
ENDIF()

FIND_LIBRARY(PROTOBUF_LIBRARY NAMES protobuf
             HINTS "${PROTOBUF_ROOT}/bin"
                   "${PROTOBUF_ROOT}/lib"
             DOC "The Google Protocol Buffers Library"
)
FIND_LIBRARY(PROTOBUF_PROTOC_LIBRARY NAMES protoc
             HINTS "${PROTOBUF_ROOT}/bin"
                   "${PROTOBUF_ROOT}/lib"
             DOC "The Google Protocol Buffers Compiler Library"
)
FIND_PROGRAM(PROTOBUF_PROTOC_EXECUTABLE NAMES protoc
             HINTS "${PROTOBUF_ROOT}/bin"
             DOC "The Google Protocol Buffers Compiler"
)
IF(PROTOBUF_PROTOC_EXECUTABLE AND NOT PROTOBUF_PROTOC_MATLAB)
    # check whether this protoc version supports matlab
    EXECUTE_PROCESS(COMMAND ${PROTOBUF_PROTOC_EXECUTABLE} "-h"
                    ERROR_VARIABLE PROTOC_HELP_TEXT
                    OUTPUT_QUIET)
    STRING(REGEX MATCH "--matlab_out" PROTOC_MATLAB_OUT "${PROTOC_HELP_TEXT}")
    IF(PROTOC_MATLAB_OUT)
        SET(PROTOBUF_PROTOC_MATLAB TRUE CACHE BOOL "Whether protoc is able to generate matlab output.")
        MESSAGE(STATUS "protoc supports matlab")
    ELSE()
        SET(PROTOBUF_PROTOC_MATLAB FALSE CACHE BOOL "Whether protoc is able to generate matlab output.")
        MESSAGE(STATUS "protoc does not support matlab")
    ENDIF()
ENDIF()
SET(PROTOBUF_PROTOC_VERSION "PROTOBUF_PROTOC_VERSION-NOTFOUND")
IF(PROTOBUF_PROTOC_EXECUTABLE)
    EXECUTE_PROCESS(COMMAND ${PROTOBUF_PROTOC_EXECUTABLE} --version
                    OUTPUT_VARIABLE PROTOBUF_PROTOC_VERSION_TEMP
                    RESULT_VARIABLE PROTOBUF_PROTOC_VERSION_RESULT)
    STRING(REGEX REPLACE ".*([0-9]\\.[0-9]\\.[0-9]).*" "\\1"
           PROTOBUF_PROTOC_VERSION_TEMP "${PROTOBUF_PROTOC_VERSION_TEMP}")
    IF(PROTOBUF_PROTOC_VERSION_TEMP)
        SET(PROTOBUF_PROTOC_VERSION "${PROTOBUF_PROTOC_VERSION_TEMP}")
    ENDIF()
ENDIF()

SET(KNOWN_VERSIONS 2.6.0 2.5.1 2.5.0 2.4.1 2.4.0 2.3.0)
# if we know the compiler version, we should favor it
IF(PROTOBUF_PROTOC_VERSION)
    LIST(INSERT KNOWN_VERSIONS 0 ${PROTOBUF_PROTOC_VERSION})
ENDIF()
SET(JAVA_NAMES ${PROTOBUF_JAVA_NAME} protobuf.jar protobuf-java.jar)
FOREACH(VERSION ${KNOWN_VERSIONS})
    LIST(APPEND JAVA_NAMES "protobuf-java-${VERSION}.jar")
ENDFOREACH()

FIND_FILE(PROTOBUF_JAVA_LIBRARY
          NAMES ${JAVA_NAMES}
          HINTS ${PROTOBUF_JAVA_ROOT}
                "${PROTOBUF_JAVA_ROOT}/share/java"
                "/usr/share/java"
                "/usr/share/java/protobuf-java"
                "/usr/share/protobuf/lib"
                "${CMAKE_INSTALL_PREFIX}/lib/java"
                "${CMAKE_INSTALL_PREFIX}/share/java")

MARK_AS_ADVANCED(PROTOBUF_INCLUDE_DIR
                 PROTOBUF_LIBRARY
                 PROTOBUF_PROTOC_LIBRARY
                 PROTOBUF_PROTOC_EXECUTABLE
                 PROTOBUF_JAVA_LIBRARY
                 PROTOBUF_PROTOC_MATLAB)

# Restore original find library prefixes
IF(WIN32)
    SET(CMAKE_FIND_LIBRARY_PREFIXES "${PROTOBUF_ORIG_FIND_LIBRARY_PREFIXES}")
ENDIF()

INCLUDE(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(PROTOBUF DEFAULT_MSG PROTOBUF_LIBRARY PROTOBUF_INCLUDE_DIR)

IF(PROTOBUF_FOUND)
    SET(PROTOBUF_INCLUDE_DIRS ${PROTOBUF_INCLUDE_DIR})
    SET(PROTOBUF_LIBRARIES    ${PROTOBUF_LIBRARY})
ENDIF()


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.codename1.ext.codescan;

import com.codename1.system.NativeInterface;

/**
 *
 * @author shannah
 */
public interface NativeCodeScanner extends NativeInterface {
    public void scanQRCode();
    public void scanBarCode();
}


text:
<?php declare( strict_types = 1 );

namespace BrightNucleus\AdminPage;

use BrightNucleus\AdminPage\Control\Control;
use BrightNucleus\AdminPage\Exception\FailedToCreateControl;
use BrightNucleus\Config\ConfigTrait;
use BrightNucleus\Config\ConfigInterface as Config;
use BrightNucleus\Config\Config as BaseConfig;
use BrightNucleus\Config\Exception\FailedToProcessConfigException;
use BrightNucleus\Invoker\InstantiatorTrait;
use BrightNucleus\OptionsStore\Option;

/**
 * Class ControlFactory.
 *
 * Create form controls that match options (or arbitrary classes).
 *
 * @since   0.1.2
 *
 * @package BrightNucleus\AdminPage
 * @author  Alain Schlesser <alain.schlesser@gmail.com>
 */
class ControlFactory {

	use ConfigTrait;
	use InstantiatorTrait;

	/**
	 * Instantiate a ViewBuilder object.
	 *
	 * @since 0.1.0
	 *
	 * @param Config $config Optional. Configuration settings.
	 *
	 * @throws FailedToProcessConfigException If the config could not be
	 *                                        processed.
	 */
	public function __construct( Config $config = null ) {
		$this->processConfig( $this->getConfig( $config ) );

	}

	/**
	 * Create a new control instance for a given option.
	 *
	 * @since 0.1.2
	 *
	 * @param Option $option Option for which to instantiate a new control.
	 * @param array  $args   Optional. Array of arguments to pass to the
	 *                       control's constructor.
	 *
	 * @return Control
	 * @throws FailedToCreateControl If no control mapping was found for the
	 *                               option.
	 */
	public function createFromOption( Option $option, array $args = [] ) {
		$class          = get_class( $option );
		$args['option'] = $option;

		$control_class = false;

		if ( $this->hasConfigKey( $class ) ) {
			$control_class = $this->getConfigKey( $class );
		}

		if ( array_key_exists( Control::TYPE, $args ) ) {
			$control_class = $args[ Control::TYPE ];
		}

		if ( ! is_subclass_of( $control_class, Control::class ) ) {
			throw FailedToCreateControl::forClass( $class );
		}

		return $this->instantiateClass( $control_class, $args );
	}

	/**
	 * Add additional Option => Control mappings to the factory config.
	 *
	 * @since 0.2.0
	 *
	 * @param array $mappings Array of Option => Control mappings.
	 */
	public function addMappings( array $mappings ) {
		$this->config = new BaseConfig(
			array_merge_recursive(
				$this->config->getArrayCopy(),
				$mappings
			)
		);
	}

	/**
	 * Get the configuration to use in the ViewBuilder.
	 *
	 * @since 0.2.0
	 *
	 * @return Config Configuration passed in through the constructor.
	 */
	protected function getConfig( $config = null ) {
		$defaults = new BaseConfig(
			__DIR__ . '/../config/defaults.php',
			null,
			null,
			'.'
		);

		$config = $config
			? new BaseConfig(
				array_merge_recursive(
					$defaults->getArrayCopy(),
					$config->getArrayCopy()
				),
				null,
				null,
				'.'
			)
			: $defaults;

		return $config->getSubConfig( 'BrightNucleus.AdminPage.ControlFactory' );
	}
}


text:
// $Id: Draw.java,v 1.67 2009/10/20 12:59:14 belaban Exp $

package bboss.org.jgroups.demos;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.management.MBeanServer;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

import bboss.org.jgroups.Address;
import bboss.org.jgroups.Channel;
import bboss.org.jgroups.ChannelListener;
import bboss.org.jgroups.ExtendedReceiverAdapter;
import bboss.org.jgroups.JChannel;
import bboss.org.jgroups.MergeView;
import bboss.org.jgroups.Message;
import bboss.org.jgroups.View;
import bboss.org.jgroups.jmx.JmxConfigurator;
import bboss.org.jgroups.util.Util;

/**
 * Shared whiteboard, each new instance joins the same group. Each instance chooses a random color,
 * mouse moves are broadcast to all group members, which then apply them to their canvas<p>
 * @author Bela Ban, Oct 17 2001
 */
public class Draw extends ExtendedReceiverAdapter implements ActionListener, ChannelListener {
    String                         groupname="DrawGroupDemo";
    private Channel                channel=null;
    private int                    member_size=1;
    static final boolean           first=true;
    private JFrame                 mainFrame=null;
    private JPanel                 sub_panel=null;
    private DrawPanel              panel=null;
    private JButton                clear_button, leave_button;
    private final Random           random=new Random(System.currentTimeMillis());
    private final Font             default_font=new Font("Helvetica",Font.PLAIN,12);
    private final Color            draw_color=selectColor();
    private static final Color     background_color=Color.white;
    boolean                        no_channel=false;
    boolean                        jmx;
    private boolean                use_state=false;
    private long                   state_timeout=5000;
    private boolean                use_unicasts=false;
    private final                  List<Address> members=new ArrayList<Address>();

    public Draw(String props, boolean no_channel, boolean jmx, boolean use_state, long state_timeout,
                boolean use_blocking, boolean use_unicasts, String name) throws Exception {
        this.no_channel=no_channel;
        this.jmx=jmx;
        this.use_state=use_state;
        this.state_timeout=state_timeout;
        this.use_unicasts=use_unicasts;
        if(no_channel)
            return;

        channel=new JChannel(props);
        if(name != null)
            channel.setName(name);
        if(use_blocking)
            channel.setOpt(Channel.BLOCK, Boolean.TRUE);
        channel.setReceiver(this);
        channel.addChannelListener(this);
    }

    public Draw(Channel channel) throws Exception {
        this.channel=channel;
        channel.setReceiver(this);
        channel.addChannelListener(this);
    }

    public Draw(Channel channel, boolean use_state, long state_timeout) throws Exception {
        this.channel=channel;
        channel.setReceiver(this);
        channel.addChannelListener(this);
        this.use_state=use_state;
        this.state_timeout=state_timeout;
    }

    public String getGroupName() {
        return groupname;
    }

    public void setGroupName(String groupname) {
        if(groupname != null)
            this.groupname=groupname;
    }

   public static void main(String[] args) {
       Draw             draw=null;
       String           props=null;
       boolean          no_channel=false;
       boolean          jmx=true;
       boolean          use_state=false;
       boolean          use_blocking=false;
       String           group_name=null;
       long             state_timeout=5000;
       boolean          use_unicasts=false;
       String           name=null;

        for(int i=0; i < args.length; i++) {
            if("-help".equals(args[i])) {
                help();
                return;
            }
            if("-props".equals(args[i])) {
                props=args[++i];
                continue;
            }
            if("-no_channel".equals(args[i])) {
                no_channel=true;
                continue;
            }
            if("-jmx".equals(args[i])) {
                jmx=Boolean.parseBoolean(args[++i]);
                continue;
            }
            if("-groupname".equals(args[i])) {
                group_name=args[++i];
                continue;
            }
            if("-state".equals(args[i])) {
                use_state=true;
                continue;
            }
            if("-use_blocking".equals(args[i])) {
                use_blocking=true;
                continue;
            }
            if("-timeout".equals(args[i])) {
                state_timeout=Long.parseLong(args[++i]);
                continue;
            }
            if("-bind_addr".equals(args[i])) {
                System.setProperty("jgroups.bind_addr", args[++i]);
                continue;
            }
            if("-use_unicasts".equals(args[i])) {
                use_unicasts=true;
                continue;
            }
            if("-name".equals(args[i])) {
                name=args[++i];
                continue;
            }

            help();
            return;
        }

        try {
            draw=new Draw(props, no_channel, jmx, use_state, state_timeout, use_blocking, use_unicasts, name);
            if(group_name != null)
                draw.setGroupName(group_name);
            draw.go();
        }
        catch(Throwable e) {
            System.err.println("fatal error: " + e.getLocalizedMessage() + ", cause: ");
            Throwable t=e.getCause();
            if(t != null)
                t.printStackTrace(System.err);
            System.exit(0);
        }
    }

    static void help() {
        System.out.println("\nDraw [-help] [-no_channel] [-props <protocol stack definition>]" +
                " [-groupname <name>] [-state] [-use_blocking] [-timeout <state timeout>] [-use_unicasts] " +
                "[-bind_addr <addr>] [-jmx <true | false>] [-name <logical name>]");
        System.out.println("-no_channel: doesn't use JGroups at all, any drawing will be relected on the " +
                "whiteboard directly");
        System.out.println("-props: argument can be an old-style protocol stack specification, or it can be " +
                "a URL. In the latter case, the protocol specification will be read from the URL\n");
    }

    private Color selectColor() {
        int red=(Math.abs(random.nextInt()) % 255);
        int green=(Math.abs(random.nextInt()) % 255);
        int blue=(Math.abs(random.nextInt()) % 255);
        return new Color(red, green, blue);
    }

    private void sendToAll(byte[] buf) throws Exception {
        for(Address mbr: members) {
            Message msg=new Message(mbr, null, buf);
            channel.send(msg);
        }
    }

    public void go() throws Exception {
        if(!no_channel && !use_state) {
            channel.connect(groupname);
        }
        mainFrame=new JFrame();
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        panel=new DrawPanel(use_state);
        panel.setBackground(background_color);
        sub_panel=new JPanel();
        mainFrame.getContentPane().add("Center", panel);
        clear_button=new JButton("Clear");
        clear_button.setFont(default_font);
        clear_button.addActionListener(this);
        leave_button=new JButton("Leave");
        leave_button.setFont(default_font);
        leave_button.addActionListener(this);
        sub_panel.add("South", clear_button);
        sub_panel.add("South", leave_button);
        mainFrame.getContentPane().add("South", sub_panel);
        mainFrame.setBackground(background_color);
        clear_button.setForeground(Color.blue);
        leave_button.setForeground(Color.blue);
        mainFrame.pack();
        mainFrame.setLocation(15, 25);
        mainFrame.setBounds(new Rectangle(250, 250));

        if(!no_channel && use_state) {
            channel.connect(groupname,null,null, state_timeout);
        }
        mainFrame.setVisible(true);
        setTitle();
    }

    void setTitle(String title) {
        String tmp="";
        if(no_channel) {
            mainFrame.setTitle(" Draw Demo ");
            return;
        }
        if(title != null) {
            mainFrame.setTitle(title);
        }
        else {
            if(channel.getAddress() != null)
                tmp+=channel.getAddress();
            tmp+=" (" + member_size + ")";
            mainFrame.setTitle(tmp);
        }
    }

    void setTitle() {
        setTitle(null);
    }

    public void receive(Message msg) {
        byte[] buf=msg.getRawBuffer();
        if(buf == null) {
            System.err.println("[" + channel.getAddress() + "] received null buffer from " + msg.getSrc() +
                    ", headers: " + msg.printHeaders());
            return;
        }

        try {
            DrawCommand comm=(DrawCommand)Util.streamableFromByteBuffer(DrawCommand.class, buf, msg.getOffset(), msg.getLength());
            switch(comm.mode) {
                case DrawCommand.DRAW:
                    if(panel != null)
                        panel.drawPoint(comm);
                    break;
                case DrawCommand.CLEAR:
                    clearPanel();
                    break;
                default:
                    System.err.println("***** received invalid draw command " + comm.mode);
                    break;
            }
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }

    public void viewAccepted(View v) {
        member_size=v.size();
        if(mainFrame != null)
            setTitle();
        members.clear();
        members.addAll(v.getMembers());

        if(v instanceof MergeView) {
            System.out.println("** MergeView=" + v);

            // This is an example of a simple merge function, which fetches the state from the coordinator
            // on a merge and overwrites all of its own state
            if(use_state && !members.isEmpty()) {
                Address coord=members.get(0);
                Address local_addr=channel.getAddress();
                if(local_addr != null && !local_addr.equals(coord)) {
                    try {
                        System.out.println("fetching state from " + coord);
                        channel.getState(coord, 5000);
                    }
                    catch(Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        else
            System.out.println("** View=" + v);
    }

    public void block() {
        System.out.println("--  received BlockEvent");
    }

    public void unblock() {
        System.out.println("-- received UnblockEvent");
    }

    public byte[] getState() {
        return panel.getState();
    }

    public void setState(byte[] state) {
        panel.setState(state);
    }

    public void getState(OutputStream ostream) {
        try {
            try {
                panel.writeState(ostream);
            }
            catch(IOException e) {
                e.printStackTrace();
            }
        }
        finally {
            Util.close(ostream);
        }
    }

    public void setState(InputStream istream) {
        try {
            try {
                panel.readState(istream);
            }
            catch(IOException e) {
                e.printStackTrace();
            }
        }
        finally {
            Util.close(istream);
        }
    }

    /* --------------- Callbacks --------------- */

    public void clearPanel() {
        if(panel != null)
            panel.clear();
    }

    public void sendClearPanelMsg() {
        DrawCommand comm=new DrawCommand(DrawCommand.CLEAR);

        try {
            byte[] buf=Util.streamableToByteBuffer(comm);
            if(use_unicasts)
                sendToAll(buf);
            else
                channel.send(new Message(null, null, buf));
        }
        catch(Exception ex) {
            System.err.println(ex);
        }
    }

    public void actionPerformed(ActionEvent e) {
        String     command=e.getActionCommand();
        if("Clear".equals(command)) {
            if(no_channel) {
                clearPanel();
                return;
            }
            sendClearPanelMsg();
        }
        else if("Leave".equals(command)) {
            stop();
        }
        else
            System.out.println("Unknown action");
    }

    public void stop() {
        if(!no_channel) {
            try {
                channel.close();
            }
            catch(Exception ex) {
                System.err.println(ex);
            }
        }
        mainFrame.setVisible(false);
        mainFrame.dispose();
    }

    /* ------------------------------ ChannelListener interface -------------------------- */

    public void channelConnected(Channel channel) {
        if(jmx) {
            Util.registerChannel((JChannel)channel, "jgroups");
        }
    }

    public void channelDisconnected(Channel channel) {
        if(jmx) {
            MBeanServer server=Util.getMBeanServer();
            if(server != null) {
                try {
                    JmxConfigurator.unregisterChannel((JChannel)channel,server, groupname);
                }
                catch(Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void channelClosed(Channel channel) {

    }

    public void channelShunned() {
    }

    public void channelReconnected(Address addr) {
    }

    /* --------------------------- End of ChannelListener interface ---------------------- */

    private class DrawPanel extends JPanel implements MouseMotionListener {
        final Dimension         preferred_size=new Dimension(235, 170);
        Image                   img=null; // for drawing pixels
        Dimension               d, imgsize=null;
        Graphics                gr=null;
        final Map<Point,Color>  state;

        public DrawPanel(boolean use_state) {
            if(use_state)
                state=new LinkedHashMap<Point,Color>();
            else
                state=null;
            createOffscreenImage(false);
            addMouseMotionListener(this);
            addComponentListener(new ComponentAdapter() {
                public void componentResized(ComponentEvent e) {
                    if(getWidth() <= 0 || getHeight() <= 0) return;
                    createOffscreenImage(false);
                }
            });
        }

        public byte[] getState() {
            byte[] retval=null;
            if(state == null) return null;
            synchronized(state) {
                try {
                    retval=Util.objectToByteBuffer(state);
                }
                catch(Exception e) {
                    e.printStackTrace();
                }
            }
            return retval;
        }

        @SuppressWarnings("unchecked")
        public void setState(byte[] buf) {
            synchronized(state) {
                try {
                    Map<Point,Color> tmp=(Map<Point,Color>)Util.objectFromByteBuffer(buf);
                    state.clear();
                    state.putAll(tmp);
                    System.out.println("received state: " + buf.length + " bytes, " + state.size() + " entries");
                    createOffscreenImage(true);
                }
                catch(Exception e) {
                    e.printStackTrace();
                }
            }
        }

        public void writeState(OutputStream outstream) throws IOException {
            synchronized(state) {
                if(state != null) {
                    DataOutputStream dos=new DataOutputStream(outstream);
                    dos.writeInt(state.size());
                    Point point;
                    Color col;
                    for(Map.Entry<Point,Color> entry: state.entrySet()) {
                        point=entry.getKey();
                        col=entry.getValue();
                        dos.writeInt(point.x);
                        dos.writeInt(point.y);
                        dos.writeInt(col.getRGB());
                    }
                    dos.flush();
                }
            }
        }

        public void readState(InputStream instream) throws IOException {
            DataInputStream in=new DataInputStream(instream);
            Map<Point,Color> new_state=new HashMap<Point,Color>();
            int num=in.readInt();
            Point point;
            Color col;
            for(int i=0; i < num; i++) {
                point=new Point(in.readInt(), in.readInt());
                col=new Color(in.readInt());
                new_state.put(point, col);
            }

            synchronized(state) {
                state.clear();
                state.putAll(new_state);
                System.out.println("read state: " + state.size() + " entries");
                createOffscreenImage(true);
            }
        }

        final void createOffscreenImage(boolean discard_image) {
            d=getSize();
            if(discard_image) {
                img=null;
                imgsize=null;
            }
            if(img == null || imgsize == null || imgsize.width != d.width || imgsize.height != d.height) {
                img=createImage(d.width, d.height);
                if(img != null) {
                    gr=img.getGraphics();
                    if(gr != null && state != null) {
                        drawState();
                    }
                }
                imgsize=d;
            }
            repaint();
        }

        /* ---------------------- MouseMotionListener interface------------------------- */

        public void mouseMoved(MouseEvent e) {}

        public void mouseDragged(MouseEvent e) {
            int                 x=e.getX(), y=e.getY();
            DrawCommand         comm=new DrawCommand(DrawCommand.DRAW, x, y,
                                                     draw_color.getRed(), draw_color.getGreen(), draw_color.getBlue());

            if(no_channel) {
                drawPoint(comm);
                return;
            }

            try {
                byte[] buf=Util.streamableToByteBuffer(comm);
                if(use_unicasts)
                    sendToAll(buf);
                else
                    channel.send(new Message(null, null, buf));
            }
            catch(Exception ex) {
                System.err.println(ex);
            }
        }

        /* ------------------- End of MouseMotionListener interface --------------------- */

        /**
         * Adds pixel to queue and calls repaint() whenever we have MAX_ITEMS pixels in the queue
         * or when MAX_TIME msecs have elapsed (whichever comes first). The advantage compared to just calling
         * repaint() after adding a pixel to the queue is that repaint() can most often draw multiple points
         * at the same time.
         */
        public void drawPoint(DrawCommand c) {
            if(c == null || gr == null) return;
            Color col=new Color(c.r, c.g, c.b);
            gr.setColor(col);
            gr.fillOval(c.x, c.y, 10, 10);
            repaint();
            if(state != null) {
                synchronized(state) {
                    state.put(new Point(c.x, c.y), col);
                }
            }
        }

        public void clear() {
            if(gr == null) return;
            gr.clearRect(0, 0, getSize().width, getSize().height);
            repaint();
            if(state != null) {
                synchronized(state) {
                    state.clear();
                }
            }
        }

        /** Draw the entire panel from the state */
        public void drawState() {
            // clear();
            Map.Entry entry;
            Point pt;
            Color col;
            synchronized(state) {
                for(Iterator it=state.entrySet().iterator(); it.hasNext();) {
                    entry=(Map.Entry)it.next();
                    pt=(Point)entry.getKey();
                    col=(Color)entry.getValue();
                    gr.setColor(col);
                    gr.fillOval(pt.x, pt.y, 10, 10);

                }
            }
            repaint();
        }

        public Dimension getPreferredSize() {
            return preferred_size;
        }

        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            if(img != null) {
                g.drawImage(img, 0, 0, null);
            }
        }

    }

}


text:
/* cpuid2cpuflags -- AT_HWCAP* routine prototypes
 * (c) 2015-2019 Michał Górny
 * 2-clause BSD licensed
 */

unsigned long get_hwcap();
unsigned long get_hwcap2();
char* get_uname_machine();


text:
layout: post
title: "Top 10 Favorite Athletes of All-Time"
categories: top10s
excerpt: "Top 10"
comments: false
share: true
---

# 10. Marcus Allen

![](https://s-media-cache-ak0.pinimg.com/736x/5f/81/9e/5f819e84563a7199fa3bd80f8e264bd7.jpg)

OK, before we get started, let me qualify this list: it is of my favorite players from when I was a kid AND currently. I do not like Marcus Allen anymore. His shine has faded from me years and years ago. But when I was a kid, he was my favorite player on my favorite team at the time; the 1983 Los Angeles Raiders. I am not sure why I liked him, the Raiders unis are cool, I like the number 32 (as you will see as you read on), and he was really fun to watch. But that was then.

# 9. Bobby Wagner

![](http://www.seahawks.com/sites/seahawks.com/files/styles/borealis_no_limit_respondmedium/public/assets/images/imported/SEA/articleImages/players/2014/wagner-bobby/141223probowl600.jpg?itok=Jwx94RvI&timestamp=1459437769)

This guy is just a stud. He is a key piece to the Seahawk defense, and probably the most understated (something this team needs more of). He is great in run stopping as well as in pass coverage, which is critical for their zone scheme. I personally think he should blitz more, but whatever. Anyway, he is also one of the nicest guys on the team and is sort of the opposite of all the loud mouths that can alienate the media, the fans, even the coaching staff.

# 8. Carl Lewis

![](https://s-media-cache-ak0.pinimg.com/originals/9c/64/5b/9c645b560bbc9a925bbd8a5fda680050.jpg)

Carl Lewis was the greatest athlete in the world during the years when I started paying attention to sports. So naturally, he has to make this list. Despite all of his records being broken, despite singing a version of the National Anthem even Roseanne Barr winces at, and despite throwing a first pitch at an MLB game that makes you question whether or not he is even athletic at all, Carl Lewis is the greatest track athlete in US history this side of Jesse Owens.

# 7. Ozzie Smith

![](https://az616578.vo.msecnd.net/files/responsive/embedded/any/desktop/2015/10/09/635799613600299905427028903_Smith.jpg)

For some reason, I was a StL Cardinal fan when I was younger. And for some even odder reason, I have kept that fealty.  Built for speed instead of power, the Cardinals were the king of AstroTurf teams. And Ozzie Smith was all that and an amazing glove for the 1980's Cardinals. Even late in his career, he learned to hit a bit, averaging over .300 once. But what he is known for is his fielding, and he was the greatest ever at the shortstop spot.

# 6. Manu Ginobili

![](http://nextimpulsesports.com/wp-content/uploads/2013/10/145731591-1590161.jpg)

When I coached, I always wanted a Manu Ginobili on the team. Well duh, he is a pro and very good, but not for those reasons. I wanted one because of his style. He was gritty, cagey, clutch, daring, and when he made a mistake he was the first guy back on defense to try to correct it. Yes, other fans of other teams hated him, but we all know he is the guy you want on your team because no one competed harder than him on a daily basis.

# 5. Magic Johnson

![](http://i.cdn.turner.com/nba/nba/history/legends/magic-johnson/magic-johnson-608.jpg)

Magic was my first favorite player. As a kid, everyone on the west side of the country loved the Lakers. And who didn't love the way Magic played? It seemed like every pass, even the easy ones, was exciting to watch. Also he was a giver; always tried to involve the other players on the team despite having the skill to score 25+ a game. Of course when you have 3 other HOFs on the team, sharing is way easier. Since he retired, he has become a business mogul and a pillar in the LA community. All of that is pretty cool. But he is about the worse Twitter follow ever.

# 4. Yadier Molina

![](http://bloximages.newyork1.vip.townnews.com/stltoday.com/content/tncms/assets/v3/editorial/5/22/5220c035-0a2a-5f32-b1c4-bed25cf0bf3b/545a1631472dd.image.jpg?resize=620%2C484)

Catchers are the toughest guys in baseball. Not only do they have to deal with getting hit occasionally with the ball, handling moody pitchers who always want to throw fastballs, and have to bat like all of the other guys. Catchers also have to be in that squat for the entire game. Ugh! And that is why you have to respect Yadi Molina. He was the heart and soul of their two World Series wins. Yes, Pujols was the best player, but Yadi was the linchpin. Ask any Cards fan and they will echo this.

# 3. Earl Thomas

![](http://www.seahawks.com/sites/seahawks.com/files/styles/borealis_gallery__full_respondmedium/public/clm_20151220_1342_1.jpg?itok=PV80qCc2&timestamp=1462652783)

ET3 is just awesome. He is the emotional leader of this team. He is the one in the back cleaning up all the overplays and mistakes the Hawk defense makes. He is the keystone to their entire Cover 3 defense. The most indispensable player outside the QB, ET3 makes their defense work. You don't believe me? Look at what happened last season when he got hurt. From leading the league in points allowed for the 5th season in a row to finishing 12th. Watch the Falcon playoff game. Yeah. He is that big of a difference.

# 2. Roger Federer

![](https://qph.ec.quoracdn.net/main-qimg-80ab5227a1603cff918ad80de130e8ed-c)

The GOAT in tennis, no one has ever played the game with the grace, balance, and versatile skill as Federer. Yes, he has won all the majors, yes he has won the most majors in all, yes he is renown by all tennis connoisseurs of being the most beautiful player of all time, but he is even a better person off the court. OK, that is not true at all. Even though he is hugely philanthropic, if he was a better person off the court, that would make him like Jesus or something. Regardless, he is still one of the most beloved and rooted for athletes around the world.

# 1. Sean Elliott

![](http://bloximages.chicago2.vip.townnews.com/tucson.com/content/tncms/assets/v3/editorial/8/8a/88aece22-1b24-11e2-beb3-0019bb2963f4/508359abac8e8.preview-620.jpg)

Tucson born, Tucson bred, and Tucson trained. Sean Elliott is the greatest athlete to ever come from my hometown. He is also one of the primary reasons why U of A is where they are in basketball now. Before Sean, Lute was obviously a great coach, but never made it out of the first round in Arizona. Then Sean came. In his junior season, he made 1st team All-American and led this squad past the 1st round, 2nd round, 3rd round, and 4th round to get to UA's first Final 4. In his senior season, UA was ranked #1 in the nation, Elliott won Player of the Year honors, and became the all-time leading scorer in Pac-10 history. Oh yeah, he had a nice career with my favorite team in the NBA (which became my favorite team when he was drafted there). Sean Elliott may not be the greatest athlete on this list. In fact, I bet he is the least known of them all. But Sean was the biggest deal in town when I was in elementary school, and holds a lot of weight when it comes to lists like this.


text:
package org.apache.shindig.social.opensocial.jpa;

import static javax.persistence.CascadeType.ALL;
import static javax.persistence.CascadeType.MERGE;
import static javax.persistence.CascadeType.PERSIST;
import static javax.persistence.CascadeType.REFRESH;
import static javax.persistence.GenerationType.IDENTITY;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import org.apache.shindig.social.opensocial.jpa.api.DbObject;
import org.apache.shindig.social.opensocial.jpa.api.FilterCapability;
import org.apache.shindig.social.opensocial.jpa.api.FilterSpecification;
import org.apache.shindig.protocol.model.Enum;
import org.apache.shindig.protocol.model.FilterOperation;
import org.apache.shindig.social.opensocial.model.Account;
import org.apache.shindig.social.opensocial.model.Address;
import org.apache.shindig.social.opensocial.model.BodyType;
import org.apache.shindig.social.opensocial.model.Drinker;
import org.apache.shindig.social.opensocial.model.ListField;
import org.apache.shindig.social.opensocial.model.LookingFor;
import org.apache.shindig.social.opensocial.model.Name;
import org.apache.shindig.social.opensocial.model.NetworkPresence;
import org.apache.shindig.social.opensocial.model.Organization;
import org.apache.shindig.social.opensocial.model.Person;
import org.apache.shindig.social.opensocial.model.Document;
import org.apache.shindig.social.opensocial.model.Smoker;
import org.apache.shindig.social.opensocial.model.Url;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.PostLoad;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.persistence.Version;

/**
 * Default Implementation of the Person object in the org.apache.shindig.social.opensocial.jpa.
 */
@Entity
@Table(name = "documents") // this table does not exist in moodle
@NamedQueries(value = {
    @NamedQuery(name = DocumentDb.FINDBY_DOCUMENTID,
        query = "select a from DocumentDb a where a.id = :id "),
    @NamedQuery(name = DocumentDb.FINDBY_LIKE_DOCUMENTID,
        query = "select a from DocumentDb a where a.id like :id") })
public class DocumentDb implements Document, DbObject {

  public static final String FINDBY_DOCUMENTID = "q.asset.findbyassetid";

  public static final String PARAM_DOCUMENTID = "id";

  public static final String FINDBY_LIKE_DOCUMENTID = "q.asset.findbylikeassetid";

  private static final String INTERESTS_PROPERTY = "interest";

  private static final Map<String, FilterSpecification> FILTER_COLUMNS =
    new HashMap<String, FilterSpecification>();

  private static final FilterOperation[] ALL_FILTEROPTIONS = new FilterOperation[] {
      FilterOperation.equals, FilterOperation.contains, FilterOperation.present,
      FilterOperation.startsWith };
  private static final FilterOperation[] NUMERIC_FILTEROPTIONS = new FilterOperation[] {
      FilterOperation.equals, FilterOperation.present };
  @SuppressWarnings("unused")
  private static final FilterOperation[] EQUALS_FILTEROPTIONS =
    new FilterOperation[] { FilterOperation.equals };

  static {
    FILTER_COLUMNS.put("displayName", new FilterSpecification("displayName", ALL_FILTEROPTIONS));

    // the following are special operations which are accepted, but work differently
    FILTER_COLUMNS.put("topFriends", new FilterSpecification());
    FILTER_COLUMNS.put("hasApp", new FilterSpecification());
  }

  private static final FilterCapability FILTER_CAPABILITY = new FilterCapability() {
    /**
     * {@inheritDoc}
     */
    public String findFilterableProperty(String fieldName, FilterOperation filterOperation) {
      FilterSpecification spec = FILTER_COLUMNS.get(fieldName);
      if (spec != null) {
        return spec.translateProperty(filterOperation);
      }
      return null;
    }

  };

  public static final String JPQL_FINDALLPERSON = null;

  // TODO The commented out query supports sorting by friend.score but needs a join with FriendDb which returns duplicates.
  // Using 'group by' to avoid duplicates doesn't work in HSQLDB or Derby - causes a "Not in aggregate function or group by clause" jdbc exception.
  // public static final String JPQL_FINDPERSON_BY_FRIENDS = "select p from PersonDb p join FriendDb f on p.objectId = f.friend.objectId where p.objectId in (select f.friend.objectId from PersonDb p, FriendDb f where p.objectId = f.person.objectId and ";
  public static final String JPQL_FINDPERSON_BY_FRIENDS = "select p from PersonDb p where p.objectId in (select f.friend.objectId from PersonDb p, FriendDb f where p.objectId = f.person.objectId and ";

  public static final Object JPQL_FINDPERSON_BY_GROUP = null;

  public static final Object JPQL_FINDDOCUMENT = "select a from DocumentDb a where ";
  public static final Object JPQL_FINDDOCUMENTS = "select a from DocumentDb a where ";

  /**
   * The internal object ID used for references to this object. Should be generated by the
   * underlying storage mechanism
   */
  @Id
  @GeneratedValue(strategy = IDENTITY)
  @Column(name = "id")
  private long objectId;

  /**
   * The internal parentId and parentType used for references to the parent of a asset.
   */
  @Basic
  @Column(name = "parent_id", length = 255)
  private String parentId;

  @Basic
  @Column(name = "parent_type", length = 255)
  protected String parentType;

  /**
   * An optimistic locking field.
   */

  @Basic
  @Column(name = "entity", length = 255)
  protected String documentEntity;

  @Basic
  @Column(name = "format_settings_type", length = 255)
  protected String documentType;

  @Transient
  protected String author;

  @Transient
  protected String authorEmail;

  @Basic
  @Column(name = "name", length = 255)
  private String displayName;

  @Basic
  @Column(name = "name", length = 255, insertable = false, updatable = false)
  private String name;

  @Basic
  @Column(name = "picture")
  protected String picture;

  /**
   *
   */
  @Transient
  protected Integer height;

  /**
   *
   */
  @Basic
  @Column(name = "description", length = 255)
  protected String description;

  /**
   *
   */
  @Basic
  @Column(name = "id", length = 255, insertable = false, updatable = false)
  protected String id;

  /**
   *
   */
  @Transient
  protected List<ListField> ims;

  /**
   *
   */
  @Basic
  @Column(name = "updated_at")
  @Temporal(TemporalType.TIMESTAMP)
  protected Date updated;

  /**
   *
   */
  @Transient
  protected String screenshotUrl;

  /**
   *
   */
  @Basic
  @Column(name = "external_thumbnail", length = 255)
  protected String thumbnailUrl;

  /**
   *
   */
  @Transient
  protected Long utcOffset;

  /**
   *
   */
  @Transient
  protected List<String> tags;

  // Note: Not in the opensocial js person object directly
  @Transient
  private boolean isOwner = false;

  public DocumentDb() {
  }

  public DocumentDb(String id, String displayName) {
    this.id = id;
    this.displayName = displayName;
  }

  public String getDocumentType() {
	  return documentType;
  }

  public void setDocumentType(String documentType) {
	  this.documentType = documentType;
  }

  public String getDocumentEntity() {
    return documentEntity;
  }

  public void setDocumentEntity(String documentEntity) {
    this.documentEntity = documentEntity;
  }

  public String getAuthor() {
    return author;
  }

  public void setAuthor(String author) {
    this.author = author;
  }

  public Integer getHeight() {
    return height;
  }

  public void setHeight(Integer height) {
    this.height = height;
  }

  public String getScreenshotUrl() {
    return screenshotUrl;
  }

  public void setScreenshotUrl(String screenshotUrl) {
    this.screenshotUrl = screenshotUrl;
  }

  public String getProfileUrl() {
    return "path_url"+String.valueOf(objectId);
  }

  public void setProfileUrl(String profileUrl) {

  }

  public String getThumbnailUrl() {
    String pic = picture;
    if (pic == null || pic.equals("")) {
      return "path_url/asset_thumb.png";
    }

    return "path_url/picture/"+String.valueOf(objectId)+"/thumb/"+pic;
  }

  public void setThumbnailUrl(String thumbnailUrl) {
    this.thumbnailUrl = thumbnailUrl;
  }

  public String getAuthorEmail() {
    return authorEmail;
  }

  public void setAuthorEmail(String authorEmail) {
    this.authorEmail = authorEmail;
  }

  public List<String> getTags() {
    return tags;
  }

  public void setTags(List<String> tags) {
    this.tags = tags;
  }

  public String getParentId() {
    return this.parentId;
  }

  public void setParentId(String parentId) {
    this.parentId = parentId;
  }

  public String getParentType() {
	  if(this.parentType.equals("User")){
		  return "@person";
	  }else{
		  return "@space";
	  }
  }

  public void setParentType(String parentType) {
    this.parentType = parentType;
  }

  public String getName() {
    return this.name;
  }

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

  public String getId() {
    return id;
  }

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

  public List<ListField> getIms() {
    return ims;
  }

  public void setIms(List<ListField> ims) {
    this.ims = ims;
  }

  public Date getUpdated() {
    if (updated == null) {
      return null;
    }
    return new Date(updated.getTime());
  }

  public void setUpdated(Date updated) {
    if (updated == null) {
      this.updated = null;
    } else {
      this.updated = new Date(updated.getTime());
    }
  }

  public String getDescription() {
    return description;
  }

  public void setDescription(String description) {
    this.description = description;
  }

  public Long getUtcOffset() {
    return utcOffset;
  }

  public void setUtcOffset(Long utcOffset) {
    this.utcOffset = utcOffset;
  }

  public boolean getIsOwner() {
    return isOwner;
  }

  public void setIsOwner(boolean isOwner) {
    this.isOwner = isOwner;
  }

  // Proxied fields

  private <T extends ListField> T getListFieldWithType(String type, List<T> list) {
    if (list != null) {
      for (T url : list) {
        if (type.equalsIgnoreCase(url.getType())) {
          return url;
        }
      }
    }

    return null;
  }

  private <T extends ListField> List<T> addListField(T field, List<T> list) {
    if (list == null) {
      list = Lists.newArrayList();
    }
    list.add(field);
    return list;
  }

  /**
   * @return the objectId
   */
  public long getObjectId() {
    return Long.parseLong(id);
  }

  @PrePersist
  public void populateDbFields() {

  }

  @PostLoad
  public void loadTransientFields() {

  }

  /*
   * (non-Javadoc)
   *
   * @see org.apache.shindig.social.opensocial.model.Person#getDisplayName()
   */
  public String getDisplayName() {
    return displayName;
  }

  /*
   * (non-Javadoc)
   *
   * @see org.apache.shindig.social.opensocial.model.Person#setDisplayName(java.lang.String)
   */
  public void setDisplayName(String displayName) {
    this.displayName = displayName;
  }

  public static FilterCapability getFilterCapability() {
    return FILTER_CAPABILITY;

  }

  /** {@inheritDoc} */
  public Map<String, ? extends Object> getAppData()
  {
    return null;
  }

  /** {@inheritDoc} */
  public void setAppData( Map<String, ? extends Object> appData )
  {
  }
}


text:
"""Module with classes and methods to manage the
CloudWatch Log functionalities at high level."""

from typing import Dict
from scar.providers.aws import GenericClient

class ECR(GenericClient):
    """Manages the AWS ElasticContainerRegistry functionality"""

    def __init__(self, resources_info: Dict):
        super().__init__()
        self.resources_info = resources_info

    def get_authorization_token(self) -> str:
        """Retrieves an authorization token."""
        return self.client.get_authorization_token()

    def get_registry_url(self) -> str:
        """Retrieves the registry URL."""
        registry_id = self.client.get_registry_id()
        return "%s.dkr.ecr.us-east-1.amazonaws.com" % registry_id

    def get_repository_uri(self, repository_name: str) -> str:
        """Check if a repository exists."""
        response = self.client.describe_repositories(repositoryNames=[repository_name])
        if response:
            return response["repositories"][0]["repositoryUri"]
        else:
            return None

    def create_repository(self, repository_name: str) -> str:
        """Creates a repository."""
        response = self.client.create_repository(repository_name)
        return response["repository"]["repositoryUri"]

    def delete_repository(self, repository_name: str):
        self.client.delete_repository(repository_name)


text:
package org.apache.beam.sdk.io.synthetic;

import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkArgument;
import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkNotNull;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.apache.beam.sdk.values.KV;
import org.apache.commons.math3.distribution.ConstantRealDistribution;
import org.joda.time.Duration;

/**
 * Synthetic bounded source options. These options are all JSON, see documentations of individual
 * fields for details. {@code SyntheticSourceOptions} uses jackson annotations which
 * PipelineOptionsFactory can use to parse and construct an instance.
 */
public class SyntheticSourceOptions extends SyntheticOptions {
  private static final long serialVersionUID = 0;

  /** Total number of generated records. */
  @JsonProperty public long numRecords;

  /**
   * Only records whose index is a multiple of this will be split points. 0 means the source is not
   * dynamically splittable (but is perfectly statically splittable). In that case it also doesn't
   * report progress at all.
   */
  @JsonProperty public long splitPointFrequencyRecords = 1;

  /**
   * Distribution for generating initial split bundles.
   *
   *
When splitting into "desiredBundleSizeBytes", we'll compute the desired number of bundles N,
   * then sample this many numbers from this distribution, normalize their sum to 1, and use that as
   * the boundaries of generated bundles.
   *
   *
The Zipf distribution is expected to be particularly useful here.
   *
   *
E.g., empirically, with 100 bundles, the Zipf distribution with a parameter of 3.5 will
   * generate bundles where the largest is about 3x-10x larger than the median; with a parameter of
   * 3.0 this ratio will be about 5x-50x; with 2.5, 5x-100x (i.e. 1 bundle can be as large as all
   * others combined).
   */
  @JsonDeserialize(using = SamplerDeserializer.class)
  public Sampler bundleSizeDistribution = fromRealDistribution(new ConstantRealDistribution(1));

  /**
   * If specified, this source will split into exactly this many bundles regardless of the hints
   * provided by the service.
   */
  @JsonProperty public Integer forceNumInitialBundles;

  /** See {@link ProgressShape}. */
  @JsonProperty public ProgressShape progressShape = ProgressShape.LINEAR;

  /**
   * The distribution for the delay when reading from synthetic source starts. This delay is
   * independent of the per-record delay and uses the same types of distributions as {@link
   * #delayDistribution}.
   */
  @JsonDeserialize(using = SamplerDeserializer.class)
  final Sampler initializeDelayDistribution = fromRealDistribution(new ConstantRealDistribution(0));

  /**
   * Generates a random delay value for the synthetic source initialization using the distribution
   * defined by {@link #initializeDelayDistribution}.
   */
  public Duration nextInitializeDelay(long seed) {
    return Duration.millis((long) initializeDelayDistribution.sample(seed));
  }

  /**
   * The delay between event and processing time. uses same types of distributions as any other
   * delay in {@link SyntheticSourceOptions}.
   *
   *
Example: we can use ConstantRealDistribution(10) to simulate constant 10 millis delay
   * between event and processing times for each record generated by UnboundedSyntheticSource.
   */
  @JsonDeserialize(using = SamplerDeserializer.class)
  Sampler processingTimeDelayDistribution = fromRealDistribution(new ConstantRealDistribution(0));

  /**
   * Generates a random delay value between event and processing time using the distribution defined
   * by {@link #processingTimeDelayDistribution}.
   */
  public Duration nextProcessingTimeDelay(long seed) {
    return Duration.millis((long) processingTimeDelayDistribution.sample(seed));
  }

  /**
   * Defines how many elements should the watermark function check in advance to "predict" how the
   * record distribution will look like.
   */
  @JsonProperty public Integer watermarkSearchInAdvanceCount = 100;

  /**
   * Could be either positive and negative. Positive drift will "push away" the watermark from the
   * actual records event times. Negative will bring it closer, possibly causing some events to be
   * "late".
   *
   *
By default there is no drift at all.
   */
  @JsonProperty public Integer watermarkDriftMillis = 0;

  @Override
  public void validate() {
    super.validate();
    checkArgument(
        numRecords >= 0, "numRecords should be a non-negative number, but found %s.", numRecords);
    checkNotNull(bundleSizeDistribution, "bundleSizeDistribution");
    checkArgument(
        forceNumInitialBundles == null || forceNumInitialBundles > 0,
        "forceNumInitialBundles, if specified, must be positive, but found %s",
        forceNumInitialBundles);
    checkArgument(
        splitPointFrequencyRecords >= 0,
        "splitPointFrequencyRecords must be non-negative, but found %s",
        splitPointFrequencyRecords);
  }

  public Record genRecord(long position) {
    // This method is supposed to generate random records deterministically,
    // so that results can be reproduced by running the same scenario a second time.
    // We need to initiate a Random object for each position to make the record deterministic
    // because liquid sharding could split the Source at any position.
    // And we also need a seed to initiate a Random object. The mapping from the position to
    // the seed should be fixed. Using the position as seed to feed Random objects will cause the
    // generated values to not be random enough because the position values are
    // close to each other. To make seeds fed into the Random objects unrelated,
    // we use a hashing function to map the position to its corresponding hashcode,
    // and use the hashcode as a seed to feed into the Random object.
    long hashCodeOfPosition = hashFunction().hashLong(position).asLong();
    return new Record(genKvPair(hashCodeOfPosition), nextDelay(hashCodeOfPosition));
  }

  /** Record generated by {@link #genRecord}. */
  public static class Record {
    public final KV<byte[], byte[]> kv;
    public final Duration sleepMsec;

    Record(KV<byte[], byte[]> kv, long sleepMsec) {
      this.kv = kv;
      this.sleepMsec = new Duration(sleepMsec);
    }
  }

  /**
   * Shape of the progress reporting curve as a function of the current offset in the {@link
   * SyntheticBoundedSource}.
   */
  public enum ProgressShape {
    /** Reported progress grows linearly from 0 to 1. */
    LINEAR,
    /** Reported progress decreases linearly from 0.9 to 0.1. */
    LINEAR_REGRESSING,
  }
}


text:
layout: post
title:  ADFIRWMC - 0. Disclaimers
date:   2018-03-01 15:33:28 -0500
categories: adfirwmc
---

## 0. Disclaimers

### You have to dig
As I built this course, I started realizing that perhaps the reader might not understand everything I am talking about. DFIR is not a field where everyone can know everything. It's just too wide and too deep. Attempting to define every term and provide background on all material would bloat this project beyond scope and diminish the value. If I didn't cover something, you might have to look it up. Searching for information is the crux of this job.

### I tried to keep it cheap
In an effort to limit barriers to education, I tried to limit the examples in this course to native, open source, or readily available free tools. Does that excluding commecial tools limit the completeness of this course? Yes, but this course is about developing your skills and not lining a vendor's pocket. Sadly, you are going to need a Windows 7 or newer system to play with to put a lot of this to use.

### Audience
I think this course is written to provide examples of DFIR techniques for two groups of people:
 1. Folks that have been in Information Security in one capacity or another and are looking to get into more hands on DFIR work.
 2. Others who might find this information useful or interesting.

This should not be the first computer related course you attempt.

### Omissions and Errors
There are two reasons I didn't include something in this course:
1. I didn't know about it. *It happens. Often.*
2. I thought you wouldn't immediately benefit from knowing it. This career field is deep, wide, and almost any fact about how things work can be refuted with an exception. This course is not designed to be extremely comprehensive, just helpful.

Either way, feel free to send me feedback and I will take a look.
### Organization

This course will cover a lot of material and most of it will be shown by example. While that is helpful in some respects, it can leave some topics less explicitly documented and more demonstrated during the course of scenario. Tools and command line utilities are going to be covered in this manner because I am not wasting our collective time documenting a technique AND all of a tool's command line functions when you can easily find that information elsewhere.

### Tone
This is meant to be informal. I authored 3 university courses last year and one of the consistent items of feedback I received was how well the frankly dry material was conveyed. While that might come across as unprofessional and lacking academic polish, I find it makes the material more digestible and that is point of learning, right?