text:
function [ plotHandle ] = plotDataTimeDomain(data, freqIndex, tStarth, tEndh, timeScaleFactor, reductionFactor, plotIdentifiers)
%PLOTDATATIMEDOMAIN Plotting raw data in the time domain
%
%   H = PLOTDATATIMEDOMAIN(D, F) plots all data in D at the frequency
%   with index F
%
%   H = PLOTDATATIMEDOMAIN(D, F, S) plots all data in D at the frequency
%   with index F from time S. S is hours counted from the first sample
%
%   H = PLOTDATATIMEDOMAIN(D, F, S, E) plots the data in D at the frequency
%   with index F from time S until E. S and E are hours counted from the
%   first sample
%
%   H = PLOTDATATIMEDOMAIN(D, F, S, E, T) plots the data in D at the frequency
%   with index F from time S until E. S and E are hours counted from the
%   first sample. T (1, 60, 3600, 86400) scales the time axis from seconds
%   to minutes, hours or days.
%
%   H = PLOTDATATIMEDOMAIN(D, F, S, E, T, R) plots the data in D at the frequency
%   with index F from time S until E. S and E are hours counted from the
%   first sample. E (1, 60, 3600, 86400) scales the time axis from seconds
%   to minutes, hours or days. The data is reduced by the factor R, thus
%   for R=10 only every 10th data point is plotted
%
%   H = PLOTDATATIMEDOMAIN(D, F, S, E, R, T, I) plots the data in D at the frequency
%   with index F from time S until E. S and E are hours counted from the
%   first sample. E (1, 60, 3600, 86400) scales the time axis from seconds
%   to minutes, hours or days. The data is reduced by the factor R, thus
%   for R=10 only every 10th data point is plotted. I is a string selecting
%   the plots to be created, it can contain any or all of the following:
%       'mag'   - plots the signal magnitude
%       'phase' - plots the signal phase
%       'bits'  - plots the DIO bits
%   Combinations such as 'mag phase bits' displays those three plots.
%
%   sebastian.buergel@bsse.etz.ch, 2015

    narginchk(2, 7);
    if nargin == 2 % assume we want to plot everything in s, no reduction
        tStarth = 0;
        tEndh = inf;
        timeScaleFactor = 1;
        reductionFactor = 1;
        plotIdentifiers = 'mag phase bits';
    elseif nargin == 3 % assume we want to plot until last sample in s, no reduction
        tEndh = inf;
        timeScaleFactor = 1;
        reductionFactor = 1;
        plotIdentifiers = 'mag phase bits';
    elseif nargin == 4 % assume we want to plot in s, no reduction
        timeScaleFactor = 1;
        reductionFactor = 1;
        plotIdentifiers = 'mag phase bits';
    elseif nargin == 5 % assume we do not want to reduce the data
        reductionFactor = 1;
        plotIdentifiers = 'mag phase bits';
    elseif nargin == 6 % assume we want to plot everything
        plotIdentifiers = 'mag phase bits';
    end
    % estimating the unit in the label of the x-axis
    timeUnitStr = '';
    if (timeScaleFactor == 1)
        timeUnitStr = 's';
    elseif (timeScaleFactor == 60)
        timeUnitStr = 'min';
    elseif (timeScaleFactor == 3600)
        timeUnitStr = 'h';
    elseif (timeScaleFactor == 86400)
        timeUnitStr = 'd';
    else
        timeUnitStr = [num2str(timeScaleFactor), 's'];
    end

    % finding start and end point in samples
    ts = data.ts(1:1:end) - data.ts(1);
    iStart = find(ts/3600 > tStarth, 1);
    iEnd = find(ts/3600 > tEndh, 1);
    if (isempty(iStart))
        iStart = 1;
    end
    if (isempty(iEnd))
        iEnd = size(ts,1);
    end

    % cropping and reducing data for plotting
    ts = ts(iStart:reductionFactor:iEnd);
    mag = data.mag(iStart:reductionFactor:iEnd, freqIndex);
    phi = data.phase(iStart:reductionFactor:iEnd);
    bits = data.bits(iStart:reductionFactor:iEnd);% - min(data.bits);
    freq = data.f(freqIndex);

    % estimating the unit in the label of the y-axis
    freqString = '';
    if (freq > 1e9)
        freqString = [num2str(freq/1e9), ' GHz'];
    elseif (freq > 1e6)
        freqString = [num2str(freq/1e6), ' MHz'];
    elseif (freq > 1e3)
        freqString = [num2str(freq/1e3), ' kHz'];
    else
        freqString = [num2str(freq), ' Hz'];
    end

    % make plots
    if (~isempty(strfind(plotIdentifiers,'mag')))
        figure(1);
        plotHandle = plot(ts./timeScaleFactor, mag, 'black');
        set(plotHandle, 'LineWidth', 1);
        xlabel(['Time [', timeUnitStr, ']']);
        ylabel([freqString, ' Signal magnitude [V]']);
    end

    if (~isempty(strfind(plotIdentifiers,'phase')))
        figure(2);
        plotHandle = plot(ts./timeScaleFactor, phi, 'black');
        set(plotHandle, 'LineWidth', 1);
        xlabel(['Time [', timeUnitStr, ']']);
        ylabel([freqString, ' Signal phase [deg]']);
    end

    if (~isempty(strfind(plotIdentifiers,'bits')))
        figure(3);
        plotHandle = plot(ts./timeScaleFactor, bitshift(bits,20,'uint32')/uint32(2^28), 'x', 'Color', 'black');
        set(plotHandle, 'LineWidth', 1);
        xlabel(['Time [', timeUnitStr, ']']);
        ylabel('DIO bits');
    end
end


text:
"""Configures pytest (beyond the ini file)."""
import matplotlib as mpl
import numpy
import pytest
from matplotlib import pyplot as plt

from dapper.dpr_config import rc

@pytest.fixture(autouse=True)
def add_sci(doctest_namespace):
    """Add numpy as np for doctests."""
    doctest_namespace["np"] = numpy
    doctest_namespace["mpl"] = mpl
    doctest_namespace["plt"] = plt
    doctest_namespace["rnd"] = numpy.random
    doctest_namespace["rc"] = rc

redpajama_set_name: RedPajamaGithub


text:
#ifndef __PERF_AUXTRACE_H
#define __PERF_AUXTRACE_H

#include <sys/types.h>
#include <stdbool.h>
#include <stddef.h>
#include <linux/list.h>
#include <linux/perf_event.h>
#include <linux/types.h>

#include "../perf.h"
#include "event.h"
#include "session.h"
#include "debug.h"

union perf_event;
struct perf_session;
struct perf_evlist;
struct perf_tool;
struct option;
struct record_opts;
struct auxtrace_info_event;
struct events_stats;

enum auxtrace_type {
	PERF_AUXTRACE_UNKNOWN,
	PERF_AUXTRACE_INTEL_PT,
	PERF_AUXTRACE_INTEL_BTS,
};

enum itrace_period_type {
	PERF_ITRACE_PERIOD_INSTRUCTIONS,
	PERF_ITRACE_PERIOD_TICKS,
	PERF_ITRACE_PERIOD_NANOSECS,
};

/**
 * struct itrace_synth_opts - AUX area tracing synthesis options.
 * @set: indicates whether or not options have been set
 * @inject: indicates the event (not just the sample) must be fully synthesized
 *          because 'perf inject' will write it out
 * @instructions: whether to synthesize 'instructions' events
 * @branches: whether to synthesize 'branches' events
 * @transactions: whether to synthesize events for transactions
 * @errors: whether to synthesize decoder error events
 * @dont_decode: whether to skip decoding entirely
 * @log: write a decoding log
 * @calls: limit branch samples to calls (can be combined with @returns)
 * @returns: limit branch samples to returns (can be combined with @calls)
 * @callchain: add callchain to 'instructions' events
 * @callchain_sz: maximum callchain size
 * @period: 'instructions' events period
 * @period_type: 'instructions' events period type
 */
struct itrace_synth_opts {
	bool			set;
	bool			inject;
	bool			instructions;
	bool			branches;
	bool			transactions;
	bool			errors;
	bool			dont_decode;
	bool			log;
	bool			calls;
	bool			returns;
	bool			callchain;
	unsigned int		callchain_sz;
	unsigned long long	period;
	enum itrace_period_type	period_type;
};

/**
 * struct auxtrace_index_entry - indexes a AUX area tracing event within a
 *                               perf.data file.
 * @file_offset: offset within the perf.data file
 * @sz: size of the event
 */
struct auxtrace_index_entry {
	u64			file_offset;
	u64			sz;
};

#define PERF_AUXTRACE_INDEX_ENTRY_COUNT 256

/**
 * struct auxtrace_index - index of AUX area tracing events within a perf.data
 *                         file.
 * @list: linking a number of arrays of entries
 * @nr: number of entries
 * @entries: array of entries
 */
struct auxtrace_index {
	struct list_head	list;
	size_t			nr;
	struct auxtrace_index_entry entries[PERF_AUXTRACE_INDEX_ENTRY_COUNT];
};

/**
 * struct auxtrace - session callbacks to allow AUX area data decoding.
 * @process_event: lets the decoder see all session events
 * @flush_events: process any remaining data
 * @free_events: free resources associated with event processing
 * @free: free resources associated with the session
 */
struct auxtrace {
	int (*process_event)(struct perf_session *session,
			     union perf_event *event,
			     struct perf_sample *sample,
			     struct perf_tool *tool);
	int (*process_auxtrace_event)(struct perf_session *session,
				      union perf_event *event,
				      struct perf_tool *tool);
	int (*flush_events)(struct perf_session *session,
			    struct perf_tool *tool);
	void (*free_events)(struct perf_session *session);
	void (*free)(struct perf_session *session);
};

/**
 * struct auxtrace_buffer - a buffer containing AUX area tracing data.
 * @list: buffers are queued in a list held by struct auxtrace_queue
 * @size: size of the buffer in bytes
 * @pid: in per-thread mode, the pid this buffer is associated with
 * @tid: in per-thread mode, the tid this buffer is associated with
 * @cpu: in per-cpu mode, the cpu this buffer is associated with
 * @data: actual buffer data (can be null if the data has not been loaded)
 * @data_offset: file offset at which the buffer can be read
 * @mmap_addr: mmap address at which the buffer can be read
 * @mmap_size: size of the mmap at @mmap_addr
 * @data_needs_freeing: @data was malloc'd so free it when it is no longer
 *                      needed
 * @consecutive: the original data was split up and this buffer is consecutive
 *               to the previous buffer
 * @offset: offset as determined by aux_head / aux_tail members of struct
 *          perf_event_mmap_page
 * @reference: an implementation-specific reference determined when the data is
 *             recorded
 * @buffer_nr: used to number each buffer
 * @use_size: implementation actually only uses this number of bytes
 * @use_data: implementation actually only uses data starting at this address
 */
struct auxtrace_buffer {
	struct list_head	list;
	size_t			size;
	pid_t			pid;
	pid_t			tid;
	int			cpu;
	void			*data;
	off_t			data_offset;
	void			*mmap_addr;
	size_t			mmap_size;
	bool			data_needs_freeing;
	bool			consecutive;
	u64			offset;
	u64			reference;
	u64			buffer_nr;
	size_t			use_size;
	void			*use_data;
};

/**
 * struct auxtrace_queue - a queue of AUX area tracing data buffers.
 * @head: head of buffer list
 * @tid: in per-thread mode, the tid this queue is associated with
 * @cpu: in per-cpu mode, the cpu this queue is associated with
 * @set: %true once this queue has been dedicated to a specific thread or cpu
 * @priv: implementation-specific data
 */
struct auxtrace_queue {
	struct list_head	head;
	pid_t			tid;
	int			cpu;
	bool			set;
	void			*priv;
};

/**
 * struct auxtrace_queues - an array of AUX area tracing queues.
 * @queue_array: array of queues
 * @nr_queues: number of queues
 * @new_data: set whenever new data is queued
 * @populated: queues have been fully populated using the auxtrace_index
 * @next_buffer_nr: used to number each buffer
 */
struct auxtrace_queues {
	struct auxtrace_queue	*queue_array;
	unsigned int		nr_queues;
	bool			new_data;
	bool			populated;
	u64			next_buffer_nr;
};

/**
 * struct auxtrace_heap_item - element of struct auxtrace_heap.
 * @queue_nr: queue number
 * @ordinal: value used for sorting (lowest ordinal is top of the heap) expected
 *           to be a timestamp
 */
struct auxtrace_heap_item {
	unsigned int		queue_nr;
	u64			ordinal;
};

/**
 * struct auxtrace_heap - a heap suitable for sorting AUX area tracing queues.
 * @heap_array: the heap
 * @heap_cnt: the number of elements in the heap
 * @heap_sz: maximum number of elements (grows as needed)
 */
struct auxtrace_heap {
	struct auxtrace_heap_item	*heap_array;
	unsigned int		heap_cnt;
	unsigned int		heap_sz;
};

/**
 * struct auxtrace_mmap - records an mmap of the auxtrace buffer.
 * @base: address of mapped area
 * @userpg: pointer to buffer's perf_event_mmap_page
 * @mask: %0 if @len is not a power of two, otherwise (@len - %1)
 * @len: size of mapped area
 * @prev: previous aux_head
 * @idx: index of this mmap
 * @tid: tid for a per-thread mmap (also set if there is only 1 tid on a per-cpu
 *       mmap) otherwise %0
 * @cpu: cpu number for a per-cpu mmap otherwise %-1
 */
struct auxtrace_mmap {
	void		*base;
	void		*userpg;
	size_t		mask;
	size_t		len;
	u64		prev;
	int		idx;
	pid_t		tid;
	int		cpu;
};

/**
 * struct auxtrace_mmap_params - parameters to set up struct auxtrace_mmap.
 * @mask: %0 if @len is not a power of two, otherwise (@len - %1)
 * @offset: file offset of mapped area
 * @len: size of mapped area
 * @prot: mmap memory protection
 * @idx: index of this mmap
 * @tid: tid for a per-thread mmap (also set if there is only 1 tid on a per-cpu
 *       mmap) otherwise %0
 * @cpu: cpu number for a per-cpu mmap otherwise %-1
 */
struct auxtrace_mmap_params {
	size_t		mask;
	off_t		offset;
	size_t		len;
	int		prot;
	int		idx;
	pid_t		tid;
	int		cpu;
};

/**
 * struct auxtrace_record - callbacks for recording AUX area data.
 * @recording_options: validate and process recording options
 * @info_priv_size: return the size of the private data in auxtrace_info_event
 * @info_fill: fill-in the private data in auxtrace_info_event
 * @free: free this auxtrace record structure
 * @snapshot_start: starting a snapshot
 * @snapshot_finish: finishing a snapshot
 * @find_snapshot: find data to snapshot within auxtrace mmap
 * @parse_snapshot_options: parse snapshot options
 * @reference: provide a 64-bit reference number for auxtrace_event
 * @read_finish: called after reading from an auxtrace mmap
 */
struct auxtrace_record {
	int (*recording_options)(struct auxtrace_record *itr,
				 struct perf_evlist *evlist,
				 struct record_opts *opts);
	size_t (*info_priv_size)(struct auxtrace_record *itr);
	int (*info_fill)(struct auxtrace_record *itr,
			 struct perf_session *session,
			 struct auxtrace_info_event *auxtrace_info,
			 size_t priv_size);
	void (*free)(struct auxtrace_record *itr);
	int (*snapshot_start)(struct auxtrace_record *itr);
	int (*snapshot_finish)(struct auxtrace_record *itr);
	int (*find_snapshot)(struct auxtrace_record *itr, int idx,
			     struct auxtrace_mmap *mm, unsigned char *data,
			     u64 *head, u64 *old);
	int (*parse_snapshot_options)(struct auxtrace_record *itr,
				      struct record_opts *opts,
				      const char *str);
	u64 (*reference)(struct auxtrace_record *itr);
	int (*read_finish)(struct auxtrace_record *itr, int idx);
	unsigned int alignment;
};

#ifdef HAVE_AUXTRACE_SUPPORT

/*
 * In snapshot mode the mmapped page is read-only which makes using
 * __sync_val_compare_and_swap() problematic.  However, snapshot mode expects
 * the buffer is not updated while the snapshot is made (e.g. Intel PT disables
 * the event) so there is not a race anyway.
 */
static inline u64 auxtrace_mmap__read_snapshot_head(struct auxtrace_mmap *mm)
{
	struct perf_event_mmap_page *pc = mm->userpg;
	u64 head = ACCESS_ONCE(pc->aux_head);

	/* Ensure all reads are done after we read the head */
	rmb();
	return head;
}

static inline u64 auxtrace_mmap__read_head(struct auxtrace_mmap *mm)
{
	struct perf_event_mmap_page *pc = mm->userpg;
#if BITS_PER_LONG == 64 || !defined(HAVE_SYNC_COMPARE_AND_SWAP_SUPPORT)
	u64 head = ACCESS_ONCE(pc->aux_head);
#else
	u64 head = __sync_val_compare_and_swap(&pc->aux_head, 0, 0);
#endif

	/* Ensure all reads are done after we read the head */
	rmb();
	return head;
}

static inline void auxtrace_mmap__write_tail(struct auxtrace_mmap *mm, u64 tail)
{
	struct perf_event_mmap_page *pc = mm->userpg;
#if BITS_PER_LONG != 64 && defined(HAVE_SYNC_COMPARE_AND_SWAP_SUPPORT)
	u64 old_tail;
#endif

	/* Ensure all reads are done before we write the tail out */
	mb();
#if BITS_PER_LONG == 64 || !defined(HAVE_SYNC_COMPARE_AND_SWAP_SUPPORT)
	pc->aux_tail = tail;
#else
	do {
		old_tail = __sync_val_compare_and_swap(&pc->aux_tail, 0, 0);
	} while (!__sync_bool_compare_and_swap(&pc->aux_tail, old_tail, tail));
#endif
}

int auxtrace_mmap__mmap(struct auxtrace_mmap *mm,
			struct auxtrace_mmap_params *mp,
			void *userpg, int fd);
void auxtrace_mmap__munmap(struct auxtrace_mmap *mm);
void auxtrace_mmap_params__init(struct auxtrace_mmap_params *mp,
				off_t auxtrace_offset,
				unsigned int auxtrace_pages,
				bool auxtrace_overwrite);
void auxtrace_mmap_params__set_idx(struct auxtrace_mmap_params *mp,
				   struct perf_evlist *evlist, int idx,
				   bool per_cpu);

typedef int (*process_auxtrace_t)(struct perf_tool *tool,
				  union perf_event *event, void *data1,
				  size_t len1, void *data2, size_t len2);

int auxtrace_mmap__read(struct auxtrace_mmap *mm, struct auxtrace_record *itr,
			struct perf_tool *tool, process_auxtrace_t fn);

int auxtrace_mmap__read_snapshot(struct auxtrace_mmap *mm,
				 struct auxtrace_record *itr,
				 struct perf_tool *tool, process_auxtrace_t fn,
				 size_t snapshot_size);

int auxtrace_queues__init(struct auxtrace_queues *queues);
int auxtrace_queues__add_event(struct auxtrace_queues *queues,
			       struct perf_session *session,
			       union perf_event *event, off_t data_offset,
			       struct auxtrace_buffer **buffer_ptr);
void auxtrace_queues__free(struct auxtrace_queues *queues);
int auxtrace_queues__process_index(struct auxtrace_queues *queues,
				   struct perf_session *session);
struct auxtrace_buffer *auxtrace_buffer__next(struct auxtrace_queue *queue,
					      struct auxtrace_buffer *buffer);
void *auxtrace_buffer__get_data(struct auxtrace_buffer *buffer, int fd);
void auxtrace_buffer__put_data(struct auxtrace_buffer *buffer);
void auxtrace_buffer__drop_data(struct auxtrace_buffer *buffer);
void auxtrace_buffer__free(struct auxtrace_buffer *buffer);

int auxtrace_heap__add(struct auxtrace_heap *heap, unsigned int queue_nr,
		       u64 ordinal);
void auxtrace_heap__pop(struct auxtrace_heap *heap);
void auxtrace_heap__free(struct auxtrace_heap *heap);

struct auxtrace_cache_entry {
	struct hlist_node hash;
	u32 key;
};

struct auxtrace_cache *auxtrace_cache__new(unsigned int bits, size_t entry_size,
					   unsigned int limit_percent);
void auxtrace_cache__free(struct auxtrace_cache *auxtrace_cache);
void *auxtrace_cache__alloc_entry(struct auxtrace_cache *c);
void auxtrace_cache__free_entry(struct auxtrace_cache *c, void *entry);
int auxtrace_cache__add(struct auxtrace_cache *c, u32 key,
			struct auxtrace_cache_entry *entry);
void *auxtrace_cache__lookup(struct auxtrace_cache *c, u32 key);

struct auxtrace_record *auxtrace_record__init(struct perf_evlist *evlist,
					      int *err);

int auxtrace_parse_snapshot_options(struct auxtrace_record *itr,
				    struct record_opts *opts,
				    const char *str);
int auxtrace_record__options(struct auxtrace_record *itr,
			     struct perf_evlist *evlist,
			     struct record_opts *opts);
size_t auxtrace_record__info_priv_size(struct auxtrace_record *itr);
int auxtrace_record__info_fill(struct auxtrace_record *itr,
			       struct perf_session *session,
			       struct auxtrace_info_event *auxtrace_info,
			       size_t priv_size);
void auxtrace_record__free(struct auxtrace_record *itr);
int auxtrace_record__snapshot_start(struct auxtrace_record *itr);
int auxtrace_record__snapshot_finish(struct auxtrace_record *itr);
int auxtrace_record__find_snapshot(struct auxtrace_record *itr, int idx,
				   struct auxtrace_mmap *mm,
				   unsigned char *data, u64 *head, u64 *old);
u64 auxtrace_record__reference(struct auxtrace_record *itr);

int auxtrace_index__auxtrace_event(struct list_head *head, union perf_event *event,
				   off_t file_offset);
int auxtrace_index__write(int fd, struct list_head *head);
int auxtrace_index__process(int fd, u64 size, struct perf_session *session,
			    bool needs_swap);
void auxtrace_index__free(struct list_head *head);

void auxtrace_synth_error(struct auxtrace_error_event *auxtrace_error, int type,
			  int code, int cpu, pid_t pid, pid_t tid, u64 ip,
			  const char *msg);

int perf_event__synthesize_auxtrace_info(struct auxtrace_record *itr,
					 struct perf_tool *tool,
					 struct perf_session *session,
					 perf_event__handler_t process);
int perf_event__process_auxtrace_info(struct perf_tool *tool,
				      union perf_event *event,
				      struct perf_session *session);
s64 perf_event__process_auxtrace(struct perf_tool *tool,
				 union perf_event *event,
				 struct perf_session *session);
int perf_event__process_auxtrace_error(struct perf_tool *tool,
				       union perf_event *event,
				       struct perf_session *session);
int itrace_parse_synth_opts(const struct option *opt, const char *str,
			    int unset);
void itrace_synth_opts__set_default(struct itrace_synth_opts *synth_opts);

size_t perf_event__fprintf_auxtrace_error(union perf_event *event, FILE *fp);
void perf_session__auxtrace_error_inc(struct perf_session *session,
				      union perf_event *event);
void events_stats__auxtrace_error_warn(const struct events_stats *stats);

static inline int auxtrace__process_event(struct perf_session *session,
					  union perf_event *event,
					  struct perf_sample *sample,
					  struct perf_tool *tool)
{
	if (!session->auxtrace)
		return 0;

	return session->auxtrace->process_event(session, event, sample, tool);
}

static inline int auxtrace__flush_events(struct perf_session *session,
					 struct perf_tool *tool)
{
	if (!session->auxtrace)
		return 0;

	return session->auxtrace->flush_events(session, tool);
}

static inline void auxtrace__free_events(struct perf_session *session)
{
	if (!session->auxtrace)
		return;

	return session->auxtrace->free_events(session);
}

static inline void auxtrace__free(struct perf_session *session)
{
	if (!session->auxtrace)
		return;

	return session->auxtrace->free(session);
}

#else

static inline struct auxtrace_record *
auxtrace_record__init(struct perf_evlist *evlist __maybe_unused,
		      int *err __maybe_unused)
{
	*err = 0;
	return NULL;
}

static inline
void auxtrace_record__free(struct auxtrace_record *itr __maybe_unused)
{
}

static inline int
perf_event__synthesize_auxtrace_info(struct auxtrace_record *itr __maybe_unused,
				     struct perf_tool *tool __maybe_unused,
				     struct perf_session *session __maybe_unused,
				     perf_event__handler_t process __maybe_unused)
{
	return -EINVAL;
}

static inline
int auxtrace_record__options(struct auxtrace_record *itr __maybe_unused,
			     struct perf_evlist *evlist __maybe_unused,
			     struct record_opts *opts __maybe_unused)
{
	return 0;
}

#define perf_event__process_auxtrace_info		0
#define perf_event__process_auxtrace			0
#define perf_event__process_auxtrace_error		0

static inline
void perf_session__auxtrace_error_inc(struct perf_session *session
				      __maybe_unused,
				      union perf_event *event
				      __maybe_unused)
{
}

static inline
void events_stats__auxtrace_error_warn(const struct events_stats *stats
				       __maybe_unused)
{
}

static inline
int itrace_parse_synth_opts(const struct option *opt __maybe_unused,
			    const char *str __maybe_unused,
			    int unset __maybe_unused)
{
	pr_err("AUX area tracing not supported\n");
	return -EINVAL;
}

static inline
int auxtrace_parse_snapshot_options(struct auxtrace_record *itr __maybe_unused,
				    struct record_opts *opts __maybe_unused,
				    const char *str)
{
	if (!str)
		return 0;
	pr_err("AUX area tracing not supported\n");
	return -EINVAL;
}

static inline
int auxtrace__process_event(struct perf_session *session __maybe_unused,
			    union perf_event *event __maybe_unused,
			    struct perf_sample *sample __maybe_unused,
			    struct perf_tool *tool __maybe_unused)
{
	return 0;
}

static inline
int auxtrace__flush_events(struct perf_session *session __maybe_unused,
			   struct perf_tool *tool __maybe_unused)
{
	return 0;
}

static inline
void auxtrace__free_events(struct perf_session *session __maybe_unused)
{
}

static inline
void auxtrace_cache__free(struct auxtrace_cache *auxtrace_cache __maybe_unused)
{
}

static inline
void auxtrace__free(struct perf_session *session __maybe_unused)
{
}

static inline
int auxtrace_index__write(int fd __maybe_unused,
			  struct list_head *head __maybe_unused)
{
	return -EINVAL;
}

static inline
int auxtrace_index__process(int fd __maybe_unused,
			    u64 size __maybe_unused,
			    struct perf_session *session __maybe_unused,
			    bool needs_swap __maybe_unused)
{
	return -EINVAL;
}

static inline
void auxtrace_index__free(struct list_head *head __maybe_unused)
{
}

int auxtrace_mmap__mmap(struct auxtrace_mmap *mm,
			struct auxtrace_mmap_params *mp,
			void *userpg, int fd);
void auxtrace_mmap__munmap(struct auxtrace_mmap *mm);
void auxtrace_mmap_params__init(struct auxtrace_mmap_params *mp,
				off_t auxtrace_offset,
				unsigned int auxtrace_pages,
				bool auxtrace_overwrite);
void auxtrace_mmap_params__set_idx(struct auxtrace_mmap_params *mp,
				   struct perf_evlist *evlist, int idx,
				   bool per_cpu);

#endif

#endif


text:
<?php

namespace models;

use CodingBeard\Blameable;
use Phalcon\Mvc\Model;

class Navbars extends Model
{

    /**
     *
     * @var integer
     */
    public $id;

    /**
     *
     * @var string
     */
    public $name;

    /**
     * Initialize method for model.
     */
    public function initialize()
    {
        $this->keepSnapshots(true);
        $this->addBehavior(new Blameable());
        $this->useDynamicUpdate(true);
        $this->hasMany('id', 'models\Navlinks', 'navbar_id', ['alias' => 'Navlinks']);
    }

    /**
     * Independent Column Mapping.
     */
    public function columnMap()
    {
        return [
            'id' => 'id',
            'name' => 'name'
        ];
    }

}


text:
/*
This css is safe to use when the video is included on other replay pages like group flight replay
*/

.sourceLabel {
	margin-right: 3px;
}

.video-head {
	margin-top: -5px;
}

.player_container {
	height: 100%;
	width: 100%;
}

#player_container {
	margin-left:-10px;
	margin-right:-10px;
}

.player {
	height: 100%;
	width: 100%;
	min-height: 200px;
}

.frame-grab-button {
	margin-right: 4px;
}

.audioIcon {
	margin-top: 2px;
	color:black !important;
}

.audioSlider {
    width: 100px;
    height: 8px;
	margin-left:4px;
	margin-right: 4px;
	margin-top: 3px;
	margin-bottom: 3px;
	background: white !important;
}

.audioSlider .ui-slider {
    border-radius: 2px;
}

.audioSlider .ui-slider-handle {
    border-radius: 4px;
    width: 0.4em;
    margin-left: -0.2em;
    background: black;
    color: black;
    border-color: black;
}


text:
class Admin::Images2Controller < ApplicationController
  layout 'admin'

  admin_assistant_for Image do |a|
    a.actions :create, :index

    a.index do |index|
      index.columns :image, :path, :created_at
    end
  end
end


text:
//---------------------------------------------------------------------
// <copyright file="TypeSystem.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.OData.Client
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Reflection;
    using Microsoft.OData.Edm.Library;
    using Microsoft.Spatial;

    /// Utility functions for processing Expression trees
    internal static class TypeSystem
    {
        /// Used for comparison with external assemblies for silverlight like Microsoft.VisualBasic.
        private const string OfficialSilverLightPublicKeyToken = "31bf3856ad364e35";

        /// Used for comparison with external assemblies for desktop like Microsoft.VisualBasic.
        private const string OfficialDesktopPublicKeyToken = "b03f5f7f11d50a3a";

        ///  Method map for methods in URI query options
        private static readonly Dictionary<MethodInfo, string> expressionMethodMap;

        ///  VB Method map for methods in URI query options
        private static readonly Dictionary<string, string> expressionVBMethodMap;

        ///  Properties that should be represented as methods
        private static readonly Dictionary<PropertyInfo, MethodInfo> propertiesAsMethodsMap;

        ///
        /// Cache used to store element type (TElement) for key Type if key Type implements IEnumerable{TElement} or
        /// null if the key Type does not implement IEnumerable{T} e.g.:
        /// List{Entity} - Entity
        /// Entity       - null
        ///
        private static readonly Dictionary<Type, Type> ienumerableElementTypeCache = new Dictionary<Type, Type>(EqualityComparer<Type>.Default);

        ///  VB Assembly name
        private const string VisualBasicAssemblyName = "Microsoft.VisualBasic,";

        ///  VB Assembly public key token
#pragma warning disable 436
        private const string VisualBasicAssemblyPublicKeyToken = "PublicKeyToken=" + OfficialDesktopPublicKeyToken;
#pragma warning restore 436
        ///
        /// Initializes method map
        ///
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Cleaner code")]
        static TypeSystem()
        {
#if !PORTABLELIB
            const int ExpectedCount = 35;
#endif
            // string functions
            expressionMethodMap = new Dictionary<MethodInfo, string>(EqualityComparer<MethodInfo>.Default);
            expressionMethodMap.Add(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }), @"contains");
            expressionMethodMap.Add(typeof(string).GetMethod("EndsWith", new Type[] { typeof(string) }), @"endswith");
            expressionMethodMap.Add(typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) }), @"startswith");
            expressionMethodMap.Add(typeof(string).GetMethod("IndexOf", new Type[] { typeof(string) }), @"indexof");
            expressionMethodMap.Add(typeof(string).GetMethod("Replace", new Type[] { typeof(string), typeof(string) }), @"replace");
            expressionMethodMap.Add(typeof(string).GetMethod("Substring", new Type[] { typeof(int) }), @"substring");
            expressionMethodMap.Add(typeof(string).GetMethod("Substring", new Type[] { typeof(int), typeof(int) }), @"substring");
            expressionMethodMap.Add(typeof(string).GetMethod("ToLower", PlatformHelper.EmptyTypes), @"tolower");
            expressionMethodMap.Add(typeof(string).GetMethod("ToUpper", PlatformHelper.EmptyTypes), @"toupper");
            expressionMethodMap.Add(typeof(string).GetMethod("Trim", PlatformHelper.EmptyTypes), @"trim");
            expressionMethodMap.Add(typeof(string).GetMethod("Concat", new Type[] { typeof(string), typeof(string) }), @"concat");
            expressionMethodMap.Add(typeof(string).GetProperty("Length", typeof(int)).GetGetMethod(), @"length");

            // date methods
            expressionMethodMap.Add(typeof(Date).GetProperty("Day", typeof(int)).GetGetMethod(), @"day");
            expressionMethodMap.Add(typeof(Date).GetProperty("Month", typeof(int)).GetGetMethod(), @"month");
            expressionMethodMap.Add(typeof(Date).GetProperty("Year", typeof(int)).GetGetMethod(), @"year");

            // timeOfDay methods
            expressionMethodMap.Add(typeof(TimeOfDay).GetProperty("Hours", typeof(int)).GetGetMethod(), @"hour");
            expressionMethodMap.Add(typeof(TimeOfDay).GetProperty("Minutes", typeof(int)).GetGetMethod(), @"minute");
            expressionMethodMap.Add(typeof(TimeOfDay).GetProperty("Seconds", typeof(int)).GetGetMethod(), @"second");

            // datetimeoffset methods (date? time?)
            expressionMethodMap.Add(typeof(DateTimeOffset).GetProperty("Day", typeof(int)).GetGetMethod(), @"day");
            expressionMethodMap.Add(typeof(DateTimeOffset).GetProperty("Hour", typeof(int)).GetGetMethod(), @"hour");
            expressionMethodMap.Add(typeof(DateTimeOffset).GetProperty("Month", typeof(int)).GetGetMethod(), @"month");
            expressionMethodMap.Add(typeof(DateTimeOffset).GetProperty("Minute", typeof(int)).GetGetMethod(), @"minute");
            expressionMethodMap.Add(typeof(DateTimeOffset).GetProperty("Second", typeof(int)).GetGetMethod(), @"second");
            expressionMethodMap.Add(typeof(DateTimeOffset).GetProperty("Year", typeof(int)).GetGetMethod(), @"year");

            // timespan methods
            expressionMethodMap.Add(typeof(TimeSpan).GetProperty("Hours", typeof(int)).GetGetMethod(), @"hour");
            expressionMethodMap.Add(typeof(TimeSpan).GetProperty("Minutes", typeof(int)).GetGetMethod(), @"minute");
            expressionMethodMap.Add(typeof(TimeSpan).GetProperty("Seconds", typeof(int)).GetGetMethod(), @"second");

            // math methods
            expressionMethodMap.Add(typeof(Math).GetMethod("Round", new Type[] { typeof(double) }), @"round");
            expressionMethodMap.Add(typeof(Math).GetMethod("Round", new Type[] { typeof(decimal) }), @"round");
            expressionMethodMap.Add(typeof(Math).GetMethod("Floor", new Type[] { typeof(double) }), @"floor");

            MethodInfo foundMethod = null;
            if (typeof(Math).TryGetMethod("Floor", new Type[] { typeof(decimal) }, out foundMethod))
            {
                expressionMethodMap.Add(foundMethod, @"floor");
            }

            expressionMethodMap.Add(typeof(Math).GetMethod("Ceiling", new Type[] { typeof(double) }), @"ceiling");

            if (typeof(Math).TryGetMethod("Ceiling", new Type[] { typeof(decimal) }, out foundMethod))
            {
                expressionMethodMap.Add(foundMethod, @"ceiling");
            }

            // Spatial methods
            expressionMethodMap.Add(typeof(GeographyOperationsExtensions).GetMethod("Distance", new Type[] { typeof(GeographyPoint), typeof(GeographyPoint) }, true /*isPublic*/, true /*isStatic*/), @"geo.distance");
            expressionMethodMap.Add(typeof(GeometryOperationsExtensions).GetMethod("Distance", new Type[] { typeof(GeometryPoint), typeof(GeometryPoint) }, true /*isPublic*/, true /*isStatic*/), @"geo.distance");

            // Portable Lib can be 35 or 33 depending on if its running on Silverlight or not, disabling in this case
#if !PORTABLELIB
            Debug.Assert(expressionMethodMap.Count == ExpectedCount, "expressionMethodMap.Count == ExpectedCount");
#endif
            // vb methods
            // lookup these by type name + method name
            expressionVBMethodMap = new Dictionary<string, string>(StringComparer.Ordinal);

            expressionVBMethodMap.Add("Microsoft.VisualBasic.Strings.Trim", @"trim");
            expressionVBMethodMap.Add("Microsoft.VisualBasic.Strings.Len", @"length");
            expressionVBMethodMap.Add("Microsoft.VisualBasic.Strings.Mid", @"substring");
            expressionVBMethodMap.Add("Microsoft.VisualBasic.Strings.UCase", @"toupper");
            expressionVBMethodMap.Add("Microsoft.VisualBasic.Strings.LCase", @"tolower");
            expressionVBMethodMap.Add("Microsoft.VisualBasic.DateAndTime.Year", @"year");
            expressionVBMethodMap.Add("Microsoft.VisualBasic.DateAndTime.Month", @"month");
            expressionVBMethodMap.Add("Microsoft.VisualBasic.DateAndTime.Day", @"day");
            expressionVBMethodMap.Add("Microsoft.VisualBasic.DateAndTime.Hour", @"hour");
            expressionVBMethodMap.Add("Microsoft.VisualBasic.DateAndTime.Minute", @"minute");
            expressionVBMethodMap.Add("Microsoft.VisualBasic.DateAndTime.Second", @"second");

            Debug.Assert(expressionVBMethodMap.Count == 11, "expressionVBMethodMap.Count == 11");

            propertiesAsMethodsMap = new Dictionary<PropertyInfo, MethodInfo>(EqualityComparer<PropertyInfo>.Default);
            propertiesAsMethodsMap.Add(
                typeof(string).GetProperty("Length", typeof(int)),
                typeof(string).GetProperty("Length", typeof(int)).GetGetMethod());
            propertiesAsMethodsMap.Add(
                typeof(DateTimeOffset).GetProperty("Day", typeof(int)),
                typeof(DateTimeOffset).GetProperty("Day", typeof(int)).GetGetMethod());
            propertiesAsMethodsMap.Add(
                typeof(DateTimeOffset).GetProperty("Hour", typeof(int)),
                typeof(DateTimeOffset).GetProperty("Hour", typeof(int)).GetGetMethod());
            propertiesAsMethodsMap.Add(
                typeof(DateTimeOffset).GetProperty("Minute", typeof(int)),
                typeof(DateTimeOffset).GetProperty("Minute", typeof(int)).GetGetMethod());
            propertiesAsMethodsMap.Add(
                typeof(DateTimeOffset).GetProperty("Second", typeof(int)),
                typeof(DateTimeOffset).GetProperty("Second", typeof(int)).GetGetMethod());
            propertiesAsMethodsMap.Add(
                typeof(DateTimeOffset).GetProperty("Month", typeof(int)),
                typeof(DateTimeOffset).GetProperty("Month", typeof(int)).GetGetMethod());
            propertiesAsMethodsMap.Add(
                typeof(DateTimeOffset).GetProperty("Year", typeof(int)),
                typeof(DateTimeOffset).GetProperty("Year", typeof(int)).GetGetMethod());
            propertiesAsMethodsMap.Add(
                typeof(TimeSpan).GetProperty("Hours", typeof(int)),
                typeof(TimeSpan).GetProperty("Hours", typeof(int)).GetGetMethod());
            propertiesAsMethodsMap.Add(
                typeof(TimeSpan).GetProperty("Minutes", typeof(int)),
                typeof(TimeSpan).GetProperty("Minutes", typeof(int)).GetGetMethod());
            propertiesAsMethodsMap.Add(
                typeof(TimeSpan).GetProperty("Seconds", typeof(int)),
                typeof(TimeSpan).GetProperty("Seconds", typeof(int)).GetGetMethod());

            propertiesAsMethodsMap.Add(
                typeof(TimeOfDay).GetProperty("Hours", typeof(int)),
                typeof(TimeOfDay).GetProperty("Hours", typeof(int)).GetGetMethod());
            propertiesAsMethodsMap.Add(
                typeof(TimeOfDay).GetProperty("Minutes", typeof(int)),
                typeof(TimeOfDay).GetProperty("Minutes", typeof(int)).GetGetMethod());
            propertiesAsMethodsMap.Add(
                typeof(TimeOfDay).GetProperty("Seconds", typeof(int)),
                typeof(TimeOfDay).GetProperty("Seconds", typeof(int)).GetGetMethod());

            propertiesAsMethodsMap.Add(
                typeof(Date).GetProperty("Year", typeof(int)),
                typeof(Date).GetProperty("Year", typeof(int)).GetGetMethod());
            propertiesAsMethodsMap.Add(
                typeof(Date).GetProperty("Month", typeof(int)),
                typeof(Date).GetProperty("Month", typeof(int)).GetGetMethod());
            propertiesAsMethodsMap.Add(
                typeof(Date).GetProperty("Day", typeof(int)),
                typeof(Date).GetProperty("Day", typeof(int)).GetGetMethod());

            Debug.Assert(propertiesAsMethodsMap.Count == 16, "propertiesAsMethodsMap.Count == 16");
        }

        ///
        /// Sees if method has URI equivalent
        ///
        /// <param name="mi">The method info</param>
        /// <param name="methodName">uri method name</param>
        /// <returns>true/ false</returns>
        internal static bool TryGetQueryOptionMethod(MethodInfo mi, out string methodName)
        {
            return (expressionMethodMap.TryGetValue(mi, out methodName) ||
                (IsVisualBasicAssembly(mi.DeclaringType.GetAssembly()) &&
                 expressionVBMethodMap.TryGetValue(mi.DeclaringType.FullName + "." + mi.Name, out methodName)));
        }

        ///
        /// Sees if property can be represented as method for translation to URI
        ///
        /// <param name="pi">The property info</param>
        /// <param name="mi">get method for property</param>
        /// <returns>true/ false</returns>
        internal static bool TryGetPropertyAsMethod(PropertyInfo pi, out MethodInfo mi)
        {
            return propertiesAsMethodsMap.TryGetValue(pi, out mi);
        }

        ///
        /// Gets the elementtype for a sequence
        ///
        /// <param name="seqType">The sequence type</param>
        /// <returns>The element type</returns>
        internal static Type GetElementType(Type seqType)
        {
            Type ienum = FindIEnumerable(seqType);
            if (ienum == null)
            {
                return seqType;
            }

            return ienum.GetGenericArguments()[0];
        }

        ///
        /// Determines whether a property is private
        ///
        /// <param name="pi">The PropertyInfo structure for the property</param>
        /// <returns>true/ false if property is private</returns>
        internal static bool IsPrivate(PropertyInfo pi)
        {
            MethodInfo mi = pi.GetGetMethod() ?? pi.GetSetMethod();
            if (mi != null)
            {
                return mi.IsPrivate;
            }

            return true;
        }

        ///
        /// Finds type that implements IEnumerable so can get element type
        ///
        /// <param name="seqType">The Type to check</param>
        /// <returns>returns the type which implements IEnumerable</returns>
        internal static Type FindIEnumerable(Type seqType)
        {
            // shortcircuit types that never implement IEnumerable (including value types as the only value types recognized by the client
            // are primitive types like decimal, GUID or DateTimeOffset)
            if (seqType == null || seqType == typeof(string) || seqType.IsPrimitive() || seqType.IsValueType() || Nullable.GetUnderlyingType(seqType) != null)
            {
                return null;
            }

            Type resultType;
            lock (ienumerableElementTypeCache)
            {
                if (!ienumerableElementTypeCache.TryGetValue(seqType, out resultType))
                {
                    resultType = FindIEnumerableForNonPrimitiveType(seqType);
                    ienumerableElementTypeCache.Add(seqType, resultType);
                }
            }

            return resultType;
        }

        /// Finds whether a non-primitive implements IEnumerable and returns element type if it does.
        /// <param name="seqType">Type to check.</param>
        /// <returns>Type of the element if the <paramref name="seqType"/> implements IEnumerable{T}. Otherwise null.</returns>
        private static Type FindIEnumerableForNonPrimitiveType(Type seqType)
        {
            Debug.Assert(seqType != null, "seqType != null");
            Debug.Assert(seqType != typeof(string) && !seqType.IsPrimitive() && !seqType.IsValueType() && Nullable.GetUnderlyingType(seqType) == null, "seqType must not be a primitive type (nullable or not)");

            if (seqType.IsArray)
            {
                return typeof(IEnumerable<>).MakeGenericType(seqType.GetElementType());
            }

            if (seqType.IsGenericType())
            {
                foreach (Type arg in seqType.GetGenericArguments())
                {
                    Type ienum = typeof(IEnumerable<>).MakeGenericType(arg);
                    if (ienum.IsAssignableFrom(seqType))
                    {
                        return ienum;
                    }
                }
            }

            IEnumerable<Type> ifaces = seqType.GetInterfaces();
            if (ifaces != null)
            {
                foreach (Type iface in ifaces)
                {
                    Type ienum = FindIEnumerable(iface);
                    if (ienum != null)
                    {
                        return ienum;
                    }
                }
            }

            if (seqType.GetBaseType() != null && seqType.GetBaseType() != typeof(object))
            {
                return FindIEnumerable(seqType.GetBaseType());
            }

            return null;
        }

        ///
        /// Checks if the given assembly is the VisualBasic assembly.
        ///
        /// <param name="assembly">assembly to check.</param>
        /// <returns>true if the assembly is Microsoft.VisualBasic, otherwise returns false.root
        /// </returns>
        private static bool IsVisualBasicAssembly(Assembly assembly)
        {
            string assemblyFullName = assembly.FullName;
            if (assemblyFullName.Contains(VisualBasicAssemblyName) && assembly.FullName.Contains(VisualBasicAssemblyPublicKeyToken))
            {
                return true;
            }

            return false;
        }
    }
}


text:
/*
Inspired by

https://leetcode.com/problems/implement-magic-dictionary/discuss/107454/Python-without-*26-factor-in-complexity

A word 'apple' has neighbors '*pple', 'a*ple', 'ap*le', 'app*e', 'appl*'. When
searching for a target word like 'apply', we know that a necessary condition is
a neighbor of 'apply' is a neighbor of some source word in our magic dictionary.
If there is more than one source word that does this, then at least one of those
source words will be different from the target word. Otherwise, we need to check
that the source doesn't equal the target.
*/
package main

import "fmt"

type MagicDictionary struct {
	m map[string][]string
}

/** Initialize your data structure here. */
func Constructor() MagicDictionary {
	return MagicDictionary{
		m: make(map[string][]string),
	}
}

/** Build a dictionary through a list of words */
func (this *MagicDictionary) BuildDict(dict []string) {
	for _, word := range dict {
		for i := 0; i < len(word); i++ {
			neighbor := word[:i] + "*" + word[i+1:]
			this.m[neighbor] = append(this.m[neighbor], word)
		}
	}
}

/** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
func (this *MagicDictionary) Search(word string) bool {
	for i := 0; i < len(word); i++ {
		neighbor := word[:i] + "*" + word[i+1:]
		count := len(this.m[neighbor])
		if count > 1 {
			return true
		} else if count == 1 {
			if this.m[neighbor][0] != word {
				return true
			}
		}
	}
	return false
}

func main() {
	dict := Constructor()
	dict.BuildDict([]string{"hello", "hallo", "leetcode"})
	fmt.Println(dict.Search("hello"))
	fmt.Println(dict.Search("hallo"))
	fmt.Println(dict.Search("hellk"))
	fmt.Println(dict.Search("hell"))
	fmt.Println(dict.Search("hellok"))
	fmt.Println(dict.Search("leetcode"))
	fmt.Println(dict.Search("leetcoded"))
}


text:
{-
  Hake: a meta build system for Barrelfish

  Copyright (c) 2009, ETH Zurich.
  All rights reserved.

  This file is distributed under the terms in the attached LICENSE file.
  If you do not find this file, copies can be found by writing to:
  ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
-}

module Main where

import System.Environment
import System.IO
import System.Directory
import System.Exit
import GHC hiding (Target)
import GHC.Paths ( libdir )
import DynFlags ( defaultFatalMessager, defaultFlushOut,
                  xopt_set,
                  ExtensionFlag (Opt_DeriveDataTypeable) )
import Data.Dynamic
import Data.Maybe
import Data.List
import Control.Monad

import RuleDefs
import HakeTypes
import qualified Path
import qualified Args
import qualified Config

--
-- Command line options and parsing code
--
data Opts = Opts { opt_makefilename :: String,
                   opt_installdir :: String,
                   opt_sourcedir :: String,
                   opt_bfsourcedir :: String,
                   opt_usage_error :: Bool,
                   opt_architectures :: [String],
                   opt_verbosity :: Integer
                 }
          deriving (Show,Eq)

parse_arguments :: [String] -> Opts
parse_arguments [] =
  Opts { opt_makefilename = "Makefile",
         opt_installdir = Config.install_dir,
         opt_sourcedir = Config.source_dir,
         opt_bfsourcedir = Config.source_dir,
         opt_usage_error = False,
         opt_architectures = [],
         opt_verbosity = 1 }
parse_arguments ("--install-dir" : (s : t)) =
  (parse_arguments t) { opt_installdir = s }
parse_arguments ("--source-dir" : s : t) =
  (parse_arguments t) { opt_sourcedir = s }
parse_arguments ("--bfsource-dir" : s : t) =
  (parse_arguments t) { opt_bfsourcedir = s }
parse_arguments ("--output-filename" : s : t) =
  (parse_arguments t) { opt_makefilename = s }
parse_arguments ("--quiet" : t ) =
  (parse_arguments t) { opt_verbosity = 0 }
parse_arguments ("--verbose" : t ) =
  (parse_arguments t) { opt_verbosity = 2 }
parse_arguments ("--architecture" : a : t ) =
  let
    o2 = parse_arguments t
    arches = (a : opt_architectures o2)
  in
    o2 { opt_architectures = arches }
parse_arguments _ =
  (parse_arguments []) { opt_usage_error = True }

usage :: String
usage = unlines [ "Usage: hake <options>",
                  "   --source-dir <dir> (required)",
                  "   --bfsource-dir <dir> (defaults to source dir)",
                  "   --install-dir <dir> (defaults to source dir)",
                  "   --quiet",
                  "   --verbose"
                ]

--
-- Handy path operator
--
infix 4 ./.
root ./. path = Path.relToDir path root

--
-- Walk all over a directory tree and build a complete list of pathnames
--
listFilesR :: FilePath -> IO [FilePath]
listFilesR path = let
    isDODD :: String -> Bool
    isDODD f = not $ (isSuffixOf "/." f)
                  || (isSuffixOf "/.." f)
                  || (isSuffixOf "CMakeFiles" f)
                  || (isPrefixOf (path ++ "/.hg") f)
                  || (isPrefixOf (path ++ "/build") f)
                  || (isPrefixOf (path ++ "/.git") f)

    listDirs :: [FilePath] -> IO [FilePath]
    listDirs = filterM doesDirectoryExist

    listFiles :: [FilePath] -> IO [FilePath]
    listFiles = filterM doesFileExist

    joinFN :: String -> String -> FilePath
    -- joinFN p1 p2 = joinPath [p1, p2]
    joinFN p1 p2 =  p1 ++ "/" ++ p2

    in do
        allfiles <- getDirectoryContents path
        no_dots <- filterM (return . isDODD) (map (joinFN path) allfiles)
        dirs <- listDirs no_dots
        subdirfiles <- (mapM listFilesR dirs >>= return . concat)
        files <- listFiles no_dots
        return $ files ++ subdirfiles

--
-- Return a list of pairs of (Hakefile name, contents)
--
readHakeFiles :: [FilePath] -> IO [ (String,String) ]
readHakeFiles [] = return []
readHakeFiles (h:hs) = do { r <- readFile h;
                            rs <- readHakeFiles hs;
                            return ((h,r):rs)
                          }
--
-- Look for Hakefiles in a list of path names
--
hakeFiles :: [FilePath] -> [String]
hakeFiles f = [ fp | fp <- f, isSuffixOf "/Hakefile" fp ]

---
--- Functions to resolve relative path names in rules.
---
--- First, the outer function: resolve path names in an HRule. The
--- third argument, 'root', is frequently the pathname of the Hakefile
--- relative to the source tree - since relative pathnames in
--- Hakefiles are interpreted relative to the Hakefile location.
---
resolveRelativePaths :: Opts -> HRule -> String -> HRule
resolveRelativePaths o (Rules hrules) root
    = Rules [ resolveRelativePaths o r root | r <- hrules ]
resolveRelativePaths o (Rule tokens) root
    = Rule [ resolveRelativePath o t root | t <- tokens ]
resolveRelativePaths o (Include token) root
    = Include ( resolveRelativePath o token root )
resolveRelativePaths o (Error s) root
    = (Error s)

--- Now resolve at the level of individual rule tokens.  At this
--- level, we need to take into account the tree (source, build, or
--- install).
resolveRelativePath :: Opts -> RuleToken -> String -> RuleToken
resolveRelativePath o (In t a f) root =
    (In t a (resolveRelativePathName o t a f root))
resolveRelativePath o (Out a f) root =
    (Out a (resolveRelativePathName o BuildTree a f root))
resolveRelativePath o (Dep t a f) root =
    (Dep t a (resolveRelativePathName o t a f root))
resolveRelativePath o (NoDep t a f) root =
    (NoDep t a (resolveRelativePathName o t a f root))
resolveRelativePath o (PreDep t a f) root =
    (PreDep t a (resolveRelativePathName o t a f root))
resolveRelativePath o (Target a f) root =
    (Target a (resolveRelativePathName o BuildTree a f root))
resolveRelativePath _ (Str s) _ = (Str s)
resolveRelativePath _ (NStr s) _ = (NStr s)
resolveRelativePath _ (ContStr b s1 s2) _ = (ContStr b s1 s2)
resolveRelativePath _ (ErrorMsg s) _ = (ErrorMsg s)
resolveRelativePath _ NL _ = NL

--- Now we get down to the nitty gritty.  We have a tree (source,
--- build, or install), an architecture (e.g. ARM), a pathname, and
--- the pathname of the Hakefile in which it occurs.

resolveRelativePathName :: Opts -> TreeRef -> String -> String -> String -> String
resolveRelativePathName o InstallTree "root" f root =
    resolveRelativePathName' ((opt_installdir o)) "root" f root
resolveRelativePathName o _ "root" f root =
    "." ./. f
resolveRelativePathName o SrcTree a f root =
    resolveRelativePathName' (opt_sourcedir o) a f root
resolveRelativePathName o BuildTree a f root =
    resolveRelativePathName' ("." ./. a) a f root
resolveRelativePathName o InstallTree a f root =
    resolveRelativePathName' ((opt_installdir o) ./. a) a f root

--- This is where the work is done: take 'root' (pathname relative to
--- us of the Hakefile) and resolve the filename we're interested in
--- relative to this.  This gives us a pathname relative to some root
--- of some architecture tree, then return this relative to the actual
--- tree we're interested in.  It's troubling that this takes more
--- bytes to explain than to code.
resolveRelativePathName' d a f root =
    let af = Path.relToFile f root
        rf = Path.makeRel $ Path.relToDir af "/"
    in Path.relToDir rf d

--
-- Generating a list of build directories
--
makeDirectories :: [(String, HRule)] -> String
makeDirectories r =
    let alldirs = makeDirs1 (Rules [ rl | (f,rl) <- r ])
        marker d = d ./. ".marker"
    in unlines ([ "# Directories follow" ] ++
                [ "hake_dirs: " ++ (marker d) ++ "\n\n" ++
                  (marker d) ++ ": \n" ++
                  "\tmkdir -p " ++ d ++ "\n" ++
                  "\ttouch " ++ (marker d) ++ "\n"
                | d <- nub alldirs])

makeDirs1 :: HRule -> [String]
makeDirs1 (Rules hrules) = concat [ makeDirs1 r | r <- hrules]
makeDirs1 (Include tok) =
    case tokDir tok of
      Nothing -> []
      Just d -> [d]
makeDirs1 (Rule toks) = [d | Just d <- [ tokDir t | t <- toks ]]
makeDirs1 (Error s) = []

tokDir :: RuleToken -> Maybe String
tokDir (In t a f) = tokDir1 f
tokDir (Out a f) =  tokDir1 f
tokDir (Dep t a f) =  tokDir1 f
tokDir (NoDep t a f) =  tokDir1 f
tokDir (PreDep t a f) =  tokDir1 f
tokDir (Target a f) =  tokDir1 f
tokDir (Str s) = Nothing
tokDir (NStr s) = Nothing
tokDir (ContStr b s1 s2) = Nothing
tokDir (ErrorMsg s) = Nothing
tokDir NL = Nothing

tokDir1 f
    | (Path.dirname f) `Path.isBelow` "." = Just (Path.dirname f)
    | otherwise = Nothing

--
-- filter rules by the set of architectures in Config.architectures
--
filterRuleByArch :: HRule -> Maybe HRule
filterRuleByArch (Rule toks) = if allowedArchs (map frArch toks) then Just (Rule toks) else Nothing
filterRuleByArch (Include tok) = if allowedArchs [frArch tok] then Just (Include tok) else Nothing
filterRuleByArch (Rules rules) = Just (Rules (catMaybes $ map filterRuleByArch rules))
filterRuleByArch x = Just x

-- a rule is included if it has only "special" architectures and enabled architectures
allowedArchs :: [String] -> Bool
allowedArchs = all (\a -> a `elem` (Config.architectures ++ specialArchitectures))
    where specialArchitectures = ["", "src", "hake", "root", "tools", "docs"]

--
-- Functions to format rules as Makefile rules
--
makeMakefile :: [(String, HRule)] -> String
makeMakefile r =
  unlines $ intersperse "" [makeMakefileSection f rl | (f,rl) <- r]

makeMakefileSection :: String -> HRule -> String
makeMakefileSection fname rules =
    "# From: " ++ fname ++ "\n\n" ++ makeMakeRules rules

makeMakeRules :: HRule -> String
makeMakeRules (Rules hrules)
    = unlines [ s | s <- [ makeMakeRules h | h <- hrules ], s /= "" ]
makeMakeRules (Include token) = unlines [
    "ifeq ($(MAKECMDGOALS),clean)",
    "else ifeq ($(MAKECMDGOALS),rehake)",
    "else ifeq ($(MAKECMDGOALS),Makefile)",
    "else",
    "include " ++ (formatToken token),
    "endif"]
makeMakeRules (Error s) = "$(error " ++ s ++ ")\n"
makeMakeRules (Rule tokens) =
    let outs = nub [ f | (Out a f) <- tokens ] ++ [ f | (Target a f) <- tokens ]
        dirs = nub [ (Path.dirname f) ./. ".marker" | f <- outs ]
        deps = nub [ f | (In t a f) <- tokens ] ++ [ f | (Dep t a f) <- tokens ]
        predeps = nub [ f | (PreDep t a f) <- tokens ]
        spaceSep :: [ String ] -> String
        spaceSep sl = concat (intersperse " " sl)
        ruleBody = (concat[ formatToken t | t <- tokens, inRule t ])
    in if outs == [] then
      ("# hake: omitted rule with no output: " ++ ruleBody)
    else
      (spaceSep outs) ++ ": "
      ++
      -- It turns out that if you add 'dirs' here, in an attempt to
      -- get Make to build the directories as well, it goes a bit
      -- pear-shaped: whenever the directory "changes" it goes out of
      -- date, so you end up rebuilding dependencies every time.
      (spaceSep (deps ++ dirs))
      ++
      (if (predeps == []) then "" else " | " ++ spaceSep (predeps))
      ++ "\n"
      ++
      (if (ruleBody == "") then "" else "\t" ++ ruleBody ++ "\n")

preamble :: Opts -> [String] -> String
preamble opts args =
    unlines ( [ "# This Makefile is generated by Hake.  Do not edit!",
                "# ",
                "# Hake was invoked with the following command line args:" ] ++
              [ "#        " ++ a | a <- args ] ++
              [ "# ",
                "SRCDIR=" ++ (opt_sourcedir opts),
                "HAKE_ARCHS=" ++ (concat $ intersperse " " Config.architectures),
                "include ./symbolic_targets.mk" ] )

stripSrcDir :: String -> String
stripSrcDir s = Path.removePrefix Config.source_dir s

hakeModule :: [String] -> [(String,String)] -> String
hakeModule allfiles hakefiles =
    let unqual_imports = ["RuleDefs", "HakeTypes", "Path", "Args"]
        qual_imports = ["Config", "Data.List" ]
        relfiles = [ stripSrcDir f | f <- allfiles ]
        wrap1 n c = wrapLet "build a"
                    ("(buildFunction a) allfiles " ++ (show n) ++ " a")
                    c
        wrap n c = "(" ++ (show n) ++ ", "
                   ++ wrapLet "find fn arg"
                          ("(fn allfiles " ++ (show n) ++ " arg)")
                          ("Rules (" ++ (wrap1 n c) ++ ")")
                   ++ ")"
        flatten :: [String] -> String
        flatten s = foldl (++) "" (intersperse ",\n" s)
        addHeader (fn,fc) = (fn, "{-# LINE 1 \"" ++ fn ++ "\" #-}\n" ++ fc)
        files = flatten [ wrap (stripSrcDir fn) fc | (fn,fc) <- map addHeader hakefiles ]
    in
      unlines ( [ "module Hakefiles where {" ]
                ++
                [ "import " ++ i ++ ";" | i <- unqual_imports ]
                ++
                [ "import qualified " ++ i ++ ";" | i <- qual_imports ]
                ++
                [ "allfiles = " ++ (show relfiles) ++ ";" ]
                ++
                [ "hf = [" ]
              ) ++ files ++ "];\n}"

wrapLet :: String -> String -> String -> String
wrapLet var expr body =
    "(let " ++ var ++ " = " ++ expr ++ " in\n" ++ body ++ ")"

evalHakeFiles :: Opts -> [String] -> [(String,String)]
              -> IO [(String,HRule)]
evalHakeFiles o allfiles hakefiles =
    let imports = [ "Hakefiles"]
        all_imports = ("Prelude":"HakeTypes":imports)
        moddirs = [ (opt_installdir o) ./. "hake",
                    ".",
                    (opt_bfsourcedir o) ./. "hake" ]
    in do
      defaultErrorHandler defaultFatalMessager defaultFlushOut $ do
         runGhc (Just libdir) $ do
           dflags <- getSessionDynFlags
	   let dflags1 = foldl xopt_set dflags [ Opt_DeriveDataTypeable ]
	   _ <- setSessionDynFlags dflags1{
		importPaths = moddirs,
                hiDir = Just "./hake",
                objectDir = Just "./hake"
	   }
           targets <- mapM (\m -> guessTarget m Nothing) imports
           setTargets targets
           load LoadAllTargets
           setContext [(IIDecl . simpleImportDecl) (mkModuleName m) | m <- (all_imports)]
           val <- dynCompileExpr "Hakefiles.hf :: [(String, HRule)]"
           return (fromDyn val [("failed",Error "failed")])

--
-- Generate dependencies of the Makefile on all the Hakefiles
--
--resolveRelativePaths o (Rules hrules) root
--- resolveRelativePath o (In t a f) root =
makeHakeDeps :: Opts -> [ String ] -> String
makeHakeDeps o l =
    let hake = resolveRelativePath o (In InstallTree "root" "/hake/hake") ""
        makefile = resolveRelativePath o (Out "root" (opt_makefilename o)) "/Hakefile"
        rule = Rule ( [ hake,
                        Str "--source-dir", Str (opt_sourcedir o),
                        Str "--install-dir", Str (opt_installdir o),
                        Str "--output-filename", makefile
                      ] ++
                      [ Dep SrcTree "root" h | h <- l ]
                    )
    in
     (makeMakeRules rule)
     ++ ".DELETE_ON_ERROR:\n\n" -- this applies to all targets in the Makefile

makeHakeDeps1 :: Opts -> [ String ] -> String
makeHakeDeps1 _ l =
    "Makefile: ./hake/hake "
    ++ concat (intersperse " " l)
    ++ "\n\t./hake/hake Makefile\n"
    ++ ".DELETE_ON_ERROR:\n\n" -- this applies to all targets in the Makefile

-- check the configuration options, returning an error string if they're insane
configErrors :: Maybe String
configErrors
    | unknownArchs /= [] = Just ("unknown architecture(s) specified: "
                               ++ (concat $ intersperse ", " unknownArchs))
    | Config.architectures == [] = Just "no architectures defined"
    | Config.lazy_thc && not Config.use_fp = Just "Config.use_fp must be true to use Config.lazy_thc."
    | otherwise = Nothing
    where
    unknownArchs = Config.architectures \\ Args.allArchitectures

---
--- Convert a Hakefile name to one relative to the root of the source tree.
---
strip_hfn :: Opts -> String -> String
strip_hfn opts f = Path.removePrefix (opt_sourcedir opts) f

main :: IO()
main = do
    -- parse arguments; architectures default to config file
    args <- System.Environment.getArgs
    let o1 = parse_arguments args
        al = if opt_architectures o1 == []
             then Config.architectures
             else opt_architectures o1
        opts = o1 { opt_architectures = al }
    if opt_usage_error opts then do
	hPutStrLn stderr usage
        exitWith $ ExitFailure 1
      else do

    -- sanity-check configuration settings
    -- this is currently known at compile time, but might not always be!
    if isJust configErrors then do
	hPutStrLn stderr $ "Error in configuration: " ++ (fromJust configErrors)
	exitWith $ ExitFailure 2
      else do

    hPutStrLn stdout ("Source directory: " ++ opt_sourcedir opts)
    hPutStrLn stdout ("BF Source directory: " ++ opt_bfsourcedir opts)
    hPutStrLn stdout ("Install directory: " ++ opt_installdir opts)

    hPutStrLn stdout "Reading directory tree..."
    l <- listFilesR (opt_sourcedir opts)
    hPutStrLn stdout "Reading Hakefiles..."
    hfl <- readHakeFiles $ hakeFiles l
    hPutStrLn stdout "Writing HakeFile module..."
    modf <- openFile ("Hakefiles.hs") WriteMode
    hPutStrLn modf $ hakeModule l hfl
    hClose modf
    hPutStrLn stdout "Evaluating Hakefiles..."
    inrules <- evalHakeFiles opts l hfl
    hPutStrLn stdout "Done!"
    -- filter out rules for unsupported architectures and resolve relative paths
    let rules =
          ([(f, resolveRelativePaths opts (fromJust (filterRuleByArch rl)) (strip_hfn opts f))
           | (f,rl) <- inrules, isJust (filterRuleByArch rl) ])
    hPutStrLn stdout $ "Generating " ++ (opt_makefilename opts) ++ " - this may take some time (and RAM)..."
    makef <- openFile(opt_makefilename opts) WriteMode
    hPutStrLn makef $ preamble opts args
    -- let hfl2 = [ strip_hfn opts (fst h) | h <- hfl ]
    hPutStrLn makef $ makeHakeDeps opts $ map fst hfl
    hPutStrLn makef $ makeMakefile rules
    hPutStrLn makef $ makeDirectories rules
    hClose makef
    exitWith ExitSuccess