text:
/*
 * Let the background process know that a page loaded.
 */
window.addEventListener("DOMContentLoaded", function()
						{
							var href = document.location.href;
							var dm = document.domain;
							switch  (dm)
							{
								case "people.opera.com":
								case "t.oslo.osa":
								case "testsuites.oslo.opera.com":
								case "testsuites.oslo.osa":
								case "www.testsuites.oslo.osa":
								case "www.testsuites.oslo.opera.com":
								case "t":
									opera.extension.postMessage("Loaded:" + document.domain);
									opera.postError("Loaded:" + document.domain);
									break;
								default:
									break;
							}
							}, false);

redpajama_set_name: RedPajamaGithub


text:
import { enableProdMode } from '@angular/core';
import { NestFactory } from '@nestjs/core';
import { ApplicationModule } from './app.module';

const PORT = process.env.PORT || 3000;

enableProdMode();

async function bootstrap() {
  const app = await NestFactory.create(ApplicationModule);
  await app.listen(PORT);
}
bootstrap().catch(err => console.error(err));


text:
/*	$OpenBSD: cpu.h,v 1.6 2004/03/09 23:05:13 deraadt Exp $	*/
/*	$NetBSD: cpu.h,v 1.1 2003/04/26 18:39:39 fvdl Exp $	*/

/*-
 * Copyright (c) 1990 The Regents of the University of California.
 * All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * William Jolitz.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)cpu.h	5.4 (Berkeley) 5/9/91
 */

#ifndef _AMD64_CPU_H_
#define _AMD64_CPU_H_

/*
 * Definitions unique to x86-64 cpu support.
 */
#include <machine/frame.h>
#include <machine/segments.h>
#include <machine/tss.h>
#include <machine/intrdefs.h>
#include <machine/cacheinfo.h>

#include <sys/device.h>
#include <sys/lock.h>

struct cpu_info {
	struct device *ci_dev;
	struct cpu_info *ci_self;
#if 0
	struct schedstate_percpu ci_schedstate; /* scheduler state */
#endif
	struct cpu_info *ci_next;

	struct proc *ci_curproc;
	struct simplelock ci_slock;
	u_int ci_cpuid;
	u_int ci_apicid;
	u_long ci_spin_locks;
	u_long ci_simple_locks;

	u_int64_t ci_scratch;

	struct proc *ci_fpcurproc;
	int ci_fpsaving;

	volatile u_int32_t ci_tlb_ipi_mask;

	struct pcb *ci_curpcb;
	struct pcb *ci_idle_pcb;
	int ci_idle_tss_sel;

	struct intrsource *ci_isources[MAX_INTR_SOURCES];
	u_int32_t	ci_ipending;
	int		ci_ilevel;
	int		ci_idepth;
	u_int32_t	ci_imask[NIPL];
	u_int32_t	ci_iunmask[NIPL];

	paddr_t 	ci_idle_pcb_paddr;
	u_int		ci_flags;
	u_int32_t	ci_ipis;

	u_int32_t	ci_feature_flags;
	u_int32_t	ci_feature_eflags;
	u_int32_t	ci_signature;
	u_int64_t	ci_tsc_freq;

	struct cpu_functions *ci_func;
	void (*cpu_setup)(struct cpu_info *);
	void (*ci_info)(struct cpu_info *);

	int		ci_want_resched;
	int		ci_astpending;
	struct trapframe *ci_ddb_regs;

	struct x86_cache_info ci_cinfo[CAI_COUNT];

	struct timeval 	ci_cc_time;
	int64_t		ci_cc_cc;
	int64_t		ci_cc_ms_delta;
	int64_t		ci_cc_denom;

	char		*ci_gdt;

	struct x86_64_tss	ci_doubleflt_tss;
	struct x86_64_tss	ci_ddbipi_tss;

	char *ci_doubleflt_stack;
	char *ci_ddbipi_stack;

	struct evcnt ci_ipi_events[X86_NIPI];
};

#define CPUF_BSP	0x0001		/* CPU is the original BSP */
#define CPUF_AP		0x0002		/* CPU is an AP */
#define CPUF_SP		0x0004		/* CPU is only processor */
#define CPUF_PRIMARY	0x0008		/* CPU is active primary processor */

#define CPUF_PRESENT	0x1000		/* CPU is present */
#define CPUF_RUNNING	0x2000		/* CPU is running */
#define CPUF_PAUSE	0x4000		/* CPU is paused in DDB */
#define CPUF_GO		0x8000		/* CPU should start running */

#define PROC_PC(p)	((p)->p_md.md_regs->tf_rip)

extern struct cpu_info cpu_info_primary;
extern struct cpu_info *cpu_info_list;

#define CPU_INFO_ITERATOR		int
#define CPU_INFO_FOREACH(cii, ci)	cii = 0, ci = cpu_info_list; \
					ci != NULL; ci = ci->ci_next

#if defined(MULTIPROCESSOR)

#define X86_MAXPROCS		32	/* bitmask; can be bumped to 64 */

#define CPU_STARTUP(_ci)	((_ci)->ci_func->start(_ci))
#define CPU_STOP(_ci)		((_ci)->ci_func->stop(_ci))
#define CPU_START_CLEANUP(_ci)	((_ci)->ci_func->cleanup(_ci))

#define curcpu()	({struct cpu_info *__ci;                  \
			asm volatile("movq %%gs:8,%0" : "=r" (__ci)); \
			__ci;})
#define cpu_number()	(curcpu()->ci_cpuid)

#define CPU_IS_PRIMARY(ci)	((ci)->ci_flags & CPUF_PRIMARY)

extern struct cpu_info *cpu_info[X86_MAXPROCS];

void cpu_boot_secondary_processors(void);
void cpu_init_idle_pcbs(void);

/*
 * Preempt the current process if in interrupt from user mode,
 * or after the current trap/syscall if in system mode.
 */
extern void need_resched(struct cpu_info *);

#else /* !MULTIPROCESSOR */

#define X86_MAXPROCS		1

#ifdef _KERNEL
extern struct cpu_info cpu_info_primary;

#define curcpu()		(&cpu_info_primary)

#endif

/*
 * definitions of cpu-dependent requirements
 * referenced in generic code
 */
#define	cpu_number()		0
#define CPU_IS_PRIMARY(ci)	1

/*
 * Preempt the current process if in interrupt from user mode,
 * or after the current trap/syscall if in system mode.
 */

#ifdef MULTIPROCESSOR
#define need_resched(ci)						\
do {									\
	struct cpu_info *__ci = (ci);					\
	__ci->ci_want_resched = 1;					\
	if (__ci->ci_curproc != NULL)					\
		aston(__ci->ci_curproc);				\
} while (/*CONSTCOND*/0)
#else
#define need_resched()							\
do {									\
	struct cpu_info *__ci = curcpu();				\
	__ci->ci_want_resched = 1;					\
	if (__ci->ci_curproc != NULL)					\
		aston(__ci->ci_curproc);				\
} while (/*CONSTCOND*/0)
#endif

#endif

#define aston(p)	((p)->p_md.md_astpending = 1)

extern u_int32_t cpus_attached;

#define curpcb		curcpu()->ci_curpcb
#define curproc		curcpu()->ci_curproc

/*
 * Arguments to hardclock, softclock and statclock
 * encapsulate the previous machine state in an opaque
 * clockframe; for now, use generic intrframe.
 */
#define clockframe intrframe

#define	CLKF_USERMODE(frame)	USERMODE((frame)->if_cs, (frame)->if_rflags)
#define CLKF_BASEPRI(frame)	(0)
#define CLKF_PC(frame)		((frame)->if_rip)
#define CLKF_INTR(frame)	(curcpu()->ci_idepth > 1)

/*
 * Give a profiling tick to the current process when the user profiling
 * buffer pages are invalid.  On the i386, request an ast to send us
 * through trap(), marking the proc as needing a profiling tick.
 */
#define	need_proftick(p)	((p)->p_flag |= P_OWEUPC, aston(p))

/*
 * Notify the current process (p) that it has a signal pending,
 * process as soon as possible.
 */
#define	signotify(p)		aston(p)

/*
 * We need a machine-independent name for this.
 */
extern void delay(int);
struct timeval;
extern void microtime(struct timeval *);

#define DELAY(x)		delay(x)

/*
 * pull in #defines for kinds of processors
 */

#ifdef _KERNEL
extern int biosbasemem;
extern int biosextmem;
extern int cpu;
extern int cpu_feature;
extern int cpu_id;
extern char cpu_vendor[];
extern int cpuid_level;

/* kern_microtime.c */

extern struct timeval cc_microset_time;
void	cc_microtime(struct timeval *);
void	cc_microset(struct cpu_info *);

/* identcpu.c */

void	identifycpu(struct cpu_info *);
int	cpu_amd64speed(int *);
void cpu_probe_features(struct cpu_info *);

/* machdep.c */
void	delay(int);
void	dumpconf(void);
int	cpu_maxproc(void);
void	cpu_reset(void);
void	x86_64_proc0_tss_ldt_init(void);
void	x86_64_bufinit(void);
void	x86_64_init_pcb_tss_ldt(struct cpu_info *);
void	cpu_proc_fork(struct proc *, struct proc *);

struct region_descriptor;
void	lgdt(struct region_descriptor *);
void	fillw(short, void *, size_t);

struct pcb;
void	savectx(struct pcb *);
void	switch_exit(struct proc *, void (*)(struct proc *));
void	proc_trampoline(void);
void	child_trampoline(void);

/* clock.c */
void	initrtclock(void);
void	startrtclock(void);
void	i8254_delay(int);
void	i8254_microtime(struct timeval *);
void	i8254_initclocks(void);

void cpu_init_msrs(struct cpu_info *);

/* trap.c */
void	child_return(void *);

/* dkcsum.c */
void	dkcsumattach(void);

/* consinit.c */
void kgdb_port_init(void);

/* bus_machdep.c */
void x86_bus_space_init(void);
void x86_bus_space_mallocok(void);

#endif /* _KERNEL */

#include <machine/psl.h>

/*
 * CTL_MACHDEP definitions.
 */
#define	CPU_CONSDEV		1	/* dev_t: console terminal device */
#define	CPU_BIOS		2	/* BIOS variables */
#define	CPU_BLK2CHR		3	/* convert blk maj into chr one */
#define	CPU_CHR2BLK		4	/* convert chr maj into blk one */
#define CPU_ALLOWAPERTURE	5	/* allow mmap of /dev/xf86 */
#define CPU_CPUVENDOR		6	/* cpuid vendor string */
#define CPU_CPUID		7	/* cpuid */
#define CPU_CPUFEATURE		8	/* cpuid features */
#define CPU_APMWARN		9	/* APM battery warning percentage */
#define CPU_KBDRESET		10	/* keyboard reset under pcvt */
#define CPU_APMHALT		11	/* halt -p hack */
#define CPU_USERLDT		12
#define CPU_MAXID		13	/* number of valid machdep ids */

#define	CTL_MACHDEP_NAMES { \
	{ 0, 0 }, \
	{ "console_device", CTLTYPE_STRUCT }, \
	{ "bios", CTLTYPE_INT }, \
	{ "blk2chr", CTLTYPE_STRUCT }, \
	{ "chr2blk", CTLTYPE_STRUCT }, \
	{ "allowaperture", CTLTYPE_INT }, \
	{ "cpuvendor", CTLTYPE_STRING }, \
	{ "cpuid", CTLTYPE_INT }, \
	{ "cpufeature", CTLTYPE_INT }, \
	{ "apmwarn", CTLTYPE_INT }, \
	{ "kbdreset", CTLTYPE_INT }, \
	{ "apmhalt", CTLTYPE_INT }, \
	{ "userldt", CTLTYPE_INT }, \
}

#endif /* !_AMD64_CPU_H_ */


text:
#ifndef MONITOR_H_
#define	MONITOR_H_

#include <stdio.h>
#include <stdint.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/stat.h>
#include <sys/uio.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <pthread.h>

#include <list>
#include <string>
#include <vector>

namespace ynode {

typedef struct {
    int init;
    long unsigned int utime_ticks;
    long int cutime_ticks;
    long unsigned int stime_ticks;
    long int cstime_ticks;

    long unsigned int cpu_total_time;
} CpuUsage;

class CpuUsageTracker {
public:
    /**
     * Returns estimated CPU usage since last call to this function.
     */
    int GetCurrent(float* ucpu_usage, float* scpu_usage, long int * uticks, long int* sticks);
    CpuUsageTracker();
private:
    int ReadCpuUsage(CpuUsage* result);
    void CalculateCpuUsage(CpuUsage* cur_usage, CpuUsage* last_usage,
                    float* ucpu_usage, float* scpu_usage, long int * uticks, long int* sticks);
    CpuUsage lastUsage_;
    CpuUsage currentUsage_;
};

/** POD structure that contains GC statistics for a given "interval"
 *  Times are in nanoseconds
 */
typedef struct {
    long unsigned int numCalls;
    uint64_t cumulativeTime; //< total time of all collections (ns)
    uint64_t maxTime;        //< max time of any single GC (ns)
} GCStat;

/**
 * Simple wrapper class to handle scoped lock for pre-existing libuv mutex
 */
class ScopedUVLock {
 public:
    ScopedUVLock(uv_mutex_t* m) : m_(m) { uv_mutex_lock(m_); }
    ~ScopedUVLock() { uv_mutex_unlock( m_ ); }
 private:
    uv_mutex_t* m_;

    ScopedUVLock();  //< can't create one of these without a reference to a mutex
};

/**
 * General interface for tracking garbage collection statistics/usage
 */
class GCUsageTracker {
public:
    GCUsageTracker() : totalCollections_(0), totalElapsedTime_(0) {};
    ~GCUsageTracker() {};

    //< Call this when a GC is starting
    void StartGC( const v8::GCType type ) {
        GetGCUsage(type).Start();
    }

    //< call when GC is ending
    void StopGC( const v8::GCType type ) {
        uint64_t elapsed = GetGCUsage(type).Stop();
        totalCollections_++;
        totalElapsedTime_ += elapsed;
    }

    const GCStat EndInterval( const v8::GCType type ) {
        return GetGCUsage( type ).EndInterval();
    }

    inline unsigned long int totalCollections() const { return totalCollections_; }
    inline uint64_t totalElapsedTime() const { return totalElapsedTime_; }

    static const int kNumGCTypes = 2;  //< must match # of distinct v8::GCTypes in v8.h

    static inline int v8GCTypeToIndex( const v8::GCType type ) {
        return type == v8::kGCTypeScavenge ? 0 : 1;
    }

    static inline v8::GCType indexTov8GCType( const int type ) {
        assert( type < kNumGCTypes );

        switch (type) {
        case 0:  return v8::kGCTypeScavenge;
        case 1:  return v8::kGCTypeMarkSweepCompact;
        default:
            return v8::kGCTypeAll;  //< with assertion above, this should be unreachable
        }
    }

    static const char* indexToString( const int type ) {
        assert( type < kNumGCTypes );

        switch (type) {
        case 0:  return "scavenge";
        case 1:  return "marksweep";
        default:
            return "unknown";  //< with assertion above, this should be unreachable
        }
    }

private:
    /**
     * Encapsulates garbage collection stats per "reporting interval"
     *
     * \desc There may be multiple calls to Start/Stop during each
     * interval.  We require a mutex lock to protect the stats_ data
     * since this is written to/updated by the v8 Javascript thread at
     * the same time as it may be read by the monitor thread
     **/
    class GCUsage {
    public:
        GCUsage();
        ~GCUsage();

        /** Returns garbage collection (GC) stats since last call to this function.
         *  Also resets the counters in order to start a new interval of GC stats
         */
        const GCStat EndInterval();

        /**
         * start and stop events get called from v8 gc prologue/epilogue
         **/
        void     Start();
        uint64_t Stop();   //< returns elapsed time as given by uv_hrtime()

    private:
        GCStat     stats_;
        uint64_t   startTime_;

        // lock used to prevent reading/writing GCStat data structure at the same time
        // by more than one thread
        uv_mutex_t  lock_;

        /* prevent copying/assigning */
        GCUsage(const GCUsage&);
        GCUsage& operator=(const GCUsage&);
    };

    inline GCUsage& GetGCUsage( const v8::GCType type ) {
        int collector = v8GCTypeToIndex( type );
        assert( collector >= 0 && collector < kNumGCTypes );

        return usage_[ v8GCTypeToIndex( type )];
    }

    GCUsage           usage_[kNumGCTypes];
    long unsigned int totalCollections_;
    uint64_t          totalElapsedTime_;
};

typedef struct {
    // time since last check
    volatile struct timeval lastTime_;

    // time since last request
    volatile struct timeval timeSinceLastRequest_;

    // last RPS
    volatile int lastRPS_;

    // requests served
    volatile float lastJiffiesPerReq_;
    volatile float lastCpuPerReq_;

    // requests already served
    volatile int lastRequests_;

    // delta between last check essentially req/per second
    // if divided by curTime - lastTime
    volatile int lastReqDelta_;

    // number of open requests
    volatile int currentOpenReqs_;

    // number of open connections
    volatile int currentOpenConns_;

    // Kb transfered since start
    volatile float lastKBytesTransfered_;
    volatile float lastKBytesSecond;

    // health status isDown
    volatile bool healthIsDown_;

    // health status: statusCode
    volatile int healthStatusCode_;

    volatile time_t healthStatusTimestamp_;

    volatile double pmem_;
} Statistics;

/** Singleton class that collects and sends stats about running isolate
 *
 * \todo This should be extended into a non-singleton
 * class that can be allocated one per v8 isolate, but for the
 * moment, it assumes there is only one running in the whole process
 * (currently true for default nodejs).
 **/
class NodeMonitor {
public:
    /** Initializes the singleton.  Do not call any other functions
     * unless this function has been called first
     */
    static void Initialize(v8::Isolate* isolate);

    void Start();
    void Stop();
    virtual ~NodeMonitor();

    /** Returns isolate which this NodeMonitor object is monitoring
     *
     *
     **/
    v8::Isolate* getIsolate() { return isolate_; };
    GCUsageTracker& getGCUsageTracker() { return gcTracker_; }

    bool sendReport();
    void setStatistics();

    static NodeMonitor& getInstance();

protected:
    // Constructor - protected since external clients must use getInstance()
    NodeMonitor(v8::Isolate* isolate);

private:
    void InitializeIPC();
    void InitializeProcessMonitorGCObject(); //< Install process.monitor.gc

    // Member variables
    bool running_;  //< have we already been started?

    time_t startTime;

    // Required to track CPU load asynchronously \todo no longer used?
    CpuUsageTracker cpuTracker_;

    // Required to track CPU load synchronously
    // in order to calculate the request per CPU ratio
    CpuUsageTracker cpuTrackerSync_;
    Statistics stats_;

    GCUsageTracker gcTracker_; //< keeps track of gc events
    pthread_t tmonitor_;    //< the pthread doing the monitoring
    v8::Isolate* isolate_;  //< the isolate this monitor is monitoring

    uv_async_t check_loop_;

    volatile unsigned int loop_count_;
    volatile unsigned int last_loop_count_;
    volatile uint64_t loop_timestamp_;
    volatile uint64_t start_timestamp_;
    volatile double consumption_;
    volatile int pending_;

    struct sockaddr_un ipcAddr_;
    socklen_t ipcAddrLen_;
    struct msghdr msg_;
    int ipcSocket_;

    static int getIntFunction(const char* funcName);
    static bool getBooleanFunction(const char* funcName);

    static NodeMonitor* instance_;  //< the singleton instance

    // null private copy/assignment constructors
    NodeMonitor(const NodeMonitor&);
    const NodeMonitor operator=(const NodeMonitor&);
};

}

#endif	/* MONITOR_H_ */


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

namespace DataComparer.Domain.Entities
{
    /// <summary>
    /// Represents a domain item containing binary data and logic for comparing and calculating differences.
    /// </summary>
    public class DataComparisonItem
    {
        private byte[] _left;

        private byte[] _right;

        /// <summary>
        /// Initializes a new instance of the <see cref="DataComparisonItem"/> class.
        /// A default constructor.
        /// </summary>
        public DataComparisonItem()
        { }

        /// <summary>
        /// Initializes a new instance of the <see cref="DataComparisonItem"/> class.
        /// </summary>
        /// <param name="left">The left binary data.</param>
        /// <param name="right">The right binary data.</param>
        public DataComparisonItem(byte[] left, byte[] right)
        {
            _left = left;
            _right = right;
        }

        /// <summary>
        /// Gets the left data.
        /// </summary>
        public IReadOnlyCollection<byte> Left
        {
            get { return _left; }
        }

        /// <summary>
        /// Gets the right data.
        /// </summary>
        public IReadOnlyCollection<byte> Right
        {
            get { return _right; }
        }

        /// <summary>
        /// Compares data and returns the state of comparison and a collection of differences.
        /// </summary>
        /// <returns>A value representing the result of the comparison.</returns>
        public virtual DiffResult Compare()
        {
            var comparisonState = CalculateComparisonState();
            return comparisonState == DiffResultType.ContentDoNotMatch
                ? new DiffResult(DiffResultType.ContentDoNotMatch, GetDifferences())
                : new DiffResult(comparisonState);
        }

        /// <summary>
        /// Sets the left data.
        /// </summary>
        public virtual void SetLeft(byte[] data)
        {
            _left = data;
        }

        /// <summary>
        /// Sets the right data.
        /// </summary>
        public virtual void SetRight(byte[] data)
        {
            _right = data;
        }

        /// <summary>
        /// Calculates the state of comparison.
        /// </summary>
        /// <returns>The state of comparison.</returns>
        private DiffResultType CalculateComparisonState()
        {
            if (_left == null && _right == null)
                return DiffResultType.Equals;

            if (_left == null || _right == null)
                return DiffResultType.SizeDoNotMatch;

            if (_left.Length != _right.Length)
                return DiffResultType.SizeDoNotMatch;

            return _left.SequenceEqual(_right) ? DiffResultType.Equals : DiffResultType.ContentDoNotMatch;
        }

        /// <summary>
        /// Gets a collection of differences between left and right data.
        /// </summary>
        /// <returns>A collection of differences.</returns>
        private List<DataDifference> GetDifferences()
        {
            var differences = new List<DataDifference>();
            var dataLength = _left.Length;
            var diffOffset = 0;
            var diffLength = 0;
            var gettingDifference = false;
            for (var index = 0; index < dataLength; ++index)
            {
                if (_left[index] == _right[index])
                {
                    if (gettingDifference)
                    {
                        differences.Add(new DataDifference(diffOffset, diffLength));
                    }

                    diffOffset = diffLength = 0;
                    gettingDifference = false;
                    continue;
                }

                if (!gettingDifference)
                {
                    diffOffset = index;
                    diffLength = 0;
                }

                diffLength++;
                gettingDifference = true;

                if (index == dataLength - 1)
                {
                    differences.Add(new DataDifference(diffOffset, diffLength));
                }
            }

            return differences;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <context id="kq" targetRuntime="MyBatis3">
        <jdbcConnection driverClass="org.mariadb.jdbc.Driver"
                        connectionURL=""
                        userId=""
                        password="">
        </jdbcConnection>

        <javaModelGenerator targetPackage="oopschen.archetype.model.generator" targetProject="src/main/java">
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <sqlMapGenerator targetPackage="generator" targetProject="src/main/resources/mybatis">
        </sqlMapGenerator>

        <javaClientGenerator type="XMLMAPPER" targetPackage="oopschen.archetype.mapper.generator"
                             targetProject="src/main/java">
        </javaClientGenerator>

        <table tableName="test">
        </table>
    </context>
</generatorConfiguration>


text:
![Splash](https://raw.githubusercontent.com/ankurp/outdoor-maintenance/master/public/screenshot.png)

Rails web site code for connecting people to do outdoor maintenance jobs in a sustainable way.

## Getting Started

1. `bundle`
1. `rake db:create`
1. `rake db:migrate`
1. `rake db:seed`
1. `rails s`


text:
<!DOCTYPE html>
<title>Service Worker: Registration (basic)</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="resources/test-helpers.sub.js"></script>
<script>
const script = 'resources/registration-worker.js';

promise_test(async (t) => {
  const scope = 'resources/registration/normal';
  const registration = await navigator.serviceWorker.register(script, {scope});
  t.add_cleanup(() => registration.unregister());
  assert_true(
    registration instanceof ServiceWorkerRegistration,
    'Successfully registered.');
}, 'Registering normal scope');

promise_test(async (t) => {
  const scope = 'resources/registration/scope-with-fragment#ref';
  const registration = await navigator.serviceWorker.register(script, {scope});
  t.add_cleanup(() => registration.unregister());
  assert_true(
    registration instanceof ServiceWorkerRegistration,
    'Successfully registered.');
  assert_equals(
    registration.scope,
    normalizeURL('resources/registration/scope-with-fragment'),
    'A fragment should be removed from scope');
}, 'Registering scope with fragment');

promise_test(async (t) => {
  const scope = 'resources/';
  const registration = await navigator.serviceWorker.register(script, {scope})
  t.add_cleanup(() => registration.unregister());
  assert_true(
    registration instanceof ServiceWorkerRegistration,
    'Successfully registered.');
}, 'Registering same scope as the script directory');
</script>


text:
#ifndef _SCSI_IOCTL_H
#define _SCSI_IOCTL_H

/* IOCTLs for SCSI.  */
#define SCSI_IOCTL_SEND_COMMAND		1	/* Send a command to the SCSI host.  */
#define SCSI_IOCTL_TEST_UNIT_READY	2	/* Test if unit is ready.  */
#define SCSI_IOCTL_BENCHMARK_COMMAND	3
#define SCSI_IOCTL_SYNC			4	/* Request synchronous parameters.  */
#define SCSI_IOCTL_START_UNIT		5
#define SCSI_IOCTL_STOP_UNIT		6
#define SCSI_IOCTL_DOORLOCK		0x5380	/* Lock the eject mechanism.  */
#define SCSI_IOCTL_DOORUNLOCK		0x5381	/* Unlock the mechanism.  */

#endif


text:
%% LecSystem class:  simple model of Lateral Entorhinal Cortex (LEC)
% Detects angles to cues in the Environment
% LEC expects that there are two or three cues:
%  Environment first cue (most salient)
%  Environment second cue
%  Environment nearest wall or a third cue
% Builds a canonical view of the cues, calculating as if current head
% direction was towards the most salient cue, and then calculating the
% angles to the second cue and the nearest wall / third cue from that angle.
% For a given position in the arena, this means that there is one canonical
% view of the cues, rather than one for each possible head direction at
% that position.
classdef LecSystem < System

    properties
%         distanceUnits
        nHeadDirectionCells
        nCueIntervals
        nFeatures
%         rewardUnits
        reward
        nOutput
        lecOutput
        environment
        index
        headDirectionSystem
        cueActivation
        cueHeadDirection
        featureWeights
%         featureGain
%         featureOffset
        featureLearningRate
        featuresDetected
        nFeatureDetectors
        readMode
        twoCuesOnly
%         offset
    end
    methods
        function obj = LecSystem()
            obj = obj@System();
%             obj.distanceUnits = 8;
            obj.nHeadDirectionCells = 60;
            % cue intervals should divide nHeadDirectionCells evenly
            obj.nCueIntervals = obj.nHeadDirectionCells;
            % set default number of features as if environment was present
            % because animal doesn't know its environment until it is
            % placed, and LecSystem is created (through
            % HippocampalFormation) before that, we need to hard-code the
            % number of features rather than deriving it.
            obj.nFeatures = 3;
%             obj.rewardUnits = 5;
            % default a head direction system, but expect to be overridden
%             obj.headDirectionSystem = HeadDirectionSystem(obj.nHeadDirectionCells);
%             obj.headDirectionSystem.build();
            obj.cueHeadDirection = 1; % default
            obj.featureLearningRate = 0.5;
            obj.nFeatureDetectors = 10; % default
            obj.readMode = 0;
%             obj.featureGain = 10;
%             obj.featureOffset = 0.65;
%             obj.offset = 0;
            obj.twoCuesOnly = false;
        end
        function build(obj)
            if obj.isEnvironmentPresentWithAtLeastTwoCues()
                if obj.environment.nCues == 2
                    if obj.twoCuesOnly
                        obj.nFeatures = 1;
                    else
                        obj.nFeatures = 3;
                    end
                else
                    obj.nFeatures = obj.environment.nCues;
                end
               % obj.nFeatures defaults or is set externally
            end
%             featureLength = obj.distanceUnits + obj.nHeadDirectionCells;
            obj.lecOutput = zeros(1, obj.nFeatures * obj.nCueIntervals);
%             obj.reward = zeros(1,obj.rewardUnits);
            obj.nOutput = length(obj.lecOutput); % + obj.rewardUnits;
            obj.index = 0;
            obj.cueActivation = zeros(1,obj.nHeadDirectionCells);
            obj.featuresDetected = zeros(1,obj.nFeatureDetectors);
            obj.featureWeights = zeros(length(obj.featuresDetected),obj.nCueIntervals);
        end
        function setEnvironment(obj, environment)
           obj.environment = environment;
        end
        function cuedEnvironment = isEnvironmentPresentWithAtLeastTwoCues(obj)
            cuedEnvironment = (isa(obj.environment,'Environment') && ...
                (obj.environment.nCues >= 2)) ;
        end
        % canonical view:
        %   head direction when pointing at most salient cue:
        %    1 to cueIntervals (e.g., 1-60)
        %   head direction offset from most salient cue head direction:
        %    cueIntervals+1 to 2*cueIntervals (e.g., 61-120)
        % if only 2 cues
        %   direction to closest wall from most salient cue head direction:
        %    2*cueIntervals+1 to 3*cueIntervals (e.g., 121-180)
        % else
        %   head direction offset from most salient cue head direction:
        %    2*cueIntervals+1 to 3*cueIntervals (e.g., 121-180)
        function buildCanonicalView(obj, headDirection)
            obj.lecOutput = zeros(1, obj.nOutput);
            if obj.isEnvironmentPresentWithAtLeastTwoCues()
                obj.index = 0;
                obj.cueHeadDirection = obj.adjustHeadDirectionTowardSalientCue(headDirection);
                if obj.twoCuesOnly
                    % nothing needed
                else
                    obj.updateLecOutput(obj.cueHeadDirection);
                end
                obj.updateLecOutput(obj.environment.cueHeadDirectionOffset(2));
                if obj.environment.nCues == 2
                    if obj.twoCuesOnly
                        % nothing needed
                    else
                        wallDirection = obj.environment.closestWallDirection();
                        obj.updateLecOutput(obj.environment.headDirectionOffset(wallDirection));
                    end
                else
                    obj.updateLecOutput(obj.environment.cueHeadDirectionOffset(3));
                end
            end
        end
%  Canonical head direction is the internal head direction when the animal
%  is pointing physically at the primary cue.  This allows us to "remember"
%  what the discrepancy is between physical and internal head direction
%  across placements in the environment.

%   for debugging:
%         function [radianPhysicalCueOffset, headDirectionRadians, radianHeadDirectionCueOffset, radianHeadDirectionOffset, canonicalHeadDirection] = ...
%           calculateCanonicalHeadDirectionForAnimalDirection(obj, physicalDirection)
        function canonicalHeadDirection = calculateCanonicalHeadDirection(obj, physicalDirection)
            saveDirection = obj.environment.getDirection();
            obj.environment.setDirection(physicalDirection);
            radianPhysicalCueOffset = obj.environment.cueDirectionOffset(1);
            headDirectionRadians = obj.headDirectionSystem.angleForCurrentHeadDirection();
            obj.environment.setDirection(headDirectionRadians);
            radianHeadDirectionCueOffset = obj.environment.cueDirectionOffset(1);
            cueDirection = obj.environment.cueDirection(1);
            obj.environment.setDirection(saveDirection);
            radianHeadDirectionOffset = radianPhysicalCueOffset - radianHeadDirectionCueOffset ;
            radianCanonicalHeadDirection = radianHeadDirectionOffset + cueDirection; % +/- .00000001; rounding
            canonicalHeadDirection = obj.environment.headDirectionOffset(radianCanonicalHeadDirection) ;
            if canonicalHeadDirection < 0
                canonicalHeadDirection = canonicalHeadDirection + obj.nHeadDirectionCells;
            end
        end

        function buildCanonicalCueActivationForAnimalDirection(obj, physicalDirection)
            canonicalHeadDirection = obj.calculateCanonicalHeadDirection(physicalDirection);
            headDirection = obj.headDirectionSystem.getMaxActivationIndex();
            obj.buildCanonicalView(canonicalHeadDirection);
            headActivation = obj.headDirectionSystem.uActivation;
            positions = canonicalHeadDirection - headDirection;
            obj.cueActivation = circshift(headActivation, positions);
        end
        function maxIndex = getCueMaxActivationIndex(obj)
            maxIndex = find(obj.cueActivation==max(obj.cueActivation));
        end
        function updateLecOutput(obj, direction)
            if direction > 0
                cueDirectionRatio = ceil(direction * (obj.nCueIntervals / obj.nHeadDirectionCells));
                obj.lecOutput(1,obj.index+cueDirectionRatio) = 1;
            end
            obj.index = obj.index + obj.nCueIntervals;
        end
        function cueHeadDirection = adjustHeadDirectionTowardSalientCue(obj, headDirection)
            obj.environment.setHeadDirection(headDirection);
            grossOffset = obj.environment.cueHeadDirectionOffset(1);
            offset = obj.nHeadDirectionCells - grossOffset + 1;
            cueHeadDirection = headDirection - offset;
            obj.environment.setHeadDirection(cueHeadDirection);
        end
        function updateFeatureWeights(obj)
%             obj.updateFeaturesDetected();
%             taken from HeadDirectionSystem

%             activation = zeros(1, obj.nHeadDirectionCells);
%             activation(1,find(obj.uActivation == max(obj.uActivation))) = 0.3;
%             newWeights = (obj.featuresDetected' * activation);
%             activation = 1./(1+exp(-obj.uActivation.*obj.featureGain)) ...
%                 - obj.featureOffset;
            newWeights = (obj.featuresDetected' * obj.cueActivation) - obj.featureWeights;
            % only update rows where features were detected
            for ii = 1:length(obj.featuresDetected)
                newWeights(ii,:) = obj.featuresDetected(1,ii).* newWeights(ii,:);
            end
            if obj.readMode
               newWeights = zeros(size(obj.featureWeights));
%                newWeights = zeros(obj.nHeadDirectionCells);
            end
            obj.featureWeights = obj.featureWeights + obj.featureLearningRate*(newWeights);
%             disp(['HDS feature detectors: ',mat2str(find(obj.featuresDetected == 1))]);
%             disp(['HDS feature weights: ',mat2str(find(obj.featureWeights > 0))]);
        end
        function featureInput = getFeatureInput(obj)
           featureInput = obj.featuresDetected * obj.featureWeights;
        end

        function indices = outputIndices(obj)
           indices = find(obj.lecOutput == 1);
        end
        function print = printOutputIndices(obj)
           print = mat2str(obj.outputIndices());
        end

        %% Single time step
         function  step(obj)
            step@System(obj);
% TODO: incorporate...
%             obj.updateFeatureWeights(); % can this be independent?
%             if obj.readMode
%                 obj.updateActivationWithFeatureInputs();
%             else
%                 obj.updateActivationWithMotionInputs();
%             end
        end
        function plot(obj)
        end
    end
end


text:
using namespace PlasticToolLocals;

//****************************************************************************************
//    Local namespace  stuff
//****************************************************************************************

namespace {

TPointD closestMeshVertexPos(const TPointD &pos, double *distance = 0) {
  const TXshCell &imageCell = TTool::getImageCell();

  TXshSimpleLevel *sl = imageCell.getSimpleLevel();
  assert(sl);

  TMeshImageP mi(TTool::getImage(false));
  assert(mi);

  // Retrieve *level* dpi
  // NOTE: This is different than current IMAGE's dpi. An image is actually
  // displayed with
  //       its level owner's dpi, RATHER than its own.

  const TPointD &dpi = sl->getDpi(imageCell.getFrameId());
  assert(dpi.x > 0.0 && dpi.y > 0.0);

  // Cast pos to image coordinates
  const TPointD pos_mesh(pos.x * (dpi.x / Stage::inch),
                         pos.y * (dpi.y / Stage::inch));

  // Retrieve the closest vertex to pos_mesh
  const std::pair<double, PlasticTool::MeshIndex> &closest =
      PlasticToolLocals::closestVertex(*mi, pos_mesh);

  const TPointD &vxPos_mesh =
      mi->meshes()[closest.second.m_meshIdx]->vertex(closest.second.m_idx).P();

  if (distance)
    *distance =
        std::min(Stage::inch / dpi.x, Stage::inch / dpi.y) * closest.first;

  // Cast it back to world coordinates
  return TPointD(vxPos_mesh.x * (Stage::inch / dpi.x),
                 vxPos_mesh.y * (Stage::inch / dpi.y));
}

//------------------------------------------------------------------------

TPointD closestSkeletonVertexPos(const TPointD &pos) {
  struct locals {
    static inline double dist2(const TPointD &pos,
                               const PlasticSkeletonVertex &vx) {
      return tcg::point_ops::dist2(pos, vx.P());
    }
  };

  const PlasticSkeletonP &skeleton = l_plasticTool.skeleton();
  if (!skeleton || skeleton->empty()) return TConsts::napd;

  const PlasticSkeleton::vertices_container &vertices = skeleton->vertices();

  return tcg::min_transform(vertices.begin(), vertices.end(),
                            tcg::bind1st(&locals::dist2, pos))
      ->P();
}

}  // namespace

//****************************************************************************************
//    Undo  definitions
//****************************************************************************************

namespace {

class VertexUndo : public TUndo {
protected:
  int m_row, m_col;  //!< Xsheet coordinates

  int m_v, m_vParent;          //!< Indices of the added vertex and its parent
  PlasticSkeletonVertex m_vx;  //!< Added vertex

  std::vector<int> m_children;  //!< Children of the vertex to insert

public:
  VertexUndo() : m_row(::row()), m_col(::column()), m_v(-1), m_vParent(-1) {}

  int getSize() const { return sizeof(*this); }  // sizeof this is roughly ok

  void storeChildren(const PlasticSkeleton &skeleton,
                     const PlasticSkeletonVertex &vx) {
    m_children.clear();

    // Traverse vx's edges and build its children table
    PlasticSkeletonVertex::edges_const_iterator et, eEnd(vx.edgesEnd());
    for (et = vx.edgesBegin(); et != eEnd; ++et) {
      int vChild = skeleton.edge(*et).vertex(1);
      if (vChild == vx.getIndex()) continue;

      m_children.push_back(vChild);
    }
  }

  void addVertex() {
    assert(m_vx.edges().empty());

    // Load the right skeleton by moving to the stored xsheet pos
    PlasticTool::TemporaryActivation tempActivate(m_row, m_col);

    const PlasticSkeletonP &skeleton = l_plasticTool.skeleton();
    TCG_ASSERT(skeleton || m_vParent < 0, return );

    // Perform addition
    l_plasticTool.setSkeletonSelection(m_vParent);
    l_plasticTool.addVertex(m_vx);

    // Store data to invert the operation
    assert(l_plasticTool.skeletonVertexSelection().hasSingleObject());
    m_v = l_plasticTool.skeletonVertexSelection();
  }

  void insertVertex() {
    if (m_children.empty()) {
      addVertex();
      return;
    }

    assert(m_vx.edges().empty());

    TCG_ASSERT(m_vParent >= 0, return );

    PlasticTool::TemporaryActivation tempActivate(m_row, m_col);

    const PlasticSkeletonP &skeleton = l_plasticTool.skeleton();
    TCG_ASSERT(skeleton, return );

    // Perform insertion
    l_plasticTool.insertVertex(m_vx, m_vParent, m_children);

    // Store data to invert the operation
    assert(l_plasticTool.skeletonVertexSelection().hasSingleObject());
    m_v = l_plasticTool.skeletonVertexSelection();
  }

  void removeVertex() {
    TCG_ASSERT(m_v >= 0, return );

    PlasticTool::TemporaryActivation tempActivate(m_row, m_col);

    const PlasticSkeletonP &skeleton = l_plasticTool.skeleton();
    TCG_ASSERT(skeleton, return );

    // Store data to invert the operation
    {
      const PlasticSkeletonVertex &vx = skeleton->vertex(m_v);

      m_vParent = vx.parent();
      m_vx      = PlasticSkeletonVertex(vx.P());

      storeChildren(*skeleton, vx);
    }

    // Perform removal
    if (m_v > 0) {
      l_plasticTool.setSkeletonSelection(m_v);
      l_plasticTool.removeVertex();
    } else
      l_plasticTool.removeSkeleton(::skeletonId());
  }
};

//------------------------------------------------------------------------

class AddVertexUndo : public VertexUndo {
public:
  AddVertexUndo(int vParent, const PlasticSkeletonVertex &vx) {
    m_vParent = vParent, m_vx = vx;
    assert(m_vx.edges().empty());
  }

  void redo() const {
    const_cast<AddVertexUndo &>(*this).VertexUndo::addVertex();
  }
  void undo() const {
    const_cast<AddVertexUndo &>(*this).VertexUndo::removeVertex();
  }
};

//------------------------------------------------------------------------

class RemoveVertexUndo : public VertexUndo {
public:
  RemoveVertexUndo(int v) {
    assert(v >= 0);
    m_v = v;
  }

  void redo() const {
    const_cast<RemoveVertexUndo &>(*this).VertexUndo::removeVertex();
  }
  void undo() const {
    const_cast<RemoveVertexUndo &>(*this).VertexUndo::insertVertex();
  }
};

//========================================================================

class InsertVertexUndo : public VertexUndo {
public:
  InsertVertexUndo(int e, const PlasticSkeletonVertex &vx) {
    const PlasticSkeleton &skeleton      = *l_plasticTool.skeleton();
    const PlasticSkeleton::edge_type &ed = skeleton.edge(e);

    m_vParent = ed.vertex(0), m_vx = vx;
    std::vector<int>(1, ed.vertex(1)).swap(m_children);
  }

  void redo() const {
    const_cast<InsertVertexUndo &>(*this).VertexUndo::insertVertex();
  }

  void undo() const {
    TCG_ASSERT(!m_children.empty(), return );

    const_cast<InsertVertexUndo &>(*this).VertexUndo::removeVertex();
  }
};

//========================================================================

class AddSkeletonUndo : public TUndo {
protected:
  int m_row, m_col;  //!< Xsheet coordinates

  int m_skelId;                 //!< The added skeleton's id
  PlasticSkeletonP m_skeleton;  //!< A COPY of the added skeleton

public:
  AddSkeletonUndo(int skelId, const PlasticSkeletonP &skeletonCopy)
      : m_row(::row())
      , m_col(::column())
      , m_skelId(skelId)
      , m_skeleton(skeletonCopy) {}

  // This is not correct... it's tough to build the right one! We're like
  // storing the whole
  // cleared deformation! So, I guess 1 MB (100 of these in the standard undos
  // pool)
  // is a reasonable estimate...
  int getSize() const { return 1 << 20; }

  void redo() const {
    PlasticTool::TemporaryActivation tempActivate(m_row, m_col);

    l_plasticTool.addSkeleton(m_skelId, new PlasticSkeleton(*m_skeleton));
    ::invalidateXsheet();
  }

  void undo() const {
    PlasticTool::TemporaryActivation tempActivate(m_row, m_col);

    l_plasticTool.removeSkeleton(m_skelId);
  }
};

//========================================================================

class RemoveSkeletonUndo : public AddSkeletonUndo {
public:
  RemoveSkeletonUndo(int skelId)
      : AddSkeletonUndo(skelId, l_plasticTool.skeleton()) {}

  void redo() const { AddSkeletonUndo::undo(); }
  void undo() const { AddSkeletonUndo::redo(); }
};

//------------------------------------------------------------------------

class RemoveSkeletonUndo_WithKeyframes : public RemoveSkeletonUndo {
  mutable std::vector<TDoubleKeyframe>
      m_skelIdsKeyframes;  //!< Skeleton Ids param curve keyframes
                           //!< for m_skelId
public:
  RemoveSkeletonUndo_WithKeyframes(int skelId) : RemoveSkeletonUndo(skelId) {}

  void redo() const {
    // Erase all keyframes corresponding to m_skelId from sd's skeleton ids
    // curve
    const SkDP &sd = l_plasticTool.deformation();
    TCG_ASSERT(sd, return );

    const TDoubleParamP &skelIdsParam = sd->skeletonIdsParam();
    if (skelIdsParam->getKeyframeCount() > 0) {
      double frame;

      for (int k = 0; k >= 0; k = skelIdsParam->getNextKeyframe(frame)) {
        const TDoubleKeyframe &kf = skelIdsParam->getKeyframe(k);
        frame                     = kf.m_frame;

        if (m_skelId == (int)kf.m_value) {
          m_skelIdsKeyframes.push_back(kf);
          skelIdsParam->deleteKeyframe(frame);
        }
      }
    }

    RemoveSkeletonUndo::redo();  // Invalidates the xsheet
  }

  void undo() const {
    l_plasticTool
        .touchDeformation();  // Skeleton removal could have destroyed the sd

    // Restore saved keyframes to sd's skelIdsParam curve
    const SkDP &sd = l_plasticTool.deformation();
    assert(sd);

    const TDoubleParamP &skelIdsParam = sd->skeletonIdsParam();

    std::vector<TDoubleKeyframe>::iterator kt, kEnd(m_skelIdsKeyframes.end());
    for (kt = m_skelIdsKeyframes.begin(); kt != kEnd; ++kt)
      skelIdsParam->setKeyframe(*kt);

    m_skelIdsKeyframes.clear();

    RemoveSkeletonUndo::undo();  // Invalidates the xsheet
  }
};

//========================================================================

class SetSkeletonIdUndo : public TUndo {
  int m_row, m_col;  //!< Xsheet coordinates

  int m_skelId;  //!< The new skeleton id value
  mutable TDoubleKeyframe
      m_oldKf;  //!< Old keyframe values for skelIds parameter
  mutable bool m_added1stKeyframe;  //!< Whether the redo() added the first
                                    //!skelIds keyframe

public:
  SetSkeletonIdUndo(int skelId)
      : m_row(::row()), m_col(::column()), m_skelId(skelId) {}

  int getSize() const { return sizeof(*this); }

  void redo() const {
    PlasticTool::TemporaryActivation tempActivate(m_row, m_col);

    const SkDP &sd = l_plasticTool.deformation();
    TCG_ASSERT(sd, return );

    const TDoubleParamP &skelIdsParam = sd->skeletonIdsParam();
    double frame                      = ::frame();

    m_oldKf            = skelIdsParam->getKeyframeAt(frame);
    m_added1stKeyframe = false;

    if (frame > 0.0 && (skelIdsParam->getKeyframeCount() == 0 ||
                        skelIdsParam->getKeyframe(0).m_frame >= frame)) {
      // Put a keyframe at the previous cell to preserve values before current
      // frame
      TDoubleKeyframe kf(frame - 1.0, skelIdsParam->getDefaultValue());
      kf.m_type = TDoubleKeyframe::Constant;

      skelIdsParam->setKeyframe(kf);
      m_added1stKeyframe = true;
    }

    TDoubleKeyframe kf(frame, m_skelId);
    kf.m_type = TDoubleKeyframe::Constant;

    skelIdsParam->setKeyframe(kf);

    // No need to invoke PlasticTool::storeSkeletonId() - automatic through
    // onChange()
  }

  void undo() const {
    PlasticTool::TemporaryActivation tempActivate(m_row, m_col);

    const SkDP &sd = l_plasticTool.deformation();
    TCG_ASSERT(sd, return );

    const TDoubleParamP &skelIdsParam = sd->skeletonIdsParam();

    if (m_oldKf.m_isKeyframe)
      skelIdsParam->setKeyframe(m_oldKf);
    else
      skelIdsParam->deleteKeyframe(m_oldKf.m_frame);

    if (m_added1stKeyframe) {
      const TDoubleKeyframe &kf = skelIdsParam->getKeyframe(0);

      assert(kf.m_value == skelIdsParam->getDefaultValue());
      if (kf.m_value == skelIdsParam->getDefaultValue())
        skelIdsParam->deleteKeyframe(kf.m_frame);
    }
  }
};

//========================================================================

class MoveVertexUndo_Build : public TUndo {
  int m_row, m_col;  //!< Xsheet coordinates

  std::vector<int> m_vIdxs;           //!< Moved vertices
  std::vector<TPointD> m_origVxsPos;  //!< Original vertex positions
  TPointD m_posShift;                 //!< Vertex positions shift

public:
  MoveVertexUndo_Build(const std::vector<int> &vIdxs,
                       const std::vector<TPointD> &origVxsPos,
                       const TPointD &posShift)
      : m_row(::row())
      , m_col(::column())
      , m_vIdxs(vIdxs)
      , m_origVxsPos(origVxsPos)
      , m_posShift(posShift) {
    assert(m_vIdxs.size() == m_origVxsPos.size());
  }

  int getSize() const {
    return int(sizeof(*this) +
               m_vIdxs.size() * (sizeof(int) + 2 * sizeof(TPointD)));
  }

  void redo() const {
    PlasticTool::TemporaryActivation tempActivate(m_row, m_col);

    l_plasticTool.setSkeletonSelection(m_vIdxs);
    l_plasticTool.moveVertex_build(m_origVxsPos, m_posShift);

    ::stageObject()
        ->invalidate();  // Should be a TStageObject's implementation detail ...
    l_plasticTool.invalidate();
  }

  void undo() const {
    PlasticTool::TemporaryActivation tempActivate(m_row, m_col);

    l_plasticTool.setSkeletonSelection(m_vIdxs);
    l_plasticTool.moveVertex_build(m_origVxsPos, TPointD());

    ::stageObject()
        ->invalidate();  // Should be a TStageObject's implementation detail ...
    l_plasticTool.invalidate();
  }
};

}  // namespace

//****************************************************************************************
//    PlasticTool  functions
//****************************************************************************************

void PlasticTool::mouseMove_build(const TPointD &pos, const TMouseEvent &me) {
  // Track mouse position
  m_pos = pos;  // Needs to be done now - ensures m_pos is valid

  m_svHigh = m_seHigh = -1;  // Reset highlighted primitives

  double d, highlightRadius = getPixelSize() * HIGHLIGHT_DISTANCE;

  const PlasticSkeletonP &skeleton = this->skeleton();
  if (skeleton) {
    // Search nearest skeleton entities

    // Look for nearest vertex
    int v = skeleton->closestVertex(pos, &d);
    if (v >= 0 && d < highlightRadius)
      m_svHigh = v;
    else {
      // Look for nearest edge
      int e = skeleton->closestEdge(pos, &d);
      if (e >= 0 && d < highlightRadius) m_seHigh = e;
    }
  }

  if (m_svHigh < 0 && m_seHigh < 0) {
    // No highlighted skeleton primitive. Mouse position may be
    // a candidate for vertex addition - snap to mesh if required
    if (m_snapToMesh.getValue()) {
      const TPointD &mvPos = ::closestMeshVertexPos(
          pos, &d);  // No need to check against closest skeleton vertex,
                     // since vertex highlighting kicks in at the same time
      if (d < highlightRadius)  // the snapping would take place.
        m_pos = mvPos;
    }
  }

  invalidate();
}

//------------------------------------------------------------------------

void PlasticTool::leftButtonDown_build(const TPointD &pos,
                                       const TMouseEvent &me) {
  // Track mouse position
  m_pressedPos = m_pos = pos;

  // Update selections
  {
    const PlasticSkeletonP &skel = skeleton();

    if (m_svHigh >= 0) {
      PlasticVertexSelection vSel(
          me.isShiftPressed()
              ? PlasticVertexSelection(branchSelection(m_svHigh))
              : PlasticVertexSelection(m_svHigh));

      if (me.isCtrlPressed())
        toggleSkeletonSelection(vSel);
      else if (!m_svSel.contains(vSel))
        setSkeletonSelection(vSel);
    } else if (m_seHigh >= 0) {
      // Insert a vertex in the edge
      TUndo *op = new InsertVertexUndo(
          m_seHigh, PlasticSkeletonVertex(projection(*skel, m_seHigh, m_pos)));
      TUndoManager::manager()->add(op);

      op->redo();
    } else if (!skel || skel->empty() || m_svSel.hasSingleObject()) {
      // Snap to mesh if required
      if (m_snapToMesh.getValue()) {
        double d, highlightRadius = getPixelSize() * HIGHLIGHT_DISTANCE;

        const TPointD &mvPos = ::closestMeshVertexPos(
            pos, &d);  // Again, no need to check against closest
                       // skeleton vertex.
        if (d < highlightRadius) m_pos = mvPos;
      }

      // Add a new vertex
      TUndo *op = new AddVertexUndo(m_svSel, PlasticSkeletonVertex(m_pos));
      TUndoManager::manager()->add(op);

      op->redo();

      assert(skeleton());
    } else
      setSkeletonSelection(-1);
  }

  // Start move vertex operation
  if (!m_svSel.isEmpty()) {
    struct locals {
      static TPointD vertexPos(const PlasticSkeleton &skel, int v) {
        return skel.vertex(v).P();
      }
    };

    const PlasticSkeletonP &skel = skeleton();
    assert(skel);

    // Adjust mouse press to the selected skeleton vertex, if necessary
    if (m_svSel.hasSingleObject()) m_pressedPos = skel->vertex(m_svSel).P();

    // Store original vertex positions
    m_pressedVxsPos = std::vector<TPointD>(
        tcg::make_cast_it(m_svSel.objects().begin(),
                          tcg::bind1st(&locals::vertexPos, *skel)),
        tcg::make_cast_it(m_svSel.objects().end(),
                          tcg::bind1st(&locals::vertexPos, *skel)));
  }

  invalidate();
}

//------------------------------------------------------------------------

void PlasticTool::leftButtonDrag_build(const TPointD &pos,
                                       const TMouseEvent &me) {
  // Track mouse position
  if (m_snapToMesh.getValue()) {
    const TPointD &mvPos = ::closestMeshVertexPos(pos),
                  &svPos = ::closestSkeletonVertexPos(mvPos);

    if (tcg::point_ops::dist(mvPos, svPos) >
        getPixelSize())  // 1) If said distance is sub-pixel, the user
      m_pos = mvPos;  //    just cannot see the assignment - so it's not safe.
  }                   // 2) The moveVertex_build() below manipulates m_pos
  else                //    (not how m_pressedPos is subtracted), so !=
    m_pos = pos;      //    is not a choice.

  moveVertex_build(m_pressedVxsPos, m_pos - m_pressedPos);
  invalidate();
}

//------------------------------------------------------------------------

void PlasticTool::leftButtonUp_build(const TPointD &pos,
                                     const TMouseEvent &me) {
  // Track mouse position
  if (m_snapToMesh.getValue()) {
    const TPointD &mvPos = ::closestMeshVertexPos(pos),
                  &svPos = ::closestSkeletonVertexPos(mvPos);

    if (tcg::point_ops::dist(mvPos, svPos) > getPixelSize())  // Same as above
      m_pos = mvPos;
  } else
    m_pos = pos;

  if (!m_svSel.isEmpty() && m_dragged) {
    TUndoManager::manager()->add(new MoveVertexUndo_Build(
        m_svSel.objects(), m_pressedVxsPos, m_pos - m_pressedPos));

    ::stageObject()
        ->invalidate();  // Should be a TStageObject's implementation detail ...
    invalidate();        // .. it's that it caches placement data and we must
  }                      // invalidate it. Gross. Can't we do anything about it?
}

//------------------------------------------------------------------------

void PlasticTool::addContextMenuActions_build(QMenu *menu) {
  bool ret = true;

  if (!m_svSel.isEmpty()) {
    QAction *deleteVertex = menu->addAction(tr("Delete Vertex"));
    ret = ret && connect(deleteVertex, SIGNAL(triggered()), &l_plasticTool,
                         SLOT(deleteSelectedVertex_undo()));

    menu->addSeparator();
  }

  assert(ret);
}

//------------------------------------------------------------------------

void PlasticTool::moveVertex_build(const std::vector<TPointD> &origVxsPos,
                                   const TPointD &posShift) {
  if (!m_svSel.isEmpty()) {
    const PlasticSkeletonP &skeleton = this->skeleton();

    // Move selected vertices
    int v, vCount = int(m_svSel.objects().size());
    for (v = 0; v != vCount; ++v)
      skeleton->moveVertex(m_svSel.objects()[v], origVxsPos[v] + posShift);

    // Deformation must be recompiled
    PlasticDeformerStorage::instance()->invalidateSkeleton(
        m_sd.getPointer(), ::skeletonId(), PlasticDeformerStorage::ALL);

    if (m_mode.getIndex() == ANIMATE_IDX)
      storeDeformation();  // Rebuild deformed skeleton - default values have
                           // changed
  }
}

//------------------------------------------------------------------------

void PlasticTool::addVertex(const PlasticSkeletonVertex &vx) {
  touchSkeleton();
  const PlasticSkeletonP &skeleton = this->skeleton();

  l_suspendParamsObservation =
      true;  // Some vertex parameters change during insert

  assert(
      m_svSel.isEmpty() ||
      m_svSel
          .hasSingleObject());  // Could there be no parent (inserting the root)
  setSkeletonSelection(skeleton->addVertex(vx, m_svSel));

  l_suspendParamsObservation = false;
  onChange();  // Update once after add

  // NOTE: Root addition does NOT currently add channels, so the above
  // onChange() is
  // quite necessary to cover that case too!

  // Xsheet change notification is necessary to inform the Function Editor that
  // new
  // channels (the vertex deformation ones) have been introduced
  TTool::getApplication()->getCurrentXsheet()->notifyXsheetChanged();
  PlasticDeformerStorage::instance()->invalidateSkeleton(
      m_sd.getPointer(), ::skeletonId(), PlasticDeformerStorage::ALL);
}

//------------------------------------------------------------------------

void PlasticTool::insertVertex(const PlasticSkeletonVertex &vx, int parent,
                               const std::vector<int> &children) {
  const PlasticSkeletonP &skeleton = this->skeleton();
  assert(skeleton);

  l_suspendParamsObservation =
      true;  // Some vertex parameters change during insert.

  setSkeletonSelection(skeleton->insertVertex(vx, parent, children));

  l_suspendParamsObservation = false;
  onChange();  // Update once after insertion

  TTool::getApplication()->getCurrentXsheet()->notifyXsheetChanged();
  PlasticDeformerStorage::instance()->invalidateSkeleton(
      m_sd.getPointer(), ::skeletonId(), PlasticDeformerStorage::ALL);
}

//------------------------------------------------------------------------

void PlasticTool::insertVertex(const PlasticSkeletonVertex &vx, int e) {
  const PlasticSkeletonP &skeleton = this->skeleton();
  assert(skeleton);

  const PlasticSkeleton::edge_type &ed = skeleton->edge(e);
  insertVertex(vx, ed.vertex(0),
               std::vector<int>(1, skeleton->edge(e).vertex(1)));
}

//------------------------------------------------------------------------

void PlasticTool::removeVertex() {
  const PlasticSkeletonP &skeleton = this->skeleton();
  assert(skeleton && m_svSel.hasSingleObject() && m_svSel > 0);

  l_suspendParamsObservation =
      true;  // Some vertex parameters change during removal.
             // We need to avoid updating WHILE removing.
  skeleton->removeVertex(m_svSel);
  PlasticDeformerStorage::instance()->invalidateSkeleton(
      m_sd.getPointer(), ::skeletonId(), PlasticDeformerStorage::ALL);

  l_suspendParamsObservation = false;
  onChange();

  clearSkeletonSelections();  // Remove mesh references - could be
                              // invalidated...

  // Xsheet change notification is necessary to inform the Function Editor that
  // some
  // channels (the vertex deformation ones) have been removed
  TTool::getApplication()
      ->getCurrentXsheet()
      ->notifyXsheetChanged();  // NOTE: This COULD invoke invalidate()...

  // Rebuild the stage object's keyframes table
  stageObject()->updateKeyframes();
}

//------------------------------------------------------------------------

int PlasticTool::addSkeleton(const PlasticSkeletonP &skeleton) {
  assert(TTool::isEnabled());

  touchDeformation();

  int skelId;
  {
    if (m_sd->empty())
      skelId = 1;
    else {
      // Get the first unused skeleton id in m_sd
      SkD::skelId_iterator st, sEnd;
      m_sd->skeletonIds(st, sEnd);

      for (skelId = 1; st != sEnd && skelId == *st; ++skelId, ++st)
        ;
    }
  }

  addSkeleton(skelId, skeleton);
  return skelId;
}

//------------------------------------------------------------------------

void PlasticTool::addSkeleton(int skelId, const PlasticSkeletonP &skeleton) {
  assert(TTool::isEnabled());

  touchDeformation();
  m_sd->attach(skelId, skeleton.getPointer());

  emit skelIdsListChanged();
}

//------------------------------------------------------------------------

void PlasticTool::removeSkeleton(int skelId) {
  // Remove the entire deformation
  clearSkeletonSelections();

  if (m_sd) {
    m_sd->detach(skelId);
    if (m_sd->empty())
      stageObject()->setPlasticSkeletonDeformation(
          PlasticSkeletonDeformationP());

    ::invalidateXsheet();  // Updates m_sd
    emit skelIdsListChanged();
  }
}

//------------------------------------------------------------------------

void PlasticTool::deleteSelectedVertex_undo() {
  if (m_svSel.isEmpty()) return;

  TUndoManager *manager = TUndoManager::manager();

  if (m_svSel.contains(0)) {
    TUndo *op = new RemoveSkeletonUndo(::skeletonId());
    manager->add(op);

    op->redo();
  } else {
    typedef PlasticVertexSelection::objects_container objects_container;

    objects_container vertexIdxs =
        m_svSel.objects();  // Each undo will reset the vertex selection,
                            // so we need a copy
    manager->beginBlock();
    {
      objects_container::const_iterator vit, viEnd = vertexIdxs.end();
      for (vit = vertexIdxs.begin(); vit != viEnd; ++vit) {
        TUndo *op = new RemoveVertexUndo(*vit);
        manager->add(op);

        op->redo();
      }
    }
    manager->endBlock();
  }
}

//------------------------------------------------------------------------

int PlasticTool::addSkeleton_undo(const PlasticSkeletonP &skeleton) {
  int skelId;

  TUndoManager *manager = TUndoManager::manager();
  manager->beginBlock();
  {
    skelId = l_plasticTool.addSkeleton(skeleton);
    assert(l_plasticTool.deformation());

    TUndo *addUndo =
        new AddSkeletonUndo(skelId, new PlasticSkeleton(*skeleton));
    manager->add(addUndo);

    TUndo *setIdUndo = new SetSkeletonIdUndo(skelId);
    manager->add(setIdUndo);

    setIdUndo->redo();
  }
  manager->endBlock();

  ::invalidateXsheet();
  return skelId;
}

//------------------------------------------------------------------------

void PlasticTool::addSkeleton_undo(int skelId,
                                   const PlasticSkeletonP &skeleton) {
  TUndoManager *manager = TUndoManager::manager();
  manager->beginBlock();
  {
    l_plasticTool.addSkeleton(skelId, skeleton);
    assert(l_plasticTool.deformation());

    TUndo *addUndo =
        new AddSkeletonUndo(skelId, new PlasticSkeleton(*skeleton));
    manager->add(addUndo);

    TUndo *setIdUndo = new SetSkeletonIdUndo(skelId);
    manager->add(setIdUndo);

    setIdUndo->redo();
  }
  manager->endBlock();

  ::invalidateXsheet();
}

//------------------------------------------------------------------------

void PlasticTool::removeSkeleton_undo(int skelId) {
  TUndo *op = new RemoveSkeletonUndo(skelId);
  TUndoManager::manager()->add(op);

  op->redo();
}

//------------------------------------------------------------------------

void PlasticTool::removeSkeleton_withKeyframes_undo(int skelId) {
  TUndo *op = new RemoveSkeletonUndo_WithKeyframes(skelId);
  TUndoManager::manager()->add(op);

  op->redo();
}

//------------------------------------------------------------------------

void PlasticTool::editSkelId_undo(int skelId) {
  TUndo *op = new SetSkeletonIdUndo(skelId);
  TUndoManager::manager()->add(op);

  op->redo();
}

//------------------------------------------------------------------------

void PlasticTool::draw_build() {
  double pixelSize = getPixelSize();

  // Draw original skeleton
  const PlasticSkeletonP &skeleton = this->skeleton();
  if (skeleton) {
    drawOnionSkinSkeletons_build(pixelSize);
    drawSkeleton(*skeleton, pixelSize);
    drawSelections(m_sd, *skeleton, pixelSize);
  }

  drawHighlights(m_sd, skeleton.getPointer(), pixelSize);

  if (!skeleton || skeleton->vertices().empty() ||
      (m_svSel.hasSingleObject() && m_svHigh < 0 && m_seHigh < 0)) {
    // Draw a handle at current mouse pos (will add a vertex)
    drawSquare(m_pos, HANDLE_SIZE * pixelSize);
  }
}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Module: ActionController::MimeResponds::ClassMethods</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href="../../.././rdoc-style.css" type="text/css" media="screen" />

          Module
          ActionController::MimeResponds::ClassMethods

            In:

                /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.0.beta4/lib/action_controller/metal/mime_responds.rb

Methods

      clear_respond_to
      respond_to

Public Instance methods

          clear_respond_to()

Clear all mimes in respond_to.

[Source]

    # File /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.0.beta4/lib/action_controller/metal/mime_responds.rb, line 54
54:       def clear_respond_to
55:         self.mimes_for_respond_to = ActiveSupport::OrderedHash.new.freeze
56:       end

          respond_to(*mimes)

Defines mimes that are rendered by default when invoking respond_with.

Examples:

  respond_to :html, :xml, :json

All actions on your controller will respond to :html, :xml and :json.

But if you want to specify it based on your actions, you can use only and
except:

  respond_to :html
  respond_to :xml, :json, :except => [ :edit ]

The definition above explicits that all actions respond to :html. And all
actions except :edit respond to :xml and :json.

You can specify also only parameters:

  respond_to :rjs, :only => :create

[Source]

    # File /usr/lib/ruby/gems/1.8/gems/actionpack-3.0.0.beta4/lib/action_controller/metal/mime_responds.rb, line 36
36:       def respond_to(*mimes)
37:         options = mimes.extract_options!
38:
39:         only_actions   = Array(options.delete(:only))
40:         except_actions = Array(options.delete(:except))
41:
42:         new = mimes_for_respond_to.dup
43:         mimes.each do |mime|
44:           mime = mime.to_sym
45:           new[mime]          = {}
46:           new[mime][:only]   = only_actions   unless only_actions.empty?
47:           new[mime][:except] = except_actions unless except_actions.empty?
48:         end
49:         self.mimes_for_respond_to = new.freeze
50:       end

[Validate]


text:
layout: post
title:  "100 Days of SwiftUI - Day 47 (repeated)"
date:   2020-05-08 14:16:53 +1200
categories: ohdos
---
According to the rules for taking part in [100 Days of SwiftUI](https://www.hackingwithswift.com/100/swiftui), as soon as I've finished each day, I have to post about it.

The topic for Day 47 (repeated) was: Milestone: Projects 7-9


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <!--
    <parameters>
        <parameter key="armd_o_auth.example.class">Armd\OAuthBundle\Example</parameter>
    </parameters>

    <services>
        <service id="armd_o_auth.example" class="%armd_o_auth.example.class%">
            <argument type="service" id="service_id" />
            <argument>plain_value</argument>
            <argument>%parameter_name%</argument>
        </service>
    </services>
    -->
</container>


text:
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "AnimatedTitleForm.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TfrmAnimatedTitle *frmAnimatedTitle;
//---------------------------------------------------------------------------
__fastcall TfrmAnimatedTitle::TfrmAnimatedTitle(TComponent* Owner)
  : TForm(Owner)
{
}
//---------------------------------------------------------------------------


text:
Adding a new API
================

While this process will usually be performed by Googlers, there's
nothing confidential about it, and it may be of interest to third
parties.

Prerequisites:

- A Windows machine with Git for Windows, Visual Studio 2017
  (including .NET Core tools) installed
- A Linux environment equivalent to Ubuntu 16.04 or higher.
  The simplest way to accomplish this is usually to use the Linux
  Subsystem for Windows, as you can then use a single fork for all
  instructions here. This environment must include jdk8.

Note that Git for Windows includes bash, and that's what our scripts
have all been written to use. Do not try to use the Linux subsystem
for Windows to run the scripts.

Relevant repositories:

- [googleapis](https://github.com/googleapis/googleapis): API definitions
- [toolkit](https://github.com/googleapis/toolkit): Code generator, also known as GAPIC
- [google-cloud-dotnet](https://github.com/GoogleCloudPlatform/google-cloud-dotnet): This
  repository, where code will end up

This list of instructions looks daunting, but it's not as bad as it
seems: it aims to be pretty comprehensive, although it assumes you
know how to use `git` appropriately.

Step 1: Fork google-cloud-dotnet on github
------------------------------------------

Our process is to merge from user-owned forks, so first fork this repo.

Step 2: Check the API is correct in googleapis
----------------------------------------------

The API should be present in the googleapis repo, including:

- Protos describing the service (e.g. [datastore v1](https://github.com/googleapis/googleapis/tree/master/google/datastore/v1)
- A YAML file (e.g. [datastore.yaml](https://github.com/googleapis/googleapis/blob/master/google/datastore/datastore.yaml)) containing
  more general service metadata
- A GAPIC YAML file (e.g. [datastore_gapic.yaml](https://github.com/googleapis/googleapis/blob/master/google/datastore/v1/datastore_gapic.yaml)
  containing more semantic information required by the code generator, such as how resources are organized and named

Check that these files all exist, and check that the C# namespace is
appropriate. The protos should contain `csharp_namespace` options
unless the default capitalization produces the correct result. The
same namespace should be specified in the GAPIC YAML file under
`language_settings > csharp > package_name`.

If anything doesn't match your expectations, please file an issue in
this repo and we'll get it sorted. (There are complexities here around internal processes.)

Step 3: Add the API to generateapis.sh
--------------------------------------

Adding an API will usually be as simple as adding a line like this
to the section at the bottom of `generateapis.sh` in the root
directory:

```text
generate_api Google.Cloud.Datastore.V1 google/datastore/v1 datastore.yaml
```

The first argument to the `generate_api` function is the API
namespace (our tooling is too primitive to work it out from the
files, at the moment). The second argument is the directory within
the `googleapis` repo. The third argument is the name of the general
YAML file for the service. (It's assumed there will only be one file
ending with `_gapic.yaml`.)

Please keep the list of `generate_api` calls in alphabetical order.

Step 4: Run generateapis.sh
---------------------------

This will clone both the `googleapis` and `toolkit` repos as
subdirectories, or pull them if they already exist.

This may take a while, and will spew a lot of output. If it fails
with a Java exception, that's probably due to a configuration issue
somewhere. You can try to fix it yourself, but it's probably worth
reaching out at that point.

Step 5: Commit just the changes for your API
--------------------------------------------

You may see changes for other APIs. Ignore those. Create a commit containing:

- Your `generateapis.sh` change
- The new directory under `apis`

If you're using separate machine for the Linux part, push the change
up to your fork on github, so you can pull it down to the Windows
machine.

Step 6: Modify the API catalog
------------------------------

Edit `apis/apis.json`. Again, this is in alphabetical order - please keep it that way.
You'll typically want JSON like this:

```json
{
  "id": "FIXME",
  "productName": "FIXME",
  "productUrl": "FIXME",
  "version": "1.0.0-beta01",
  "type": "grpc",
  "description": "FIXME",
  "tags": [ "FIXME_1", "FIXME_2" ],
}
```

Fix everything with "FIXME". There's no set number of tags, but these are used for the NuGet package,
so consider what users will search for.

The above assumes you're happy to create an initial beta release for
the generated code immediately. As of late 2017, that's usually
fine. If you want to avoid creating a release, use a version of
`1.0.0-alpha00` or `1.0.0-beta00` depending on whether or not you
expect to perform alpha releases.

If your project uses the IAM or long-running operations APIs, you'll need to add dependencies for those, e.g.

```json
"dependencies": {
  "Google.LongRunning": "1.0.0",
  "Google.Cloud.Iam.V1": "1.0.0"
}
```

Look at other APIs for example values.

Step 7: Generate files
----------------------

Run `generateprojects.sh`. This should create:

- A solution file
- Project files for the production project and the snippets
- A stub documentation file

Step 8: Run the smoke test
--------------------------

New APIs should come with a smoke test, just to check we can at
least make a single request.

- Ensure the `TEST_PROJECT` environment variable is set to your GCP
  project ID.
- Ensure the API is enabled for your project
- Run `runintegrationtests.sh --smoke Your.ApiName.Here`

Step 9: Create a PR
-------------------

You should now have a lot of new project/coverage/doc/solution files, and
your modified API catalog.

Commit all of these, push and create a pull request. This should
consist of two commits: one for the original codegen, and one for
the API catalog and project files.

(You *can* do all of this in a single commit, but we've typically
found that separating them helps diagnose issues with one part or
another.)

Step 10: Merge the PR
---------------------

As everything is generated other than the API catalog change, the PR
can be merged on green.

Step 11 (Optional): Release the first package for the API
---------------------------------------------------------

Follow the [releasing process](PROCESSES.md) to push a package to
nuget.org. If you do this, also update the root documentation
(`README.md` and `docs/root/index.md`) to indicate this.


text:
@interface LCTabBar ()

@end

@implementation LCTabBar

- (NSMutableArray *)tabBarItems {

    if (_tabBarItems == nil) {

        _tabBarItems = [[NSMutableArray alloc] init];
    }
    return _tabBarItems;
}

- (void)addTabBarItem:(UITabBarItem *)item {

    LCTabBarItem *tabBarItem = [[LCTabBarItem alloc] initWithItemImageRatio:self.itemImageRatio];

    tabBarItem.badgeTitleFont         = self.badgeTitleFont;
    tabBarItem.itemTitleFont          = self.itemTitleFont;
    tabBarItem.itemTitleColor         = self.itemTitleColor;
    tabBarItem.selectedItemTitleColor = self.selectedItemTitleColor;

    tabBarItem.tabBarItemCount = self.tabBarItemCount;

    tabBarItem.tabBarItem = item;

    [tabBarItem addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchDown];

    [self addSubview:tabBarItem];

    [self.tabBarItems addObject:tabBarItem];

    if (self.tabBarItems.count == 1) {

        [self buttonClick:tabBarItem];
    }
}

- (void)buttonClick:(LCTabBarItem *)tabBarItem {

    if ([self.delegate respondsToSelector:@selector(tabBar:didSelectedItemFrom:to:)]) {

        [self.delegate tabBar:self didSelectedItemFrom:self.selectedItem.tabBarItem.tag to:tabBarItem.tag];
    }

    self.selectedItem.selected = NO;
    self.selectedItem = tabBarItem;
    self.selectedItem.selected = YES;
}

- (void)layoutSubviews {

    [super layoutSubviews];

    CGFloat w = self.frame.size.width;
    CGFloat h = self.frame.size.height;

    int count = (int)self.tabBarItems.count;
    CGFloat itemY = 0;
    CGFloat itemW = w / self.subviews.count;
    CGFloat itemH = h;

    for (int index = 0; index < count; index++) {

        LCTabBarItem *tabBarItem = self.tabBarItems[index];
        tabBarItem.tag = index;
        CGFloat itemX = index * itemW;
        tabBarItem.frame = CGRectMake(itemX, itemY, itemW, itemH);
    }
}

@end


text:
wired4j
=======

wired4j is a Java implementation of the [Wired](http://wired.read-write.fr/) client protocol.


text:
package org.apache.geode.internal.cache;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;

import org.apache.logging.log4j.Logger;

import org.apache.geode.cache.persistence.PartitionOfflineException;
import org.apache.geode.distributed.DistributedLockService;
import org.apache.geode.distributed.internal.ReplyException;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.internal.cache.PartitionedRegion.BucketLock;
import org.apache.geode.internal.cache.partitioned.RedundancyAlreadyMetException;
import org.apache.geode.internal.cache.persistence.MembershipChangeListener;
import org.apache.geode.internal.cache.persistence.PersistenceAdvisorImpl;
import org.apache.geode.internal.cache.persistence.PersistentMemberID;
import org.apache.geode.internal.cache.persistence.PersistentMemberManager;
import org.apache.geode.internal.cache.persistence.PersistentMemberView;
import org.apache.geode.internal.cache.persistence.PersistentStateListener.PersistentStateAdapter;
import org.apache.geode.internal.i18n.LocalizedStrings;
import org.apache.geode.internal.logging.LogService;
import org.apache.geode.internal.logging.log4j.LocalizedMessage;
import org.apache.geode.internal.logging.log4j.LogMarker;
import org.apache.geode.internal.util.TransformUtils;

public class BucketPersistenceAdvisor extends PersistenceAdvisorImpl {

  private static final Logger logger = LogService.getLogger();

  public CountDownLatch someMemberRecoveredLatch = new CountDownLatch(1);
  public boolean recovering = true;
  private boolean atomicCreation;
  private final BucketLock bucketLock;
  /**
   * A listener to watch for removes during the recovery process. After recovery is done, we know
   * longer need to worry about removes.
   */
  private final RecoveryListener recoveryListener;
  private final ProxyBucketRegion proxyBucket;
  private short version;
  private RuntimeException recoveryException;

  public BucketPersistenceAdvisor(CacheDistributionAdvisor advisor, DistributedLockService dl,
      PersistentMemberView storage, String regionPath, DiskRegionStats diskStats,
      PersistentMemberManager memberManager, BucketLock bucketLock,
      ProxyBucketRegion proxyBucketRegion) {
    super(advisor, dl, storage, regionPath, diskStats, memberManager);
    this.bucketLock = bucketLock;

    recoveryListener = new RecoveryListener();
    this.proxyBucket = proxyBucketRegion;
    addListener(recoveryListener);
  }

  public void recoveryDone(RuntimeException e) {
    this.recovering = false;
    if (!getPersistedMembers().isEmpty()) {
      ((BucketAdvisor) cacheDistributionAdvisor).setHadPrimary();
    }
    // Make sure any removes that we saw during recovery are
    // applied.
    removeListener(recoveryListener);
    for (PersistentMemberID id : recoveryListener.getRemovedMembers()) {
      removeMember(id);
    }
    if (someMemberRecoveredLatch.getCount() > 0) {
      this.recoveryException = e;
      this.someMemberRecoveredLatch.countDown();
    } else if (recoveryException != null) {
      logger.fatal(LocalizedMessage.create(
          LocalizedStrings.BucketPersistenceAdvisor_ERROR_RECOVERYING_SECONDARY_BUCKET_0,
          new Object[] {proxyBucket.getPartitionedRegion().getFullPath(),
              proxyBucket.getBucketId()}),
          e);
    }
  }

  @Override
  public void checkInterruptedByShutdownAll() {
    // when ShutdownAll is on-going, break all the GII for BR
    if (proxyBucket.getCache().isCacheAtShutdownAll()) {
      throw proxyBucket.getCache().getCacheClosedException("Cache is being closed by ShutdownAll");
    }
    proxyBucket.getPartitionedRegion().checkReadiness();
  }

  public boolean isRecovering() {
    return this.recovering;
  }

  @Override
  public void beginWaitingForMembershipChange(Set<PersistentMemberID> membersToWaitFor) {
    if (recovering) {
      bucketLock.unlock();
    } else {
      if (membersToWaitFor != null && !membersToWaitFor.isEmpty()) {
        String message = LocalizedStrings.PartitionedRegionDataStore_DATA_OFFLINE_MESSAGE
            .toLocalizedString(proxyBucket.getPartitionedRegion().getFullPath(),
                proxyBucket.getBucketId(), membersToWaitFor);
        throw new PartitionOfflineException((Set) membersToWaitFor, message);
      }
    }
  }

  @Override
  public void logWaitingForMembers() {
    // We only log the bucket level information at fine level.
    if (logger.isDebugEnabled(LogMarker.PERSIST_ADVISOR_VERBOSE)) {
      Set<String> membersToWaitForPrettyFormat = new HashSet<String>();

      if (offlineMembersWaitingFor != null && !offlineMembersWaitingFor.isEmpty()) {
        TransformUtils.transform(offlineMembersWaitingFor, membersToWaitForPrettyFormat,
            TransformUtils.persistentMemberIdToLogEntryTransformer);
        logger.debug(LogMarker.PERSIST_ADVISOR_VERBOSE, LocalizedMessage.create(
            LocalizedStrings.BucketPersistenceAdvisor_WAITING_FOR_LATEST_MEMBER,
            new Object[] {proxyBucket.getPartitionedRegion().getFullPath(),
                proxyBucket.getBucketId(),
                TransformUtils.persistentMemberIdToLogEntryTransformer.transform(getPersistentID()),
                membersToWaitForPrettyFormat}));
      } else {
        TransformUtils.transform(allMembersWaitingFor, membersToWaitForPrettyFormat,
            TransformUtils.persistentMemberIdToLogEntryTransformer);
        if (logger.isDebugEnabled()) {
          logger.debug(LogMarker.PERSIST_ADVISOR_VERBOSE,
              "All persistent members being waited on are online, but they have not yet initialized");
        }
        logger.debug(LogMarker.PERSIST_ADVISOR_VERBOSE, LocalizedMessage.create(
            LocalizedStrings.BucketPersistenceAdvisor_WAITING_FOR_LATEST_MEMBER,
            new Object[] {proxyBucket.getPartitionedRegion().getFullPath(),
                proxyBucket.getBucketId(),
                TransformUtils.persistentMemberIdToLogEntryTransformer.transform(getPersistentID()),
                membersToWaitForPrettyFormat}));
      }
    }
  }

  @Override
  public void endWaitingForMembershipChange() {
    if (recovering) {
      bucketLock.lock();
      // We allow regions with persistent colocated children to exceed redundancy
      // so that we can create the child bucket. Otherwise, we need to check
      // that redundancy has not already been met now that we've got the dlock
      // the delock.
      if (!proxyBucket.hasPersistentChildRegion()
          && !proxyBucket.checkBucketRedundancyBeforeGrab(null, false)) {
        if (logger.isDebugEnabled(LogMarker.PERSIST_ADVISOR_VERBOSE)) {
          logger.debug(LogMarker.PERSIST_ADVISOR_VERBOSE,
              "{}-{}: After reacquiring dlock, we detected that redundancy is already satisfied",
              shortDiskStoreId(), regionPath);
        }
        // Remove the persistent data for this bucket, since
        // redundancy is already satisfied.
        proxyBucket.destroyOfflineData();
        throw new RedundancyAlreadyMetException();
      }
    }
  }

  @Override
  public void updateMembershipView(InternalDistributedMember replicate,
      boolean targetReinitializing) {
    if (recovering) {
      super.updateMembershipView(replicate, targetReinitializing);
      someMemberRecoveredLatch.countDown();
    } else {
      // don't update the membership view, we already updated it during recovery.
    }
  }

  /**
   * Wait for there to be initialized copies of this bucket. Get the latest membership view from
   * those copies.
   *
   */
  public void initializeMembershipView() {
    MembershipChangeListener listener = new MembershipChangeListener(this);
    addListener(listener);
    boolean interrupted = false;
    try {
      while (!isClosed) {
        cacheDistributionAdvisor.getAdvisee().getCancelCriterion().checkCancelInProgress(null);

        // Look for any online copies of the bucket.
        // If there are any, get a membership view from them.
        Map<InternalDistributedMember, PersistentMemberID> onlineMembers =
            cacheDistributionAdvisor.adviseInitializedPersistentMembers();
        if (onlineMembers != null) {
          if (updateMembershipView(onlineMembers.keySet())) {
            break;
          }
        }

        Set<InternalDistributedMember> postRecoveryMembers =
            ((BucketAdvisor) cacheDistributionAdvisor).adviseRecoveredFromDisk();
        if (postRecoveryMembers != null) {
          if (updateMembershipView(postRecoveryMembers)) {
            break;
          }
        }

        Set<PersistentMemberID> membersToWaitFor = getPersistedMembers();

        if (!membersToWaitFor.isEmpty()) {
          setWaitingOnMembers(membersToWaitFor, membersToWaitFor);
          try {
            listener.waitForChange();
          } catch (InterruptedException e) {
            interrupted = true;
          }
        } else {
          beginUpdatingPersistentView();
          break;
        }
      }
    } finally {
      setWaitingOnMembers(null, null);
      removeListener(listener);
      if (interrupted) {
        Thread.currentThread().interrupt();
      }
    }
  }

  private boolean updateMembershipView(Collection<InternalDistributedMember> targets) {
    for (InternalDistributedMember target : targets) {
      try {
        updateMembershipView(target, false);
        return true;
      } catch (ReplyException e) {
        // The member left?
        if (logger.isDebugEnabled()) {
          logger.debug("Received a reply exception trying to update membership view", e);
        }
      }
    }
    return false;
  }

  public void bucketRemoved() {
    this.resetState();
  }

  @Override
  public boolean acquireTieLock() {
    // We don't actually need to get a dlock here for PRs, we're already
    // holding the bucket lock when we create a bucket region
    return true;
  }

  @Override
  public void releaseTieLock() {
    // We don't actually need to get a dlock here for PRs, we're already
    // holding the bucket lock when we create a bucket region
  }

  @Override
  protected String getRegionPathForOfflineMembers() {
    return proxyBucket.getPartitionedRegion().getFullPath();
  }

  @Override
  public Set<PersistentMemberID> getMissingMembers() {
    if (recovering) {
      return super.getMissingMembers();
    } else {
      Set<PersistentMemberID> offlineMembers = getPersistedMembers();
      offlineMembers.removeAll(cacheDistributionAdvisor.advisePersistentMembers().values());
      return offlineMembers;
    }
  }

  @Override
  public PersistentMemberID generatePersistentID() {
    PersistentMemberID id = persistentMemberView.generatePersistentID();
    if (id == null) {
      return id;
    } else {
      id = new PersistentMemberID(id.getDiskStoreId(), id.getHost(), id.getDirectory(),
          this.proxyBucket.getPartitionedRegion().getBirthTime(), version++);
      return id;
    }
  }

  private static class RecoveryListener extends PersistentStateAdapter {
    private Set<PersistentMemberID> removedMembers =
        Collections.synchronizedSet(new HashSet<PersistentMemberID>());

    @Override
    public void memberRemoved(PersistentMemberID persistentID, boolean revoked) {
      this.removedMembers.add(persistentID);
    }

    public HashSet<PersistentMemberID> getRemovedMembers() {
      synchronized (removedMembers) {
        return new HashSet<PersistentMemberID>(removedMembers);
      }
    }
  }

  /**
   * Callers should have already verified that debug output is enabled.
   *
   */
  public void dump(String infoMsg) {
    persistentMemberView.getOnlineMembers();
    persistentMemberView.getOfflineMembers();
    persistentMemberView.getOfflineAndEqualMembers();
    persistentMemberView.getMyInitializingID();
    persistentMemberView.getMyPersistentID();
    final StringBuilder buf = new StringBuilder(2000);
    if (infoMsg != null) {
      buf.append(infoMsg);
      buf.append(": ");
    }
    buf.append("\nMY PERSISTENT ID:\n");
    buf.append(persistentMemberView.getMyPersistentID());
    buf.append("\nMY INITIALIZING ID:\n");
    buf.append(persistentMemberView.getMyInitializingID());

    buf.append("\nONLINE MEMBERS:\n");
    for (PersistentMemberID id : persistentMemberView.getOnlineMembers()) {
      buf.append("\t");
      buf.append(id);
      buf.append("\n");
    }

    buf.append("\nOFFLINE MEMBERS:\n");
    for (PersistentMemberID id : persistentMemberView.getOfflineMembers()) {
      buf.append("\t");
      buf.append(id);
      buf.append("\n");
    }

    buf.append("\nOFFLINE AND EQUAL MEMBERS:\n");
    for (PersistentMemberID id : persistentMemberView.getOfflineAndEqualMembers()) {
      buf.append("\t");
      buf.append(id);
      buf.append("\n");
    }
    logger.debug(buf.toString());
  }

  /**
   * Wait for this bucket to be recovered from disk, at least to the point where it starts doing a
   * GII.
   *
   * This method will throw an exception if the recovery thread encountered an exception.
   */
  public void waitForPrimaryPersistentRecovery() {
    boolean interupted = false;
    while (true) {
      try {
        someMemberRecoveredLatch.await();
        break;
      } catch (InterruptedException e) {
        interupted = true;
      }
    }

    if (interupted) {
      Thread.currentThread().interrupt();
    }

    if (recoveryException != null) {
      StackTraceElement[] oldStack = recoveryException.getStackTrace();
      recoveryException.fillInStackTrace();
      ArrayList<StackTraceElement> newStack = new ArrayList<StackTraceElement>();
      newStack.addAll(Arrays.asList(oldStack));
      newStack.addAll(Arrays.asList(recoveryException.getStackTrace()));

      recoveryException.setStackTrace(newStack.toArray(new StackTraceElement[0]));
      throw recoveryException;
    }
  }

  /**
   * Overridden to fix bug 41336. We defer initialization of this member until after the atomic
   * bucket creation phase is over.
   */
  @Override
  public void setInitializing(PersistentMemberID newId) {
    if (atomicCreation) {
      if (logger.isDebugEnabled(LogMarker.PERSIST_ADVISOR_VERBOSE)) {
        logger.debug(LogMarker.PERSIST_ADVISOR_VERBOSE,
            "{}-{}: {} Deferring setInitializing until the EndBucketCreation phase for {}",
            shortDiskStoreId(), regionPath, regionPath, newId);
      }
    } else {
      super.setInitializing(newId);
    }
  }

  /**
   * Overridden to fix bug 41336. We defer initialization of this member until after the atomic
   * bucket creation phase is over.
   */
  @Override
  public void setOnline(boolean didGII, boolean wasAtomicCreation, PersistentMemberID newId)
      throws ReplyException {
    // This is slightly confusing. If we're currently in the middle of an atomic
    // creation, we will do nothing right now. Later, when endBucketCreation
    // is called, we will pass the "wasAtomicCreation" flag down to the super
    // class to ensure that it knows its coming online as part of an atomic creation.
    if (this.atomicCreation) {
      if (logger.isDebugEnabled(LogMarker.PERSIST_ADVISOR_VERBOSE)) {
        logger.debug(LogMarker.PERSIST_ADVISOR_VERBOSE,
            "{}-{}: {} Deferring setOnline until the EndBucketCreation phase for {}",
            shortDiskStoreId(), regionPath, regionPath, newId);
      }
    } else {
      super.setOnline(didGII, wasAtomicCreation, newId);
    }
  }

  /**
   * Finish the atomic creation of this bucket on multiple members This method is called with the
   * proxy bucket synchronized.
   */
  public void endBucketCreation(PersistentMemberID newId) {
    synchronized (lock) {
      if (!atomicCreation) {
        if (logger.isDebugEnabled(LogMarker.PERSIST_ADVISOR_VERBOSE)) {
          logger.debug(LogMarker.PERSIST_ADVISOR_VERBOSE,
              "{}-{}: {} In endBucketCreation - already online, skipping (possible concurrent endBucketCreation)",
              shortDiskStoreId(), regionPath, regionPath);
        }
        return;
      }

      if (logger.isDebugEnabled(LogMarker.PERSIST_ADVISOR_VERBOSE)) {
        logger.debug(LogMarker.PERSIST_ADVISOR_VERBOSE,
            "{}-{}: {} In endBucketCreation - now persisting the id {}", shortDiskStoreId(),
            regionPath, regionPath, newId);
      }
      atomicCreation = false;
    }
    super.setOnline(false, true, newId);
  }

  public boolean isAtomicCreation() {
    return this.atomicCreation;
  }

  public void setAtomicCreation(boolean atomicCreation) {
    if (getPersistentID() != null) {
      return;
    }
    synchronized (lock) {
      this.atomicCreation = atomicCreation;
    }
  }

  private BucketPersistenceAdvisor getColocatedPersistenceAdvisor() {
    PartitionedRegion colocatedRegion =
        ColocationHelper.getColocatedRegion(proxyBucket.getPartitionedRegion());
    if (colocatedRegion == null) {
      return null;
    }
    ProxyBucketRegion colocatedProxyBucket =
        colocatedRegion.getRegionAdvisor().getProxyBucketArray()[proxyBucket.getBucketId()];
    return colocatedProxyBucket.getPersistenceAdvisor();
  }
}