text:
import os
from time import time
from time import sleep
import datetime
from optparse import OptionParser
import pickle
from threading import Thread, Lock

import numpy as np
from scipy.misc import imresize

import led

#import keras
import keras.backend as K
import model_keras
import tensorflow as tf

try:
    import config
except:
    print( "Driver.py failed to load config file config.py." )
    print( "Try copying config_empty.py to config.py and re-running." )
    exit()

def log( message, options ):
    logFileName = os.path.join(options.dir_ep, options.episode) + ".log"
    fmt = '%Y%m%d-%H%M%S.%f'
    datestr = datetime.datetime.now().strftime(fmt)

    with open(logFileName,'a') as outf:
        outf.write(datestr + ": " + message + "\n")

def linear_unbin(arr, N=15, offset=-1, R=2.0):
    '''
    preform inverse linear_bin, taking
    one hot encoded arr, and get max value
    rescale given R range and offset
    '''
    b = np.argmax(arr)
    a = b *(R/(N + offset)) + offset
    return a

class Driver:
    def __init__(self, model_path, camera, controller, model_name=None):
        """ model_path: location of the saved keras model
            camera: A instance of PiVideoStream
            controller: DriveDaemon which handles creating the camera and sending motor commands
        """
        K.set_learning_phase(False)

        self.stopped = False
        self.model_path = model_path
        self.camera = camera
        self.controller = controller
        #self.embedding = { "stop":0, "forward":1, "left":2, "right":3, "backward":4 }
        self.embedding = [ "stop", "forward", "left", "right", "backward" ]
        self.image_delay = 0.01
        led.turnLEDOn( True, 11 )
        led.turnLEDOn( True, 13 )
        self.isRNN = False
        self.continuous = False
        if self.isRNN:
            self.model = model_keras.make_model_lstm( len(self.embedding), (120,120,3), batch_size=1, timesteps=1, stateful=True, dropouts=[0.25,0.25,0.25,0.25,0.25] )
        else:
            #self.model = model_keras.make_model_test( len(self.embedding), (120,120,3), dropouts=[0.25,0.25,0.25,0.25,0.25] )
            if self.continuous:
                self.model = model_keras.make_model_fc( 1, (120,120,3), dkconv=True, dropouts=[0.25,0.25,0.25,0.25,0.25], categorical=False )
                #self.model = model_keras.read_model( model_path, model_name )
            else:
                self.model = model_keras.read_model( model_path, model_name )
                #self.model = model_keras.make_model_fc( len(self.embedding), (120,120,3), dkconv=True, dropouts=[0.25,0.25,0.25,0.25,0.25] )
        self.model.load_weights( os.path.join( model_path, model_name+"_weights.h5" ) )
        self.model._make_predict_function()
        self.graph = tf.get_default_graph()
        #self.graph = K.get_session().graph # This should work, too
        led.turnAllLEDOn( False )

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        # I'm not 100% sure this will result in everything being closed. Best to also call stop().
        self.stopped = True

    def stop(self,signum=0,frame=0):
        # indicate that the thread should be stopped
        self.stopped = True
        led.turnAllLEDOn( False )

    def _step(self):
        if self.stopped:
            return
        (image,pre_image) = self.camera.read()
        image = pre_image
        if image is not None:
            t2 = time()
            image = self.pre_process(image, image_norm=False)
            t3 = time()
            actions = self.model.predict_on_batch(image)
            if self.isRNN:
                actions = actions[0][0]
            else:
                actions = actions[0]
            t4 = time()
            #print( "Actions: {}".format( actions ) )
            #if action == 0:
            #    action = np.argmax( actions[1:] ) + 1
            #    #print( "skipping stop action" )
            if len(actions) == 15:
                steering = linear_unbin(actions)
                action = 'dk {} {}'.format( steering, 1.0 )
                self.controller.do_action( action )
            elif self.continuous:
                if len(actions) == 2:
                    action = 'throttles {} {}'.format( actions[0], actions[1] )
                else:
                    action = 'dk {} {}'.format( actions[0], 1.0 )
                self.controller.do_action( action )
            else:
                action = np.argmax(actions) # No exploration, just choose the best
                self.controller.do_action( self.embedding[action] )
            #print( "Times; {} {}".format( t3-t2, t4-t3 ) )

    def _drive( self ):
        led.turnLEDOn( True, 11 )
        with self.graph.as_default():
            while not self.stopped:
                sleep(self.image_delay)
                self._step()
        self.controller.do_action( "stop" )
        led.turnAllLEDOn( False )

    def startDriving( self ):
        self.stopped = False
        Thread(target=self._drive, args=()).start()

    def endDriving( self ):
        self.stop()

    def softmax(self, x):
      probs = np.exp(x - np.max(x))
      probs /= np.sum(probs )
      return probs

    def pre_process(self,  image, image_norm=True ):
        image = image.astype(np.float) # / 255.0
        if image.shape[0] > 120 or image.shape[1] > 120:
            image = imresize(image, (120,120), interp='nearest' ) # This is slow, 0.3 - 0.4 seconds

        if image_norm:
            image[:,:,0] -= np.mean(image[:,:,0])
            image[:,:,1] -= np.mean(image[:,:,1])
            image[:,:,2] -= np.mean(image[:,:,2])
            image[:,:,0] /= np.std(image[:,:,0])
            image[:,:,1] /= np.std(image[:,:,1])
            image[:,:,2] /= np.std(image[:,:,2])
        else:
            image /= 255.0

        if self.isRNN:
            image = image.reshape( 1, 1, 120, 120, 3 )
        else:
            image = image.reshape( 1, 120, 120, 3 )

        return image

def getOptions():
    usage = "Usage: python ./drive.py [options]"
    parser = OptionParser()
    parser.add_option("-e","--episode", help="Episode Name. Used for episode related file names. Defaults to date/time.");
    parser.add_option("--dir_ep", help="Directory for saving all episode related files. Defaults to episode name.");
    parser.add_option("--test_only", action="store_true", default=False, help="Run tests, then exit.");
    parser.add_option("--video", action="store_true", default=False, help="Record video during an episode.");
    parser.add_option("-s","--steps", type="int", default=300, help="Number of steps to run. Defaults to 300.");

    (options, args) = parser.parse_args()

    if not options.episode:
        n = datetime.datetime.now()
        options.episode = n.strftime('%Y%m%d_%H%M%S.drive')

    if not options.dir_ep:
        options.dir_ep = options.episode
    else:
        options.dir_ep = os.path.join( options.dir_ep, options.episode )

    options.dir_ep = os.path.expanduser(options.dir_ep)

    # Hard code this for now
    options.im_format = "numpy"

    return (options, args)

def test(options):
    cwd = os.getcwd()
    print( cwd )
    actions_path = os.path.join( options.dir_ep, options.episode+"_actions.text" )
    print( actions_path )
    actions_path = os.path.abspath(actions_path)
    print( actions_path )
    exit()

if __name__ == "__main__":
    (options, args) = getOptions()

    if options.test_only:
        test(options)

    #def __init__(self, drive_dir, video_path=None, camera=None, image_delay=None):
    #with Driver( os.path.expanduser("~/models/default.h5"), None, None ) as adrive:
    with Driver( os.path.expanduser("~/models"), None, None, model_name="Binned1" ) as adrive:
        adrive.startDriving()
        sleep(20)
        adrive.endDriving()


text:
package main

import (
	"flag"
	"fmt"

	"github.com/nlordell/utub"
)

type infoCommand struct{}

func (i *infoCommand) Name() string {
	return "info"
}

func (i *infoCommand) Description() string {
	return "outputs detailed information about the video"
}

func (i *infoCommand) ArgNames() string {
	return "<url | id | search>"
}

func (i *infoCommand) Vars(fs *flag.FlagSet) {}

func (i *infoCommand) Execute(args []string) {
	id, err := getID(args...)
	assert(err)

	video, err := getVideo(id)
	assert(err)

	config, err := utub.ExtractPlayerConfig(id)
	assert(err)
	formats, err := config.Formats()
	assert(err)

	formattable := make([][]string, len(formats))
	formatjusts := []justification{
		justifyRight,
		justifyLeft,
		justifyCenter,
	}
	for i, f := range formats {
		mediatype, _ := f.Meta().MediaType()
		formattable[i] = []string{
			fmt.Sprintf("[%d]", f.ID()),
			mediatype,
			f.Meta().Mode.String(),
			f.Meta().Resolution.String(),
			func() string {
				if f.Meta().FPS <= 0 {
					return ""
				}
				return fmt.Sprintf("%dfps", f.Meta().FPS)
			}(),
			func() string {
				if f.Meta().Bitrate <= 0 {
					return f.Meta().Quality
				}
				return fmt.Sprintf("%dkbps", f.Meta().Bitrate/1024)
			}(),
		}
	}

	display("ID", string(id))
	display("Name", video.Snippet.Title)
	display("Description", video.Snippet.Description)
	displayTable("Formats", formattable, formatjusts)
}

redpajama_set_name: RedPajamaGithub


text:
// -*- mode: c++; -*-

#include <ascii_table/ascii_table.h>
#include <string>
#include <vector>
#include <memory>
#include <sstream>

using namespace std;

template<>
class TypedCell<double> : public Cell {
public:
    TypedCell(double value) : value_(value) {}
    virtual ~TypedCell() {}

    virtual string show(size_t maxlen) const {
        ostringstream ss;
        ss.precision(3);
        ss << fixed << value_;
        if (ss.str().size() > maxlen)
            throw CellLengthException(ss.str(), maxlen);
        return ss.str();
    }
private:
    double value_;
};

int main() {
    Table t;

    t.addColumn(Column(Column::Header("String", {})));
    t.addColumn(Column(Column::Header("Fx string", {})), 20);
    t.addColumn(Column(Column::Header("int", {})));
    t.addColumn(Column(Column::Header("double", {})));
    t.addColumn(Column(Column::Header("Double column", {"a", "b"})));

    t.addRow({make_cell<string>("1, 1"),
                make_cell<string>("1, 2"),
                make_cell<int>(3),
                make_cell<double>(0.5),
                make_cell<int>(179),
                make_cell<int>(181)});
    t.addRow({make_cell<string>("2, 1"),
                make_cell<string>("2, 2"),
                make_cell<int>(3),
                make_cell<double>(123),
                make_cell<int>(183),
                make_cell<int>(185)});

    t.print();

    return 0;
}


text:
package com.sksamuel.elastic4s

import org.elasticsearch.action.admin.cluster.node.tasks.cancel.CancelTasksResponse
import org.elasticsearch.action.admin.cluster.node.tasks.list.ListTasksResponse
import org.elasticsearch.action.admin.cluster.tasks.PendingClusterTasksResponse
import org.elasticsearch.client.Client
import org.elasticsearch.common.unit.TimeValue

import scala.concurrent.Future
import scala.concurrent.duration.FiniteDuration

trait TaskApi {

  implicit object ListTasksDefinitionExecutable
    extends Executable[ListTasksDefinition, ListTasksResponse, ListTasksResponse] {
    override def apply(client: Client, d: ListTasksDefinition): Future[ListTasksResponse] = {
      val builder = client.admin().cluster().prepareListTasks(d.nodeIds: _*)
      d.waitForCompletion.foreach(builder.setWaitForCompletion)
      d.detailed.foreach(builder.setDetailed)
      injectFuture(builder.execute)
    }
  }

  implicit object CancelTasksDefinitionExecutable
    extends Executable[CancelTasksDefinition, CancelTasksResponse, CancelTasksResponse] {
    override def apply(client: Client, d: CancelTasksDefinition): Future[CancelTasksResponse] = {
      val builder = client.admin().cluster().prepareCancelTasks(d.nodeIds: _*)
      d.timeout.foreach(duration => builder.setTimeout(TimeValue.timeValueNanos(duration.toNanos)))
      builder.setActions(d.actions: _*)
      injectFuture(builder.execute)
    }
  }

  implicit object PendingClusterTasksDefinitionExecutable
    extends Executable[PendingClusterTasksDefinition, PendingClusterTasksResponse, PendingClusterTasksResponse] {
    override def apply(client: Client, d: PendingClusterTasksDefinition): Future[PendingClusterTasksResponse] = {
      val builder = client.admin().cluster().preparePendingClusterTasks()
      builder.setLocal(d.local)
      d.masterNodeTimeout.foreach(duration => builder.setMasterNodeTimeout(TimeValue.timeValueNanos(duration.toNanos)))
      injectFuture(builder.execute)
    }
  }
}

case class CancelTasksDefinition(nodeIds: Seq[String],
                                 timeout: Option[FiniteDuration] = None,
                                 actions: Seq[String] = Nil)

case class PendingClusterTasksDefinition(local: Boolean,
                                         masterNodeTimeout: Option[FiniteDuration] = None)

case class ListTasksDefinition(nodeIds: Seq[String],
                               detailed: Option[Boolean] = None,
                               waitForCompletion: Option[Boolean] = None)


text:
package org.apache.batik.bridge;

import java.awt.AWTPermission;
import java.io.FilePermission;
import java.io.SerializablePermission;
import java.lang.reflect.ReflectPermission;
import java.net.NetPermission;
import java.net.SocketPermission;
import java.security.AllPermission;
import java.security.Permission;
import java.sql.SQLPermission;
import java.util.PropertyPermission;
import java.util.Vector;

import javax.sound.sampled.AudioPermission;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget;

import org.apache.batik.dom.svg.SVGOMDocument;
import org.apache.batik.script.ScriptHandler;
import org.apache.batik.script.Window;
import org.apache.batik.util.ParsedURL;

/**
 * @author Vincent Hardy
 * @version $Id$
 */
public class JarCheckPermissionsGranted implements ScriptHandler {
    public static final String svgNS = "http://www.w3.org/2000/svg";
    public static final String testNS = "http://xml.apache.org/batik/test";

    /**
     * Path for the file tested with FilePermission
     */
    public static final String testedPath = "build.sh";

    /**
     * Host which is used for testing
     */
    public static final String testedHost = "nagoya.apache.org:8080";

    /**
     * Table of Permissions which will be tested.
     */
    protected static Object[][] basePermissions = {
        {"AllPermission", new AllPermission()},
        {"FilePermission read", new FilePermission(testedPath, "read")},
        {"FilePermission write", new FilePermission(testedPath, "write")},
        {"FilePermission execute", new FilePermission(testedPath, "execute")},
        {"FilePermission delete", new FilePermission(testedPath, "delete")},
        // 1.4 {"ServicePermission", new ServicePermission("krbtgt/EXAMPLE.COM@EXAMPLE.COM", "initiate")},
        {"SocketPermission accept", new SocketPermission(testedHost, "accept")},
        {"SocketPermission connect", new SocketPermission(testedHost, "connect")},
        {"SocketPermission listen", new SocketPermission(testedHost, "listen")},
        {"SocketPermission resolve", new SocketPermission(testedHost, "resolve")},
        {"AudioPermission play", new AudioPermission("play")},
        {"AudioPermission record", new AudioPermission("record")},
        {"AWTPermission accessClipboard", new AWTPermission("accessClipboard")},
        {"AWTPermission accessEventQueue", new AWTPermission("accessEventQueue")},
        {"AWTPermission listenToAllAWTEvents", new AWTPermission("listenToAllAWTEvents")},
        {"AWTPermission showWindowWithoutWarningBanner", new AWTPermission("showWindowWithoutWarningBanner")},
        {"AWTPermission readDisplayPixels", new AWTPermission("readDisplayPixels")},
        {"AWTPermission createRobot", new AWTPermission("createRobot")},
        {"AWTPermission fullScreenExclusive", new AWTPermission("fullScreenExclusive")},
        // 1.4 {"DelegationPermission", new DelegationPermission()},
        // 1.4 {"LoggingPermission", new LoggingPermission("control")},
        {"NetPermission setDefaultAuthenticator", new NetPermission("setDefaultAuthenticator")},
        {"NetPermission requestPasswordAuthentication", new NetPermission("requestPasswordAuthentication")},
        {"NetPermission specifyStreamHandler", new NetPermission("specifyStreamHandler")},
        {"PropertyPermission java.home read", new PropertyPermission("java.home", "read")},
        {"PropertyPermission java.home write", new PropertyPermission("java.home", "write")},
        {"ReflectPermission", new ReflectPermission("suppressAccessChecks")},
        {"RuntimePermission createClassLoader", new RuntimePermission("createClassLoader")},
        {"RuntimePermission getClassLoader", new RuntimePermission("getClassLoader")},
        {"RuntimePermission setContextClassLoader", new RuntimePermission("setContextClassLoader")},
        {"RuntimePermission setSecurityManager", new RuntimePermission("setSecurityManager")},
        {"RuntimePermission createSecurityManager", new RuntimePermission("createSecurityManager")},
        {"RuntimePermission exitVM", new RuntimePermission("exitVM")},
        {"RuntimePermission shutdownHooks", new RuntimePermission("shutdownHooks")},
        {"RuntimePermission setFactory", new RuntimePermission("setFactory")},
        {"RuntimePermission setIO", new RuntimePermission("setIO")},
        {"RuntimePermission modifyThread", new RuntimePermission("modifyThread")},
        {"RuntimePermission stopThread", new RuntimePermission("stopThread")},
        {"RuntimePermission modifyThreadGroup", new RuntimePermission("modifyThreadGroup")},
        {"RuntimePermission getProtectionDomain", new RuntimePermission("getProtectionDomain")},
        {"RuntimePermission readFileDescriptor", new RuntimePermission("readFileDescriptor")},
        {"RuntimePermission writeFileDescriptor", new RuntimePermission("writeFileDescriptor")},
        {"RuntimePermission loadLibrary.{library name}", new RuntimePermission("loadLibrary.{library name}")},
        {"RuntimePermission accessClassInPackage.java.security", new RuntimePermission("accessClassInPackage.java.security")},
        {"RuntimePermission defineClassInPackage.java.lang", new RuntimePermission("defineClassInPackage.java.lang")},
        {"RuntimePermission accessDeclaredMembers", new RuntimePermission("accessDeclaredMembers")},
        {"RuntimePermission queuePrintJob", new RuntimePermission("queuePrintJob")},

        {"SecurityPermission createAccessControlContext", new SerializablePermission("createAccessControlContext")},
        {"SecurityPermission getDomainCombiner", new SerializablePermission("getDomainCombiner")},
        {"SecurityPermission getPolicy", new SerializablePermission("getPolicy")},
        {"SecurityPermission setPolicy", new SerializablePermission("setPolicy")},
        {"SecurityPermission setSystemScope", new SerializablePermission("setSystemScope")},
        {"SecurityPermission setIdentityPublicKey", new SerializablePermission("setIdentityPublicKey")},
        {"SecurityPermission setIdentityInfo", new SerializablePermission("setIdentityInfo")},
        {"SecurityPermission addIdentityCertificate", new SerializablePermission("addIdentityCertificate")},
        {"SecurityPermission removeIdentityCertificate", new SerializablePermission("removeIdentityCertificate")},
        {"SecurityPermission printIdentity", new SerializablePermission("printIdentity")},
        {"SecurityPermission getSignerPrivateKey", new SerializablePermission("getSignerPrivateKey")},
        {"SecurityPermission setSignerKeyPair", new SerializablePermission("setSignerKeyPair")},

        {"SerializablePermission enableSubclassImplementation", new SerializablePermission("enableSubclassImplementation")},
        {"SerializablePermission enableSubstitution", new SerializablePermission("enableSubstitution")},

        {"SQLPermission", new SQLPermission("setLog")},

        // 1.4 {"SSLPermission setHostnameVerifier", new SSLPermission("setHostnameVerifier")}
        // 1.4{"SSLPermission getSSLSessionContext", new SSLPermission("getSSLSessionContext")}
    };

    /**
     * Set of Permissions to test. One is added if the Document is loaded from a host
     */
    private Object[][] permissions;

    /**
     * Runs this handler.
     * @param document The current document.
     * @param win An object which represents the current viewer.
     */
    public void run(final Document document, final Window win){
        //
        // If the document is loaded over the network, check that the
        // class has permission to access the server
        //
        ParsedURL docURL = ((SVGOMDocument)document).getParsedURL();
        if (docURL != null && docURL.getHost() != null &&
                !"".equals(docURL.getHost())) {
            permissions = new Object[basePermissions.length + 3][2];
            System.arraycopy(basePermissions, 0,
                             permissions, 3, basePermissions.length);

            String docHost = docURL.getHost();
            if (docURL.getPort() != -1) {
                docHost += ":" + docURL.getPort();
            }

            permissions[0][0] = "SocketPermission accept " + docHost;
            permissions[0][1] = new SocketPermission(docHost, "accept");
            permissions[1][0] = "SocketPermission connect " + docHost;
            permissions[1][1] = new SocketPermission(docHost, "connect");
            permissions[2][0] = "SocketPermission resolve " + docHost;
            permissions[2][1] = new SocketPermission(docHost, "resolve");
        } else {
            permissions = basePermissions;
        }

        EventTarget root = (EventTarget)document.getDocumentElement();
        root.addEventListener("SVGLoad", new EventListener() {
                public void handleEvent(Event evt){
                    SecurityManager sm = System.getSecurityManager();
                    int successCnt = 0;
                    Vector unexpectedDenial = new Vector();
                    int unexpectedDenialCnt = 0;
                    int unexpectedGrantsCnt = 0;

                    if (sm == null){
                        for (int i=0; i<permissions.length; i++) {
                            successCnt++;
                        }
                    }
                    else {
                        for (int i=0; i<permissions.length; i++) {
                            Permission p = (Permission)permissions[i][1];
                            try {
                                sm.checkPermission(p);
                                successCnt++;
                            } catch (SecurityException se){
                                unexpectedDenial.add(permissions[i][0]);
                                unexpectedDenialCnt++;
                            }
                        }
                    }

                    // Update the test's metadata
                    Element result = document.getElementById("testResult");
                    if ( successCnt == permissions.length ) {
                        result.setAttributeNS(null, "result", "passed");
                    } else {
                        System.out.println("test failed: " + unexpectedGrantsCnt + " / " + unexpectedDenialCnt);
                        result.setAttributeNS(null, "result", "failed");
                        result.setAttributeNS(null, "errorCode", "unexpected.grants.or.denials");

                        String unexpectedDenialString = "";

                        for (int i=0; i<unexpectedDenialCnt; i++) {
                            unexpectedDenialString += unexpectedDenial.elementAt(i).toString();
                        }

                        Element entry = null;

                        entry = document.createElementNS(testNS, "errorDescriptiongEntry");
                        entry.setAttributeNS(null, "id", "unexpected.denials.count");
                        entry.setAttributeNS(null, "value", "" + unexpectedDenialCnt);
                        result.appendChild(entry);

                        System.out.println("unexpected.denials : " + unexpectedDenialString);
                        entry = document.createElementNS(testNS, "errorDescriptionEntry");
                        entry.setAttributeNS(null, "id", "unexpected.denials");
                        entry.setAttributeNS(null, "value", unexpectedDenialString);
                        result.appendChild(entry);
                    }
                } }, false);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TicketOnline.Models
{
    public class CoachViewModel
    {
        public   int Id { get; set; }
        public string Name { get; set; }

        public string Type { get; set; }

        public string Router { get; set; }

        public int NumberSeat { get; set; }

        public DateTime StartDate { get; set; }

        public string StartHour { get; set; }

        public List<TicketVewModel> Tickets {get; set;}

        public CoachViewModel()
        {
            this.Tickets = new List<TicketVewModel>();
        }
    }
}


text:
package net.runelite.api;

public interface NameableContainer<T extends Nameable>
{
	/**
	 * Get the number of members in this container
	 *
	 * @return
	 */
	int getCount();

	/**
	 * Get the members in this container
	 *
	 * @return
	 */
	T[] getMembers();

	/**
	 * Find a nameable by name
	 *
	 * @param name the name
	 * @return
	 */
	T findByName(String name);
}


text:
As many of you have experienced, having a server exposed to the internet can be at least annoying and sometimes just plain dangerous if not properly secured.

This project started off a couple of years ago as a way to dynamically block people who were trying to brute-force ssh on my server by way of syslog passing auth events to it and, based on configurable regexs, pull out offending IPs and block them for a configurable amount of time.

Two last things to note:
 1. I'm a C/C++ developer writing perl so my perl looks like C code...
 2. As I'm mostly a FreeBSD guy, I've written this script with that in mind.  It may be portable to Linux or another system but that is not my primary goal at the moment.  This is simply a small, side project I use as an ocassional distraction.

# Basic Setup

To get going with pflogblock, I recommend the following basic configuration items:
 * The following dependencies are required for pflogblock to run:
  * A compatible syslog that is able to pipe messages to external applications
    * The default FreeBSD syslog is capable of this
  * A compatible firewall
    * Currently, only pf is supported - pflogblock uses pfctl directly
  * perl 5.18 or above
    * Currently building/testing with perl 5.20
  * perl File::Which (CPAN)
    * Can be found in FreeBSD ports: sysutils/p5-File-Which
 * Place pflogblock.pl in a location where it will be run by root
  * Ownership should be: root:wheel
  * Permissions should be: -rwxrx---- (750)
 * Setup cronjobs to automatically load the last known blacklist and expire IPs off of the blacklist
  * Example cronjobs for this can be found in this source tree: https://github.com/newodahs/pflogblock/blob/master/fbsd/root.crontab
  * Keep in mind you may need to set the PATH environment variable in your crontab, otherwise pflogblock may have trouble finding pfctl
 * Setup whitelist table and blacklist regex configuration files
  * Example blacklist regex configuration can be found in this source tree: https://github.com/newodahs/pflogblock/blob/master/fbsd/usr/local/etc/pflogblock_regex.conf
  * Example whitelist table can be found in this source tree: https://github.com/newodahs/pflogblock/blob/master/fbsd/var/db/pflogblock_whitelist
    * The whitelist is very important - you don't want to lock yourself out on accident!
 * Setup pf with a pflogblock table -- this is the table pflogblock will automatically update with what it believes to be malicious addresses
  * Example pf configuration lines can be found in this source tree: https://github.com/newodahs/pflogblock/blob/master/fbsd/etc/pf.conf
 * Setup syslog to pipe log messages from desired log file for processing
  * Example assumes the auth.log (which is likely the most appropriate)
  * Example syslog configuration lines can be found in this source tree: https://github.com/newodahs/pflogblock/blob/master/fbsd/etc/syslog.conf

# Advanced Configuration

Once you have everything up and working, feel free to mess around with the configuration a bit.  As I noted in the
first few lines of this file, I originally wrote this with an eye toward stopping brute-force ssh attempts.  It
should be possible, however, to pass just about any log messages through this script and take action to block any
address found.

Keep in mind, if you're writing your own custom regexs to take action on: pflogblock will only take action on the
first capture group in the regex.  Try to keep your captures to a single one for now - this may change in the future.

# Release Notes

July-2015
First public revision of this script.  Base functionality is as follows:
 * Accepts piped log messages from syslog for processing
  * See: https://www.freebsd.org/cgi/man.cgi?query=syslog.conf(5) for more information
 * Setup to be syslog smart - once run by syslog it will stay active while the pipe is open
  * This keeps the script at the ready while honoring documented behavior for this type of integration
 * Ships with two default blacklist regexs to determine bad behavior with
  * Default blacklist regexs may be overriden with: /usr/local/etc/pflogblock_regex.conf
 * Allows specification of a whitelist (addresses that will never be blacklisted)
  * Whitelist location is /var/db/pflogblock_whitelist;
 * Resolves DNS to IPv4 or IPv6 for blocking
  * Blocks /all/ associated address to resolved DNS entries (not just the first one)
 * Logs out its own activities to syslog (LOG_SECURITY)


text:
from DirectorBgnThread import directorThread
import traceback

"""
if __name__ == "__main__":
    dt = directorThread(None)
    dt.start()
    dt.max_triggers = 50
    dt.EnableDataSaving = False
    nFiles = 1
    dt.set_file_prefix("mytest")
    dt.set_file_path(".")
    dt.set_files_contiguous(True)
    dt.set_files_to_save(nFiles)
    dt.set_file_size(dt.max_triggers/nFiles)

    time.sleep(6)
    dt.set_DataAlias("paperino/image","paperino/mandelbrot")
    dt.set_player_priority("paperino",0)
    dt.set_player_priority("pippo",1)
    dt.set_player_priority("pluto",1)

    dt._started = True
    while (dt._started):
        time.sleep(1)
    print "-------------",dt.zcc.ask_for_log("paperino")
    print "-------------",dt.zcc.ask_for_log("pluto")
    print "-------------",dt.zcc.ask_for_log("pippo")
    #dt.join()
    print dt.PlayersInfo

"""
def get_user_input_loop(dt):
        while True:    # infinite loop
            try:
                n = raw_input("\n\nEnter command (type ? for help): ")
                cmd_in = (n.lower()).strip(' ')
                if cmd_in == "start":
                    dt._started = True
                elif cmd_in == "stop":
                    dt._started = False
                elif cmd_in == "players?":
                    print dt.PlayersInfo
                elif "priority[" in cmd_in:
                    plname = (cmd_in.split("[")[1]).split("]")[0]
                    prio = int((cmd_in.split("="))[-1])
                    dt.set_player_priority(plname,prio)
                elif "triggers=" in cmd_in:
                    max_triggers = int(cmd_in.split('=')[-1])
                    dt.max_triggers = max_triggers
                    print "OK"
                elif cmd_in == "quit":
                    return  # stops the loop
                elif cmd_in == "?":
                    print "Available commands:"
                    print "\tstart, stop, players?, triggers=N, priority[plname]=N, quit"
            except KeyboardInterrupt:
                print "Bye"
                return
            except Exception:
                traceback.print_exc()

if __name__ == "__main__":
    dt = directorThread(None)
    dt.start()
    #
    dt.max_triggers = 1
    dt.EnableDataSaving = False
    nFiles = 1
    dt.set_file_prefix("mytest")
    dt.set_file_path(".")
    dt.set_files_contiguous(True)
    dt.set_files_to_save(nFiles)
    dt.set_file_size(dt.max_triggers/nFiles)
    #
    get_user_input_loop(dt)
    dt.quit_and_exit()


text:
package it.unibz.krdb.obda.reformulation.semindex.tests;

import java.util.Set;

import it.unibz.krdb.obda.model.OBDADataFactory;
import it.unibz.krdb.obda.model.Predicate;
import it.unibz.krdb.obda.model.impl.OBDADataFactoryImpl;
import it.unibz.krdb.obda.ontology.BasicClassDescription;
import it.unibz.krdb.obda.ontology.OClass;
import it.unibz.krdb.obda.ontology.Ontology;
import it.unibz.krdb.obda.ontology.OntologyFactory;
import it.unibz.krdb.obda.ontology.PropertyExpression;
import it.unibz.krdb.obda.ontology.SomeValuesFrom;
import it.unibz.krdb.obda.ontology.impl.OntologyFactoryImpl;
import it.unibz.krdb.obda.owlrefplatform.core.dagjgrapht.Equivalences;
import it.unibz.krdb.obda.owlrefplatform.core.dagjgrapht.EquivalencesDAG;
import it.unibz.krdb.obda.owlrefplatform.core.dagjgrapht.TBoxReasoner;
import it.unibz.krdb.obda.owlrefplatform.core.dagjgrapht.TBoxReasonerImpl;
import it.unibz.krdb.obda.quest.dag.TestTBoxReasonerImpl_OnGraph;
import junit.framework.TestCase;

public class DAGChainTest extends TestCase {

	SemanticIndexHelper						helper				= new SemanticIndexHelper();

	private static final OBDADataFactory	predicateFactory	= OBDADataFactoryImpl.getInstance();
	private static final OntologyFactory	descFactory			= OntologyFactoryImpl.getInstance();

	private static <T> int sizeOf(Set<Equivalences<T>> set) {
		int size = 0;
		for(Equivalences<T> e: set){
			size += e.size();
		}
		return size;
	}

	public void test_simple_isa() {
		Ontology ontology = OntologyFactoryImpl.getInstance().createOntology();

		OClass ac = descFactory.createClass("a");
		OClass bc = descFactory.createClass("b");
		OClass cc = descFactory.createClass("c");

		ontology.addSubClassOfAxiomWithReferencedEntities(bc, ac);
		ontology.addSubClassOfAxiomWithReferencedEntities(cc, bc);

		TBoxReasonerImpl reasoner0 = new TBoxReasonerImpl(ontology);
		TBoxReasoner reasoner = TBoxReasonerImpl.getChainReasoner(reasoner0);
		EquivalencesDAG<BasicClassDescription> classes = reasoner.getClasses();

		Equivalences<BasicClassDescription> ac0 = classes.getVertex(ac);
		Equivalences<BasicClassDescription> bc0 = classes.getVertex(bc);
		Equivalences<BasicClassDescription> cc0 = classes.getVertex(cc);

		assertTrue(classes.getSub(ac0).contains(bc0));
		assertTrue(classes.getSub(ac0).contains(cc0));
		assertEquals(sizeOf(classes.getSub(ac0)), 3); // getDescendants is reflexive

		assertTrue(classes.getSub(bc0).contains(cc0));
		assertEquals(sizeOf(classes.getSub(bc0)), 2);  // getDescendants is reflexive
		assertEquals(sizeOf(classes.getSub(cc0)), 1);  // getDescendants is reflexive
	}

	public void test_exists_simple() {
		Ontology ontology = OntologyFactoryImpl.getInstance().createOntology();

		PropertyExpression rprop = descFactory.createObjectProperty("r");
		PropertyExpression riprop = rprop.getInverse();
		OClass ac = descFactory.createClass("a");
		SomeValuesFrom er = descFactory.createPropertySomeRestriction(rprop);
		SomeValuesFrom ier = descFactory.createPropertySomeRestriction(riprop);
		OClass cc = descFactory.createClass("c");

		ontology.addSubClassOfAxiomWithReferencedEntities(er, ac);
		ontology.addSubClassOfAxiomWithReferencedEntities(cc, ier);

		//generate Graph
		TBoxReasonerImpl res0 = new  TBoxReasonerImpl(ontology);
		//DefaultDirectedGraph<Description,DefaultEdge> res1 = res0.getGraph();

//		for (Description nodes: res.vertexSet()) {
//			System.out.println("---- " + nodes);
//		}

		TestTBoxReasonerImpl_OnGraph reasoner = new TestTBoxReasonerImpl_OnGraph(res0);
		reasoner.convertIntoChainDAG();

		EquivalencesDAG<BasicClassDescription> classes = reasoner.getClasses();

		Equivalences<BasicClassDescription> ac0 = classes.getVertex(ac);
		Equivalences<BasicClassDescription> cc0 = classes.getVertex(cc);
		Equivalences<BasicClassDescription> er0 = classes.getVertex(er);
		Equivalences<BasicClassDescription> ier0 = classes.getVertex(ier);

		assertTrue(classes.getSub(ac0).contains(er0));
		assertTrue(classes.getSub(ac0).contains(ier0));
		assertTrue(classes.getSub(ac0).contains(cc0));
		assertEquals(sizeOf(classes.getSub(ac0)), 4);  // getDescendants is reflexive

		assertTrue(classes.getSub(er0).contains(cc0));
		assertEquals(sizeOf(classes.getSub(er0)), 2);  // getDescendants is reflexive

		assertTrue(classes.getSub(ier0).contains(cc0));
		assertEquals(sizeOf(classes.getSub(ier0)), 2);  // getDescendants is reflexive
		assertEquals(sizeOf(classes.getSub(cc0)), 1);  // getDescendants is reflexive
	}

	public void test_exists_complex() {

		Ontology ontology = OntologyFactoryImpl.getInstance().createOntology();

		PropertyExpression rprop = descFactory.createObjectProperty("r");
		PropertyExpression riprop = rprop.getInverse();

		OClass ac = descFactory.createClass("a");
		SomeValuesFrom er = descFactory.createPropertySomeRestriction(rprop);
		SomeValuesFrom ier = descFactory.createPropertySomeRestriction(riprop);
		OClass cc = descFactory.createClass("c");
		OClass bc = descFactory.createClass("b");
		OClass dc = descFactory.createClass("d");

		ontology.addSubClassOfAxiomWithReferencedEntities(er, ac);
		ontology.addSubClassOfAxiomWithReferencedEntities(cc, ier);
		ontology.addSubClassOfAxiomWithReferencedEntities(bc, er);
		ontology.addSubClassOfAxiomWithReferencedEntities(ier, dc);

		//DAGImpl dag221 = DAGBuilder.getDAG(ontology);
		//TBoxReasonerImpl reasoner221 = new TBoxReasonerImpl(dag221);
		//DAGImpl dagChain221 = reasoner221.getChainDAG();
		TBoxReasonerImpl resoner0 = new TBoxReasonerImpl(ontology);
		TBoxReasoner reasoner = TBoxReasonerImpl.getChainReasoner(resoner0);

		EquivalencesDAG<BasicClassDescription> classes = reasoner.getClasses();

		Equivalences<BasicClassDescription> ac0 = classes.getVertex(ac);
		Equivalences<BasicClassDescription> bc0 = classes.getVertex(bc);
		Equivalences<BasicClassDescription> cc0 = classes.getVertex(cc);
		Equivalences<BasicClassDescription> dc0 = classes.getVertex(dc);
		Equivalences<BasicClassDescription> er0 = classes.getVertex(er);
		Equivalences<BasicClassDescription> ier0 = classes.getVertex(ier);

		assertTrue(classes.getSub(ac0).contains(er0));
		assertTrue(classes.getSub(ac0).contains(ier0));
		assertTrue(classes.getSub(ac0).contains(cc0));
		assertTrue(classes.getSub(ac0).contains(bc0));
		assertEquals(sizeOf(classes.getSub(ac0)), 5);  // getDescendants is reflexive

		assertTrue(classes.getSub(dc0).contains(er0));
		assertTrue(classes.getSub(dc0).contains(ier0));
		assertTrue(classes.getSub(dc0).contains(cc0));
		assertTrue(classes.getSub(dc0).contains(bc0));
		assertEquals(sizeOf(classes.getSub(dc0)), 5);  // getDescendants is reflexive

		assertTrue(classes.getSub(er0).contains(bc0));
		assertTrue(classes.getSub(er0).contains(cc0));
		assertEquals(sizeOf(classes.getSub(er0)), 3);  // getDescendants is reflexive

		assertTrue(classes.getSub(ier0).contains(bc0));
		assertTrue(classes.getSub(ier0).contains(cc0));
		assertEquals(sizeOf(classes.getSub(ier0)), 3);  // getDescendants is reflexive

		assertEquals(sizeOf(classes.getSub(bc0)), 1);  // getDescendants is reflexive
		assertEquals(sizeOf(classes.getSub(cc0)), 1);  // getDescendants is reflexive
	}
}


text:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <saffire/general/hashtable.h>
#include <saffire/memory/smm.h>
#include <saffire/general/string.h>
#include <saffire/objects/object.h>
#include <saffire/debug.h>

extern t_hashfuncs chained_hf;

#define HT_INITIAL_BUCKET_COUNT    16           // Initial hash size
#define HT_LOAD_FACTOR           1.25           // Above this load, we will increase the hash size (it's above 1.00
                                                // because we use chaining instead of linear probing or other means)
#define HT_RESIZE_FACTOR         1.75           // Factor to resize to (current size * ht_resize_factor)

#define DEFAULT_HASHFUNCS        &chained_hf     // Default hash table functionality

/**
 * Creates new hash table
 */
static t_hash_table *_ht_create(int bucket_count, float load_factor, float resize_factor, t_hashfuncs *hashfuncs) {
    // Allocate memory for table and buckets
    t_hash_table *ht = (t_hash_table *) smm_malloc(sizeof (t_hash_table));

    ht->bucket_count = 0;
    ht->element_count = 0;
    ht->load_factor = load_factor;
    ht->resize_factor = resize_factor;
    ht->copy_on_write = 0;
    ht->hashfuncs = hashfuncs;
    ht->head = NULL;
    ht->tail = NULL;

    ht->hashfuncs->resize(ht, bucket_count);
    return ht;
}

/**
 * Create a new hash table with all default value
 */
t_hash_table *ht_create(void) {
    return _ht_create(HT_INITIAL_BUCKET_COUNT, HT_LOAD_FACTOR, HT_RESIZE_FACTOR, DEFAULT_HASHFUNCS);
}

/**
 * Create a new hash table with customized values
 */
t_hash_table *ht_create_custom(int bucket_count, float load_factor, float resize_factor, t_hashfuncs *hashfuncs) {
    return _ht_create(bucket_count, load_factor, resize_factor, hashfuncs);
}

/**
 *
 * @param ht
 * @param copy_on_write
 * @return
 */
t_hash_table *ht_copy(t_hash_table *ht, int copy_on_write) {
    t_hash_table *copy = smm_malloc(sizeof (t_hash_table));

    memcpy(copy, ht, sizeof (t_hash_table));

    copy->copy_on_write = copy_on_write;

    if (!copy_on_write) {
        ht->hashfuncs->deep_copy(copy);
    }

    return copy;
}

/**
 * Free a hash table
 */
void ht_destroy(t_hash_table *ht) {
    t_hash_table_bucket *bucket, *next_bucket;

    // Nothing to free
    if (!ht) return;

    if (!ht->copy_on_write) {
        // Destroy buckets
        bucket = ht->head;
        while (bucket) {
            // Find next bucket
            next_bucket = bucket->next_element;

            // Now, we can safely remove bucket
            ht_key_free(bucket->key);
            smm_free(bucket);

            // goto next bucket
            bucket = next_bucket;
        }

        // Free bucket list array
        smm_free(ht->bucket_list);
    }

    // Destroy hash table
    smm_free(ht);
    return;
}

/**
 *
 * @param ht
 * @param s
 * @return
 */
void *ht_find(t_hash_table *ht, t_hash_key *key) {
    return ht->hashfuncs->find(ht, key);
}
void *ht_find_str(t_hash_table *ht, char *key) {
    t_hash_key *hkey = ht_key_create(HASH_KEY_STR, (void *)key);
    void *ret = ht_find(ht, hkey);
    ht_key_free(hkey);
    return ret;
}
void *ht_find_num(t_hash_table *ht, long key) {
    t_hash_key *hkey = ht_key_create(HASH_KEY_NUM, (void *)key);
    void *ret = ht_find(ht, hkey);
    ht_key_free(hkey);
    return ret;
}
void *ht_find_obj(t_hash_table *ht, t_object *key) {
    t_hash_key *hkey = ht_key_create(HASH_KEY_OBJ, key);
    void *ret = ht_find(ht, hkey);
    ht_key_free(hkey);
    return ret;
}

void *ht_find_ptr(t_hash_table *ht, void *key) {
    t_hash_key *hkey = ht_key_create(HASH_KEY_PTR, key);
    void *ret = ht_find(ht, hkey);
    ht_key_free(hkey);
    return ret;
}

/**
 * Return 0 when key is not found, 1 otherwise
 */
int ht_exists(t_hash_table *ht, t_hash_key *key) {
    return ht->hashfuncs->exists(ht, key);
}
int ht_exists_str(t_hash_table *ht, char *key) {
    t_hash_key *hkey = ht_key_create(HASH_KEY_STR, (void *)key);
    int ret = ht_exists(ht, hkey);
    ht_key_free(hkey);
    return ret;
}
int ht_exists_num(t_hash_table *ht, long key) {
    t_hash_key *hkey = ht_key_create(HASH_KEY_NUM, (void *)key);
    int ret = ht_exists(ht, hkey);
    ht_key_free(hkey);
    return ret;
}
int ht_exists_obj(t_hash_table *ht, t_object *key) {
    t_hash_key *hkey = ht_key_create(HASH_KEY_OBJ, key);
    int ret = ht_exists(ht, hkey);
    ht_key_free(hkey);
    return ret;
}
int ht_exists_ptr(t_hash_table *ht, void *key) {
    t_hash_key *hkey = ht_key_create(HASH_KEY_PTR, key);
    int ret = ht_exists(ht, hkey);
    ht_key_free(hkey);
    return ret;
}

/**
 * Adds ht[key] = value;
 * Note that key is not duplicated.
 *
 * @param ht
 * @param key
 * @param value
 * @return
 */
int ht_add(t_hash_table *ht, t_hash_key *key, void *value) {
    if (ht->copy_on_write) {
        ht->hashfuncs->deep_copy(ht);
    }
    return ht->hashfuncs->add(ht, key, value);
}
int ht_add_str(t_hash_table *ht, char *key, void *value) {
    return ht_add(ht, ht_key_create(HASH_KEY_STR, (void *)key), value);
}
int ht_add_num(t_hash_table *ht, long key, void *value) {
    return ht_add(ht, ht_key_create(HASH_KEY_NUM, (void *)key), value);
}
int ht_add_obj(t_hash_table *ht, t_object *key, void *value) {
    return ht_add(ht, ht_key_create(HASH_KEY_OBJ, key), value);
}
int ht_add_ptr(t_hash_table *ht, void *key, void *value) {
    return ht_add(ht, ht_key_create(HASH_KEY_PTR, key), value);
}

int ht_append_num(t_hash_table *ht, void *value) {
    return ht_add_num(ht, ht->element_count, value);
}

/**
 * Replace key/value into hashtable
 */
void *ht_replace(t_hash_table *ht, t_hash_key *key, void *value) {
    if (ht->copy_on_write) {
        ht->hashfuncs->deep_copy(ht);
    }

    /* Check if the key exists, if so, remove and add new value. We do this because even though the
     * key by itself is equal, it could be on a different address. It would mean that if we do
     * key comparison the wrong way (by address, instead of their actual value), things can go wrong. */
    if (ht->hashfuncs->exists(ht, key)) {
        void *data = ht->hashfuncs->find(ht, key);
        ht->hashfuncs->remove(ht, key);
        ht->hashfuncs->add(ht, key, value);
        return data;
    }

    return ht->hashfuncs->replace(ht, key, value);
}
void *ht_replace_str(t_hash_table *ht, char *key, void *value) {
    t_hash_key *hkey = ht_key_create(HASH_KEY_STR, key);
    return ht_replace(ht, hkey, value);
}
void *ht_replace_num(t_hash_table *ht, long key, void *value) {
    t_hash_key *hkey = ht_key_create(HASH_KEY_NUM, (void *)key);
    return ht_replace(ht, hkey, value);

}
void *ht_replace_obj(t_hash_table *ht, t_object *key, void *value) {
    t_hash_key *hkey = ht_key_create(HASH_KEY_OBJ, key);
    return ht_replace(ht, hkey, value);
}
void *ht_replace_ptr(t_hash_table *ht, void *key, void *value) {
    t_hash_key *hkey = ht_key_create(HASH_KEY_PTR, key);
    return ht_replace(ht, hkey, value);
}

/**
 * Removes key from hashtable
 */
void *ht_remove(t_hash_table *ht, t_hash_key *key) {
    if (ht->copy_on_write) {
        ht->hashfuncs->deep_copy(ht);
    }
    return ht->hashfuncs->remove(ht, key);
}
void *ht_remove_str(t_hash_table *ht, char *key) {
    t_hash_key *hkey = ht_key_create(HASH_KEY_STR, key);
    void *ret = ht_remove(ht, hkey);
    ht_key_free(hkey);
    return ret;
}
void *ht_remove_num(t_hash_table *ht, long key) {
    t_hash_key *hkey = ht_key_create(HASH_KEY_NUM, (void *)key);
    void *ret = ht_remove(ht, hkey);
    ht_key_free(hkey);
    return ret;
}
void *ht_remove_obj(t_hash_table *ht, t_object *key) {
    t_hash_key *hkey = ht_key_create(HASH_KEY_OBJ, key);
    void *ret = ht_remove(ht, hkey);
    ht_key_free(hkey);
    return ret;
}
void *ht_remove_ptr(t_hash_table *ht, void *key) {
    t_hash_key *hkey = ht_key_create(HASH_KEY_PTR, key);
    void *ret = ht_remove(ht, hkey);
    ht_key_free(hkey);
    return ret;
}

/*
 * ITERATOR FUNCTIONALITY
 */

int ht_iter_init(t_hash_iter *iter, t_hash_table *ht) {
    iter->ht = ht;
    iter->bucket_idx = 0;
    iter->bucket = ht ? ht->head : NULL;
    return 1;
}

int ht_iter_init_tail(t_hash_iter *iter, t_hash_table *ht) {
    iter->ht = ht;
    iter->bucket_idx = 0;
    iter->bucket = ht ? ht->tail : NULL;
    return 1;
}

/**
 * Rewind hash table (or initialize a new table)
 */
int ht_iter_rewind(t_hash_iter *iter, t_hash_table *ht) {
    if (iter == NULL) return 0;

    // No hash table set, and no hash table given
    if (iter->ht == NULL && ht == NULL) return 0;

    // Set hash table
    if (ht != NULL) iter->ht = ht;

    iter->bucket_idx = 0;
    iter->bucket = ht->head;

    return 1;
}

/**
 * Return 0 when iterator is not valid (no more elements)
 */
int ht_iter_valid(t_hash_iter *iter) {
    return (iter->bucket != NULL);
}

/**
 * Goto next element (either inside the bucket, or the next bucket)
 */
int ht_iter_next(t_hash_iter *iter) {
    // Nothing found (or no more items)
    if (iter->bucket == NULL) return 0;

    iter->bucket = iter->bucket->next_element;
    return (iter->bucket != NULL);
}

int ht_iter_prev(t_hash_iter *iter) {
    // Nothing found (or no more items)
    if (iter->bucket == NULL) return 0;

    iter->bucket = iter->bucket->prev_element;
    return (iter->bucket != NULL);
}

/**
 * Fetch key from current element
 */
t_hash_key *ht_iter_key(t_hash_iter *iter) {
    if (iter->bucket == NULL) return NULL;
    return iter->bucket->key;
}

char *ht_iter_key_str(t_hash_iter *iter) {
    if (iter->bucket == NULL) return NULL;
    return iter->bucket->key->val.s;
}

long ht_iter_key_num(t_hash_iter *iter) {
    if (iter->bucket == NULL) return 0;
    return iter->bucket->key->val.n;
}

t_object *ht_iter_key_obj(t_hash_iter *iter) {
    if (iter->bucket == NULL) return NULL;
    return iter->bucket->key->val.o;
}

void *ht_iter_key_ptr(t_hash_iter *iter) {
    if (iter->bucket == NULL) return NULL;
    return (void *)iter->bucket->key->val.p;
}

/**
 * Fetch value from current element
 */
void *ht_iter_value(t_hash_iter *iter) {
    if (iter->bucket == NULL) return NULL;
    return iter->bucket->value;
}

/**
 *
 */
t_hash_key *ht_key_create(int type, void *val) {
    t_hash_key *hk = (t_hash_key *)malloc(sizeof(t_hash_key));
    switch (type) {
        case HASH_KEY_STR :
            hk->type = HASH_KEY_STR;
            hk->val.s = string_strdup0((char *)val);
            break;
        case HASH_KEY_NUM :
            hk->type = HASH_KEY_NUM;
            hk->val.n = (uintptr_t)val;
            break;
        case HASH_KEY_PTR :
            hk->type = HASH_KEY_PTR;
            hk->val.p = (uintptr_t)val;
            break;
        default:
        case HASH_KEY_OBJ :
            hk->type = HASH_KEY_OBJ;
            hk->val.o = (t_object *)val;
            break;

    }
    return hk;
}

/**
 * Creates a copy of a key
 */
t_hash_key *ht_key_copy(t_hash_key *org) {
    t_hash_key *cpy = (t_hash_key *)malloc(sizeof(t_hash_key));
    memcpy(cpy, org, sizeof(t_hash_key));

    if (cpy->type == HASH_KEY_STR) {
        cpy->val.s = string_strdup0(org->val.s);
    }
    return cpy;
}

/**
 * Free hash key
 */
void ht_key_free(t_hash_key *hk) {
    if (!hk) return;

    if (hk->type == HASH_KEY_STR) {
        smm_free(hk->val.s);
    }
    smm_free(hk);
}

#ifdef __DEBUG

void ht_debug(t_hash_table *ht) {
    t_hash_iter iter;
    ht_iter_init(&iter, ht);

    while (ht_iter_valid(&iter)) {
        t_hash_key *key = ht_iter_key(&iter);
        t_string *s = NULL;
        if (key->type == HASH_KEY_STR) {
            s = char0_to_string(key->val.s);
        } else if (key->type == HASH_KEY_NUM) {
            smm_asprintf_string(&s, char0_to_string("%d"), key->val.n);
        } else if (key->type == HASH_KEY_PTR) {
            smm_asprintf_string(&s, char0_to_string("%p"), key->val.p);
        } else if (key->type == HASH_KEY_OBJ) {
            smm_asprintf_string(&s, char0_to_string("%s{%d}"), object_debug(key->val.o), ((t_object *)key->val.o)->ref_count);
        }
        t_object *obj = ht_iter_value(&iter);

        DEBUG_PRINT_STRING_ARGS("%-40s => %s{%d}[%08X]\n", s->val, object_debug(obj), obj->ref_count, (intptr_t)obj);

        string_free(s);
        ht_iter_next(&iter);
    }
}

void ht_debug_keys(t_hash_table *ht) {
    t_hash_iter iter;
    ht_iter_init(&iter, ht);

    while (ht_iter_valid(&iter)) {
        t_hash_key *key = ht_iter_key(&iter);
        t_string *s;
        if (key->type == HASH_KEY_STR) {
            s = char0_to_string(key->val.s);
        } else if (key->type == HASH_KEY_NUM) {
            smm_asprintf_string(&s, char0_to_string("%d"), key->val.n);
        } else if (key->type == HASH_KEY_NUM) {
            smm_asprintf_string(&s, char0_to_string("%p"), key->val.p);
        } else if (key->type == HASH_KEY_OBJ) {
            smm_asprintf_string(&s, char0_to_string("%s{%d}"), object_debug(key->val.o), ((t_object *)key->val.o)->ref_count);
        }

        DEBUG_PRINT_STRING_ARGS("%-40s\n", s->val);

        string_free(s);
        ht_iter_next(&iter);
    }
}

#endif


text:
package org.adligo.tests4j.models.shared.results;

import org.adligo.tests4j.models.shared.association.I_ClassAssociations;
import org.adligo.tests4j.models.shared.coverage.I_SourceFileCoverageBrief;
import org.adligo.tests4j.models.shared.coverage.SourceFileCoverageBrief;
import org.adligo.tests4j.shared.asserts.reference.I_ClassAttributes;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SourceFileTrialResult extends BaseTrialResult implements I_SourceFileTrialResult {
	private SourceFileTrialResultMutant mutant;
	private SourceFileCoverageBrief probes;
	private I_ClassAssociations dependencies;
	private Map<String, I_ClassAttributes> references_;

	public SourceFileTrialResult() {
		mutant = new SourceFileTrialResultMutant();
	}

	public SourceFileTrialResult(I_SourceFileTrialResult p) {
		super(p);
		mutant = new SourceFileTrialResultMutant(p, false);
		if (p.hasRecordedCoverage()) {
			probes = new SourceFileCoverageBrief( p.getSourceFileCoverage());
		}
		dependencies = p.getDependencies();
		if (dependencies != null) {
			references_ = new HashMap<>();
			List<I_ClassAttributes> ars = dependencies.getReferences();
			for (I_ClassAttributes ar: ars) {
				references_.put(ar.getName(), ar);
			}
			references_ = Collections.unmodifiableMap(references_);
		} else {
			references_ = Collections.emptyMap();
		}
	}

	public I_SourceFileCoverageBrief getSourceFileCoverage() {
		return probes;
	}

	public String getSourceFileName() {
		return mutant.getSourceFileName();
	}

	@Override
	public boolean hasRecordedCoverage() {
		if (probes == null) {
			return false;
		}
		return true;
	}

	public I_ClassAssociations getDependencies() {
		return dependencies;
	}

	public void setDependencies(I_ClassAssociations dependencies) {
		this.dependencies = dependencies;
	}

	@Override
	public I_ClassAttributes getReferences(String className) {
		return references_.get(className);
	}

	@Override
	public I_ClassAttributes getSourceClassAttributes() {
		return references_.get(mutant.getSourceFileName());
	}
}