text:
"use strict"

/**@type {Map<string, User>}}*/
let uids = new Map();
/**@type {Map<string, number>}}*/
let utimeOld = new Map();
/**@type {Map<string, number>}}*/
let utimeNew = new Map();
let u404s = new Set();
let chkreports = new StandardDB();
let isRunning = false;
let rowcount = 0;
let curBtn = null;

/**@type {HTMLInputElement}}*/
const aloneRec = $("#aloneRec")[0], autoLoop = $("#autoLoop")[0], wtime = $("#waittime")[0], maxact = $("#maxact")[0], limitdate = $("#limitdate")[0];
let repeatMode = "no";

const thetable = $("#maintable").DataTable(
    {
        paging: true,
        lengthMenu: [[10, 20, 50, -1], [10, 20, 50, "All"]],
        data: [],
        order: [[6, "desc"]],
        columns:
        [
            {
                data: "usr",
                render: displayRender(dat => `<a class="bgopen usr" data-id="${dat.id}" href="https://www.zhihu.com/people/${dat.id}">${dat.name}</a>`)
            },
            {
                data: "status",
                render: displayRender(dat => dat === "ban" ? "停用" : (dat === "sban" ? "永禁言" : "正常?")),
            },
            { data: "artcnt" },
            { data: "anscnt" },
            { data: "follower" },
            { data: "zancnt" },
            { data: "index" }
        ]
    });

/**
 * @param {StandardDB} rec
 */
const bypasser = (rec, uid, lasttime) =>
{
    if (!rec) return;
    utimeOld.set(uid, lasttime);
    if (aloneRec.checked)
    {
        chkreports.add(rec);
        return false;
    }
    else
        return true;
}

async function fastChk(uid, begintime, wailtAll)
{
    ContentBase.BASE_LIM_DATE = new Date(limitdate.value).toUTCSeconds();
    const user = await ContentBase.checkUserState(uid, bypasser, [maxact.value], wailtAll);
    if(curBtn)
    {
        curBtn.style.background = user ? "green" : "red";
    }
    if (!user)
    {
        u404s.add(uid);
        return;
    }
    uids.set(user.id, user);
    utimeNew.set(uid, begintime);
    const newdata = { usr: { id: user.id, name: user.name }, index: rowcount++ };
    Object.assign(newdata, user);
    thetable.row.add(newdata);
    thetable.draw(false);
}

async function monitorCycle(btn, objs)
{
    while (isRunning)
    {
        for (let i = 0; isRunning && i < objs.length; ++i)
        {
            const uid = objs[i];
            btn.textContent = uid;
            let begintime = new Date().toUTCSeconds();
            const sleeper = _sleep(Number(wtime.value));
            let chkpms;
            if (!uids.has(uid))
            {
                if (maxact.value == 0)
                    fastChk(uid, begintime, false);
                else
                    await fastChk(uid, begintime, true);
            }
            else if (maxact.value > 0 || autoLoop.checked)
            {
                const limittime = repeatMode == "new" ? utimeNew.get(uid) : new Date(limitdate.value).toUTCSeconds();
                if (repeatMode == "old")
                    begintime = utimeOld.get(uid);
                else
                    utimeNew.set(uid, begintime);
                const actspms = ContentBase.fetchUserActs(uid, maxact.value, limittime, begintime);
                const user = uids.get(uid);
                const newdata = { usr: { id: user.id, name: user.name }, index: rowcount++ };
                Object.assign(newdata, user);
                thetable.row.add(newdata);
                thetable.draw(false);
                const acts = await actspms;
                utimeOld.set(uid, acts.lasttime);
                if (aloneRec.checked)
                    chkreports.add(acts.acts);
                else
                    ContentBase._report("batch", acts.acts);
            }
            await sleeper;
        }
        if (!autoLoop.checked)
            return;
    }
}

$(document).on("click", "input[name=repeat]:radio", e =>
{
    repeatMode = e.target.value;
});
$(document).on("click", "#show404", e =>
{
    $("#outbox")[0].value = JSON.stringify(u404s.toArray());
});
$(document).on("click", "#showban", e =>
{
    const bans = Array.from(uids.values()).filter(u=>u.status!="").mapToProp("id");
    $("#outbox")[0].value = JSON.stringify(bans);
});
$(document).on("click", "#del404", e =>
{
    u404s.clear();
});
$(document).on("click", "#refresh", e =>
{
    thetable.draw(false);
});
$(document).on("click", "#clean", e =>
{
    chkreports = new StandardDB();
});
$(document).on("click", "#bakstate", e=>
{
    const state =
    {
        users: Array.from(Array.from(uids.values())),
        utimeOld: Array.from(utimeOld.entries()),
        utimeNew: Array.from(utimeNew.entries()),
        u404s: u404s.toArray(),
        chkreports: chkreports,
        input: $("#userinput")[0].value
    };
    const time = new Date().Format("yyyyMMdd-hhmm");
    DownloadMan.exportDownload(state, "json", `AutoSpider-state-${time}.json`);
});
$("body").on("dragover", "#bakstate", ev => ev.preventDefault());
$("body").on("drop", "#bakstate", ev =>
{
    ev.preventDefault();
    const files = ev.originalEvent.dataTransfer.files;
    if (files.length <= 0)
        return;
    const reader = new FileReader();
    reader.onload = e =>
    {
        const content = e.target.result;
        const state = JSON.parse(content);
        console.log(state);
        uids.clear();
        rowcount = 0;
        thetable.clear();
        state.users.forEach(usr =>
        {
           let user = new User();
           Object.assign(user, usr);
           uids.set(user.id, user);
           const newdata = { usr: { id: user.id, name: user.name }, index: rowcount++ };
           Object.assign(newdata, user);
           thetable.row.add(newdata);
        });
        utimeOld = new Map(state.utimeOld);
        utimeNew = new Map(state.utimeNew);
        u404s = new Set(state.u404s);
        Object.assign(chkreports, state.chkreports);
        $("#userinput")[0].value = state.input;
        thetable.draw(false);
    }
    reader.readAsText(files[0]);
});
$(document).on("click", "#export", e =>
{
    const btn = e.target;
    btn.textContent = "合并";
    const res = chkreports.selfMerge();
    btn.textContent = "导出";
    const time = new Date().Format("yyyyMMdd-hhmm");
    DownloadMan.exportDownload(res, "json", `AutoSpider-${time}.json`);
});
$(document).on("click", "#import", ev =>
{
    const btn = ev.target;
    const files = $("#infile")[0].files;
    if (files.length <= 0)
        return;
    const reader = new FileReader();
    reader.onload = e =>
    {
        const content = e.target.result;
        const report = JSON.parse(content);
        console.log(report);
        const details = report.details;
        report.details = [];
        ContentBase._report("batch", report);
        for (let i = 0; i < details.length; i += 5000)
            ContentBase._report("details", details.slice(i, i + 5000));
    }
    reader.readAsText(files[0]);
});
$(document).on("click", "#rfsold,#rfsnew", async e =>
{
    const btn = e.target;
    btn.textContent = "获取中";
    let objs;
    if (e.ctrlKey)
    {
        const txt = $("#userinput")[0].value;
        objs = JSON.parse(txt);
        const banset = (await ContentBase.checkSpam("users", objs)).banned;
        objs = objs.filter(uid => !u404s.has(uid) && banset.has(uid));
    }
    else
    {
        objs = Array.from(uids.values()).filter(u => u.status !== "").mapToProp("id");
    }
    const info = await DBfunc("getAny", "rectime", "id", objs);
    if (btn.id == "rfsold")
    {
        info.forEach(i => utimeOld.set(i.id, i.old));
        btn.textContent = "刷新最旧点";
    }
    else
    {
        info.forEach(i => utimeNew.set(i.id, i.new));
        btn.textContent = "刷新最新点";
    }
});
$(document).on("click", "#chkban", async e =>
{
    const btn = e.target;
    autoLoop.checked = false;
    if (isRunning)
    {
        isRunning = false;
        btn.textContent = "复查封禁";
        return;
    }
    isRunning = true;
    let objs;
    if (e.ctrlKey)
    {
        const txt = $("#userinput")[0].value;
        objs = JSON.parse(txt);
        const banset = (await ContentBase.checkSpam("users", objs)).banned;
        objs = objs.filter(uid => !u404s.has(uid) && banset.has(uid));
        const usrs = await DBfunc("getAny", "users", "id", objs);
        usrs.forEach(usr => uids.set(usr.id, usr));
    }
    else
    {
        objs = Array.from(uids.values()).filter(u => u.status !== "").mapToProp("id");
    }
    console.log(`here [${objs.length}] obj users`);

    await monitorCycle(btn, objs);

    isRunning = false;
    btn.textContent = "完毕";
});

$(document).on("click", "#go", async e =>
{
    const btn = e.target;
    if (isRunning)
    {
        isRunning = false;
        btn.textContent = "开始";
        return;
    }
    isRunning = true;
    curBtn = btn;
    const isCtrl = e.ctrlKey;
    try
    {
        const txt = $("#userinput")[0].value;
        let objs = JSON.parse(txt);
        if (repeatMode == "no")
            objs = objs.filter(uid => !uids.has(uid));
        const banset = isCtrl ? new Set() : (await ContentBase.checkSpam("users", objs)).banned;
        objs = objs.filter(uid => !u404s.has(uid) && !banset.has(uid));
        console.log(`here [${objs.length}] obj users`);

        await monitorCycle(btn, objs);

        isRunning = false;
        btn.textContent = "完毕";
    }
    catch (e)
    {
        console.warn(e);
        isRunning = false;
        curBtn.style.background = "";
        curBtn = null;
    }
});


text:
package org.springframework.expression.spel.support;

import org.springframework.expression.TypedValue;

/**
 * @author Andy Clement
 * @since 3.0
 */
public class BooleanTypedValue extends TypedValue {

	public static final BooleanTypedValue TRUE = new BooleanTypedValue(true);

	public static final BooleanTypedValue FALSE = new BooleanTypedValue(false);

	private BooleanTypedValue(boolean b) {
		super(b);
	}

	public static BooleanTypedValue forValue(boolean b) {
		return (b ? TRUE : FALSE);
	}

}

redpajama_set_name: RedPajamaGithub


text:
package awsmodel

import (
	"fmt"
	"sort"
	"strings"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/ec2"
	"k8s.io/klog/v2"
	"k8s.io/kops/pkg/apis/kops"
	"k8s.io/kops/pkg/featureflag"
	"k8s.io/kops/pkg/model"
	"k8s.io/kops/pkg/model/defaults"
	"k8s.io/kops/upup/pkg/fi"
	"k8s.io/kops/upup/pkg/fi/cloudup/awstasks"
	"k8s.io/kops/upup/pkg/fi/cloudup/awsup"
)

const (
	// DefaultVolumeType is the default volume type
	DefaultVolumeType = ec2.VolumeTypeGp3
	// DefaultVolumeIonIops is the default volume IOPS when volume type is io1 or io2
	DefaultVolumeIonIops = 100
	// DefaultVolumeGp3Iops is the default volume IOPS when volume type is gp3
	DefaultVolumeGp3Iops = 3000
	// DefaultVolumeGp3Throughput is the default volume throughput when volume type is gp3
	DefaultVolumeGp3Throughput = 125
	// DefaultVolumeDeleteOnTermination is the default volume behavior after instance termination
	DefaultVolumeDeleteOnTermination = true
	// DefaultVolumeEncryption is the default volume encryption behavior
	DefaultVolumeEncryption = true
)

// AutoscalingGroupModelBuilder configures AutoscalingGroup objects
type AutoscalingGroupModelBuilder struct {
	*AWSModelContext

	BootstrapScriptBuilder *model.BootstrapScriptBuilder
	Lifecycle              fi.Lifecycle
	SecurityLifecycle      fi.Lifecycle
	Cluster                *kops.Cluster
}

var _ fi.ModelBuilder = &AutoscalingGroupModelBuilder{}

// Build is responsible for constructing the aws autoscaling group from the kops spec
func (b *AutoscalingGroupModelBuilder) Build(c *fi.ModelBuilderContext) error {
	for _, ig := range b.InstanceGroups {
		name := b.AutoscalingGroupName(ig)

		if featureflag.SpotinstHybrid.Enabled() {
			if HybridInstanceGroup(ig) {
				klog.V(2).Infof("Skipping instance group: %q", name)
				continue
			}
		}

		task, err := b.buildLaunchTemplateTask(c, name, ig)
		if err != nil {
			return err
		}
		c.AddTask(task)

		// @step: now lets build the autoscaling group task
		tsk, err := b.buildAutoScalingGroupTask(c, name, ig)
		if err != nil {
			return err
		}
		tsk.LaunchTemplate = task
		c.AddTask(tsk)

		warmPool := b.Cluster.Spec.WarmPool.ResolveDefaults(ig)
		{
			enabled := fi.Bool(warmPool.IsEnabled())
			warmPoolTask := &awstasks.WarmPool{
				Name:      &name,
				Lifecycle: b.Lifecycle,
				Enabled:   enabled,
			}
			if warmPool.IsEnabled() {
				warmPoolTask.MinSize = warmPool.MinSize
				warmPoolTask.MaxSize = warmPool.MaxSize

				if warmPool.EnableLifecycleHook {
					hookName := "kops-warmpool"
					name := fmt.Sprintf("%s-%s", hookName, ig.GetName())

					lifecyleTask := &awstasks.AutoscalingLifecycleHook{
						ID:               aws.String(name),
						Name:             aws.String(name),
						HookName:         aws.String(hookName),
						Lifecycle:        b.Lifecycle,
						AutoscalingGroup: b.LinkToAutoscalingGroup(ig),
						DefaultResult:    aws.String("ABANDON"),
						// We let nodeup have 10 min to complete. Normally this should happen much faster,
						// but CP nodes need 5 min or so to start on new clusters, and we need to wait for that.
						HeartbeatTimeout:    aws.Int64(600),
						LifecycleTransition: aws.String("autoscaling:EC2_INSTANCE_LAUNCHING"),
					}

					c.AddTask(lifecyleTask)

				}

			}
			c.AddTask(warmPoolTask)
		}
	}

	return nil
}

// buildLaunchTemplateTask is responsible for creating the template task into the aws model
func (b *AutoscalingGroupModelBuilder) buildLaunchTemplateTask(c *fi.ModelBuilderContext, name string, ig *kops.InstanceGroup) (*awstasks.LaunchTemplate, error) {
	// @step: add the iam instance profile
	link, err := b.LinkToIAMInstanceProfile(ig)
	if err != nil {
		return nil, fmt.Errorf("unable to find IAM profile link for instance group %q: %w", ig.ObjectMeta.Name, err)
	}

	rootVolumeSize, err := defaults.DefaultInstanceGroupVolumeSize(ig.Spec.Role)
	if err != nil {
		return nil, err
	}
	if fi.Int32Value(ig.Spec.RootVolumeSize) > 0 {
		rootVolumeSize = fi.Int32Value(ig.Spec.RootVolumeSize)
	}

	rootVolumeType := fi.StringValue(ig.Spec.RootVolumeType)
	if rootVolumeType == "" {
		rootVolumeType = DefaultVolumeType
	}

	rootVolumeEncryption := DefaultVolumeEncryption
	if ig.Spec.RootVolumeEncryption != nil {
		rootVolumeEncryption = fi.BoolValue(ig.Spec.RootVolumeEncryption)
	}

	rootVolumeKmsKey := ""
	if fi.BoolValue(ig.Spec.RootVolumeEncryption) && ig.Spec.RootVolumeEncryptionKey != nil {
		rootVolumeKmsKey = *ig.Spec.RootVolumeEncryptionKey
	}

	securityGroups, err := b.buildSecurityGroups(c, ig)
	if err != nil {
		return nil, err
	}

	tags, err := b.CloudTagsForInstanceGroup(ig)
	if err != nil {
		return nil, fmt.Errorf("error building cloud tags: %v", err)
	}

	userData, err := b.BootstrapScriptBuilder.ResourceNodeUp(c, ig)
	if err != nil {
		return nil, err
	}

	lt := &awstasks.LaunchTemplate{
		Name:                         fi.String(name),
		Lifecycle:                    b.Lifecycle,
		CPUCredits:                   fi.String(fi.StringValue(ig.Spec.CPUCredits)),
		HTTPPutResponseHopLimit:      fi.Int64(1),
		HTTPTokens:                   fi.String(ec2.LaunchTemplateHttpTokensStateOptional),
		HTTPProtocolIPv6:             fi.String(ec2.LaunchTemplateInstanceMetadataProtocolIpv6Disabled),
		IAMInstanceProfile:           link,
		ImageID:                      fi.String(ig.Spec.Image),
		InstanceInterruptionBehavior: ig.Spec.InstanceInterruptionBehavior,
		InstanceMonitoring:           fi.Bool(false),
		InstanceType:                 fi.String(strings.Split(ig.Spec.MachineType, ",")[0]),
		IPv6AddressCount:             fi.Int64(0),
		RootVolumeIops:               fi.Int64(int64(fi.Int32Value(ig.Spec.RootVolumeIops))),
		RootVolumeOptimization:       ig.Spec.RootVolumeOptimization,
		RootVolumeSize:               fi.Int64(int64(rootVolumeSize)),
		RootVolumeType:               fi.String(rootVolumeType),
		RootVolumeEncryption:         fi.Bool(rootVolumeEncryption),
		RootVolumeKmsKey:             fi.String(rootVolumeKmsKey),
		SecurityGroups:               securityGroups,
		Tags:                         tags,
		UserData:                     userData,
	}

	{
		// @step: check the subnets are ok and pull together an array for us
		subnets, err := b.GatherSubnets(ig)
		if err != nil {
			return nil, err
		}

		// @step: check if we can add an public ip to this subnet
		switch subnets[0].Type {
		case kops.SubnetTypePublic, kops.SubnetTypeUtility:
			lt.AssociatePublicIP = fi.Bool(true)
			if ig.Spec.AssociatePublicIP != nil {
				lt.AssociatePublicIP = ig.Spec.AssociatePublicIP
			}
		case kops.SubnetTypePrivate:
			lt.AssociatePublicIP = fi.Bool(false)
		}

		// @step: add an IPv6 address
		for _, clusterSubnet := range b.Cluster.Spec.Subnets {
			for _, igSubnet := range ig.Spec.Subnets {
				if clusterSubnet.Name != igSubnet {
					continue
				}
				if clusterSubnet.IPv6CIDR != "" {
					lt.IPv6AddressCount = fi.Int64(1)
					lt.HTTPProtocolIPv6 = fi.String(ec2.LaunchTemplateInstanceMetadataProtocolIpv6Enabled)
				}
			}
		}
	}

	// @step: add any additional block devices
	for i := range ig.Spec.Volumes {
		x := &ig.Spec.Volumes[i]
		if x.Type == "" {
			x.Type = DefaultVolumeType
		}
		if x.Type == ec2.VolumeTypeIo1 || x.Type == ec2.VolumeTypeIo2 {
			if x.Iops == nil {
				x.Iops = fi.Int64(DefaultVolumeIonIops)
			}
		} else if x.Type == ec2.VolumeTypeGp3 {
			if x.Iops == nil {
				x.Iops = fi.Int64(DefaultVolumeGp3Iops)
			}
			if x.Throughput == nil {
				x.Throughput = fi.Int64(DefaultVolumeGp3Throughput)
			}
		} else {
			x.Iops = nil
		}
		deleteOnTermination := DefaultVolumeDeleteOnTermination
		if x.DeleteOnTermination != nil {
			deleteOnTermination = fi.BoolValue(x.DeleteOnTermination)
		}
		encryption := DefaultVolumeEncryption
		if x.Encrypted != nil {
			encryption = fi.BoolValue(x.Encrypted)
		}
		lt.BlockDeviceMappings = append(lt.BlockDeviceMappings, &awstasks.BlockDeviceMapping{
			DeviceName:             fi.String(x.Device),
			EbsDeleteOnTermination: fi.Bool(deleteOnTermination),
			EbsEncrypted:           fi.Bool(encryption),
			EbsKmsKey:              x.Key,
			EbsVolumeIops:          x.Iops,
			EbsVolumeSize:          fi.Int64(x.Size),
			EbsVolumeThroughput:    x.Throughput,
			EbsVolumeType:          fi.String(x.Type),
		})
	}

	if ig.Spec.DetailedInstanceMonitoring != nil {
		lt.InstanceMonitoring = ig.Spec.DetailedInstanceMonitoring
	}

	if ig.Spec.InstanceMetadata != nil && ig.Spec.InstanceMetadata.HTTPPutResponseHopLimit != nil {
		lt.HTTPPutResponseHopLimit = ig.Spec.InstanceMetadata.HTTPPutResponseHopLimit
	}

	if ig.Spec.InstanceMetadata != nil && ig.Spec.InstanceMetadata.HTTPTokens != nil {
		lt.HTTPTokens = ig.Spec.InstanceMetadata.HTTPTokens
	}

	if rootVolumeType == ec2.VolumeTypeIo1 || rootVolumeType == ec2.VolumeTypeIo2 {
		if fi.Int32Value(ig.Spec.RootVolumeIops) < 100 {
			lt.RootVolumeIops = fi.Int64(int64(DefaultVolumeIonIops))
		}
	} else if rootVolumeType == ec2.VolumeTypeGp3 {
		if fi.Int32Value(ig.Spec.RootVolumeIops) < 3000 {
			lt.RootVolumeIops = fi.Int64(int64(DefaultVolumeGp3Iops))
		}
		if fi.Int32Value(ig.Spec.RootVolumeThroughput) < 125 {
			lt.RootVolumeThroughput = fi.Int64(int64(DefaultVolumeGp3Throughput))
		} else {
			lt.RootVolumeThroughput = fi.Int64(int64(fi.Int32Value(ig.Spec.RootVolumeThroughput)))
		}
	} else {
		lt.RootVolumeIops = nil
	}

	if b.AWSModelContext.UseSSHKey() {
		if lt.SSHKey, err = b.LinkToSSHKey(); err != nil {
			return nil, err
		}
	}

	// When using a MixedInstances ASG, AWS requires the SpotPrice be defined on the ASG
	// rather than the LaunchTemplate or else it returns this error:
	//   You cannot use a launch template that is set to request Spot Instances (InstanceMarketOptions)
	//   when you configure an Auto Scaling group with a mixed instances policy.
	if ig.Spec.MixedInstancesPolicy == nil && ig.Spec.MaxPrice != nil {
		lt.SpotPrice = ig.Spec.MaxPrice
	} else {
		lt.SpotPrice = fi.String("")
	}
	if ig.Spec.SpotDurationInMinutes != nil {
		lt.SpotDurationInMinutes = ig.Spec.SpotDurationInMinutes
	}

	if ig.Spec.Tenancy != "" {
		lt.Tenancy = fi.String(ig.Spec.Tenancy)
	}

	return lt, nil
}

// buildSecurityGroups is responsible for building security groups for a launch template.
func (b *AutoscalingGroupModelBuilder) buildSecurityGroups(c *fi.ModelBuilderContext, ig *kops.InstanceGroup) ([]*awstasks.SecurityGroup, error) {
	// @step: if required we add the override for the security group for this instancegroup
	sgLink := b.LinkToSecurityGroup(ig.Spec.Role)
	if ig.Spec.SecurityGroupOverride != nil {
		sgName := fmt.Sprintf("%v-%v", fi.StringValue(ig.Spec.SecurityGroupOverride), ig.Spec.Role)
		sgLink = &awstasks.SecurityGroup{
			ID:     ig.Spec.SecurityGroupOverride,
			Name:   &sgName,
			Shared: fi.Bool(true),
		}
	}

	securityGroups := []*awstasks.SecurityGroup{sgLink}

	if ig.HasAPIServer() &&
		b.APILoadBalancerClass() == kops.LoadBalancerClassNetwork {
		for _, id := range b.Cluster.Spec.API.LoadBalancer.AdditionalSecurityGroups {
			sgTask := &awstasks.SecurityGroup{
				ID:        fi.String(id),
				Lifecycle: b.SecurityLifecycle,
				Name:      fi.String("nlb-" + id),
				Shared:    fi.Bool(true),
			}
			if err := c.EnsureTask(sgTask); err != nil {
				return nil, err
			}
			securityGroups = append(securityGroups, sgTask)
		}
	}

	// @step: add any additional security groups to the instancegroup
	for _, id := range ig.Spec.AdditionalSecurityGroups {
		sgTask := &awstasks.SecurityGroup{
			ID:        fi.String(id),
			Lifecycle: b.SecurityLifecycle,
			Name:      fi.String(id),
			Shared:    fi.Bool(true),
		}
		if err := c.EnsureTask(sgTask); err != nil {
			return nil, err
		}
		securityGroups = append(securityGroups, sgTask)
	}

	return securityGroups, nil
}

// buildAutoscalingGroupTask is responsible for building the autoscaling task into the model
func (b *AutoscalingGroupModelBuilder) buildAutoScalingGroupTask(c *fi.ModelBuilderContext, name string, ig *kops.InstanceGroup) (*awstasks.AutoscalingGroup, error) {

	t := &awstasks.AutoscalingGroup{
		Name:      fi.String(name),
		Lifecycle: b.Lifecycle,

		Granularity: fi.String("1Minute"),
		Metrics: []string{
			"GroupDesiredCapacity",
			"GroupInServiceInstances",
			"GroupMaxSize",
			"GroupMinSize",
			"GroupPendingInstances",
			"GroupStandbyInstances",
			"GroupTerminatingInstances",
			"GroupTotalInstances",
		},

		InstanceProtection: fi.Bool(false),
	}

	minSize := fi.Int64(1)
	maxSize := fi.Int64(1)
	if ig.Spec.MinSize != nil {
		minSize = fi.Int64(int64(*ig.Spec.MinSize))
	} else if ig.Spec.Role == kops.InstanceGroupRoleNode {
		minSize = fi.Int64(2)
	}
	if ig.Spec.MaxSize != nil {
		maxSize = fi.Int64(int64(*ig.Spec.MaxSize))
	} else if ig.Spec.Role == kops.InstanceGroupRoleNode {
		maxSize = fi.Int64(2)
	}

	t.MinSize = minSize
	t.MaxSize = maxSize

	subnets, err := b.GatherSubnets(ig)
	if err != nil {
		return nil, err
	}
	if len(subnets) == 0 {
		return nil, fmt.Errorf("could not determine any subnets for InstanceGroup %q; subnets was %s", ig.ObjectMeta.Name, ig.Spec.Subnets)
	}
	for _, subnet := range subnets {
		t.Subnets = append(t.Subnets, b.LinkToSubnet(subnet))
	}

	tags, err := b.CloudTagsForInstanceGroup(ig)
	if err != nil {
		return nil, fmt.Errorf("error building cloud tags: %v", err)
	}
	t.Tags = tags

	processes := []string{}
	processes = append(processes, ig.Spec.SuspendProcesses...)
	t.SuspendProcesses = &processes

	if ig.Spec.InstanceProtection != nil {
		t.InstanceProtection = ig.Spec.InstanceProtection
	}

	t.LoadBalancers = []*awstasks.ClassicLoadBalancer{}
	t.TargetGroups = []*awstasks.TargetGroup{}

	// Spotinst handles load balancer attachments internally, so there's no
	// need to create separate attachments for both managed (+Spotinst) and
	// hybrid (+SpotinstHybrid) instance groups.
	if !featureflag.Spotinst.Enabled() ||
		(featureflag.SpotinstHybrid.Enabled() && !HybridInstanceGroup(ig)) {
		if b.UseLoadBalancerForAPI() && ig.HasAPIServer() {
			if b.UseNetworkLoadBalancer() {
				t.TargetGroups = append(t.TargetGroups, b.LinkToTargetGroup("tcp"))
				if b.Cluster.Spec.API.LoadBalancer.SSLCertificate != "" {
					t.TargetGroups = append(t.TargetGroups, b.LinkToTargetGroup("tls"))
				}
			} else {
				t.LoadBalancers = append(t.LoadBalancers, b.LinkToCLB("api"))
			}
		}

		if ig.Spec.Role == kops.InstanceGroupRoleBastion {
			t.LoadBalancers = append(t.LoadBalancers, b.LinkToCLB("bastion"))
		}
	}

	for _, extLB := range ig.Spec.ExternalLoadBalancers {
		if extLB.LoadBalancerName != nil {
			lb := &awstasks.ClassicLoadBalancer{
				Name:             extLB.LoadBalancerName,
				Lifecycle:        b.Lifecycle,
				LoadBalancerName: extLB.LoadBalancerName,
				Shared:           fi.Bool(true),
			}
			t.LoadBalancers = append(t.LoadBalancers, lb)
			c.EnsureTask(lb)
		}

		if extLB.TargetGroupARN != nil {
			targetGroupName, err := awsup.GetTargetGroupNameFromARN(fi.StringValue(extLB.TargetGroupARN))
			if err != nil {
				return nil, err
			}
			tg := &awstasks.TargetGroup{
				Name:      fi.String(name + "-" + targetGroupName),
				Lifecycle: b.Lifecycle,
				ARN:       extLB.TargetGroupARN,
				Shared:    fi.Bool(true),
			}
			t.TargetGroups = append(t.TargetGroups, tg)
			c.AddTask(tg)
		}
	}
	sort.Stable(awstasks.OrderLoadBalancersByName(t.LoadBalancers))
	sort.Stable(awstasks.OrderTargetGroupsByName(t.TargetGroups))

	// @step: are we using a mixed instance policy
	if ig.Spec.MixedInstancesPolicy != nil {
		spec := ig.Spec.MixedInstancesPolicy

		t.MixedInstanceOverrides = spec.Instances
		t.MixedOnDemandAboveBase = spec.OnDemandAboveBase
		t.MixedOnDemandAllocationStrategy = spec.OnDemandAllocationStrategy
		t.MixedOnDemandBase = spec.OnDemandBase
		t.MixedSpotAllocationStrategy = spec.SpotAllocationStrategy
		t.MixedSpotInstancePools = spec.SpotInstancePools
		t.MixedSpotMaxPrice = ig.Spec.MaxPrice
	}

	return t, nil
}


text:
enum GameRaycastFlags : uint32_t {
	GRF_HITTEST_SEL_CIRCLE = 1,
	GRF_HITTEST_CYLINDER = 2, // this is set as a default
	GRF_HITTEST_MESH = 4, // this is set as a default - looks like "Get radius from Aas"
	GRF_HITTEST_3D = 6,
	GRF_ExcludeScenery = 8,
	GRF_ExcludeItems = 16,
	GRF_ExcludePortals = 32,
	GRF_ExcludeContainers = 64,
	GRF_ExcludeCritters = 0x80,
	GRF_ExcludeDead = 0x100,
	GRF_ExcludeUnconscious = 0x200
};

inline GameRaycastFlags operator|(GameRaycastFlags lhs, GameRaycastFlags rhs) {
	return static_cast<GameRaycastFlags>(static_cast<uint32_t>(lhs) | static_cast<uint32_t>(rhs));
}

enum RaycastFlags : uint32_t // used in the ObjIterator
{
	HasToBeCleared = 1,
	HasRadius = 2,
	HasSourceObj = 4,
	ExcludeItemObjects = 8, // excludes obj_t_weapon through obj_t_gneric and obj_t_bag
	StopAfterFirstBlockerFound = 0x10, // probably a performance optimization; also probably a source of bugs!
	StopAfterFirstFlyoverFound = 0x20,
	RequireDistToSourceLessThanTargetDist = 0x40, // I think this flag has another more general role, not quite sure yet
	HasRangeLimit = 0x80,
	HasTargetObj = 0x100,
	GetObjIntersection =0x200, // will return the first point along the ray where it intersects with the found object/tile
	IgnoreFlyover = 0x400, // probably used for LOS or archery queries
	ExcludePortals = 0x800, // doors etc.
	FoundCoverProvider = 0x80000000 // subtile marked as Blocker OR (FlyOver AND Cover)
};

enum RaycastResultFlags : int
{
	RaycastResultFlag1 = 1,
	BlockerSubtile = 2,
	FlyoverSubtile = 4,
	RaycastResultFlag8 = 8
};

struct RaycastResultItem
{
	int flags;
	int field4;
	LocAndOffsets loc;
	objHndl obj;
	LocAndOffsets intersectionPoint;
	float intersectionDistance; // dist from origin along the line where the object/tile intersects with the ray
	int field34;
};

struct RaycastPacket
{
	RaycastFlags flags;
	int field4;
	LocAndOffsets origin;
	LocAndOffsets targetLoc;
	float radius;
	int field2C;
	objHndl sourceObj;
	objHndl target;
	float rayRangeInches; // limits the distance from the origin
	RaycastResultItem * results;
	int resultCount;
	RaycastPacket()
	{
		this->flags = HasToBeCleared;
		this->resultCount = 0;
		this->results = 0;
		this->origin.location.locx = 0;
		this->origin.location.locy = 0;
		this->origin.off_x = 0;
		this->origin.off_y = 0;
		this->targetLoc.location.locx = 0;
		this->targetLoc.location.locy = 0;
		this->targetLoc.off_x = 0;
		this->targetLoc.off_y = 0;
	}

	int Raycast();
	int RaycastShortRange();
	void RaycastPacketFree();
	~RaycastPacket();
};

struct RaycastPointSearchPacket
{
	float originAbsX;
	float originAbsY;
	float targetAbsX;
	float targetAbsY;
	float ux; //normalized direction x component
	float uy;
	float rangeInch;
	float absOdotU; // dot product of the origin point and the direction vector, normalized by the direction vector norm
	float radius;

	RaycastPointSearchPacket(const XMFLOAT2 &origin, const XMFLOAT2 &endPt);
	bool IsPointInterceptedBySegment(const XMFLOAT2 &v, float objRadius);
};

struct PointAlongSegment
{
	float absX;
	float absY;
	float distFromOrigin;
};

bool PickObjectOnScreen(int x, int y, objHndl *pickedHandle, GameRaycastFlags flags);


text:
cask 'freesmug-chromium' do
  version '71.0.3578.80'
  sha256 '0957ca27279b07450d229eb9e558690c05a1e6cf92dd7e8e728b982a7c9ac574'

  # sourceforge.net/osxportableapps was verified as official when first introduced to the cask
  url "https://downloads.sourceforge.net/osxportableapps/Chromium_OSX_#{version}.dmg"
  appcast 'https://sourceforge.net/projects/osxportableapps/rss?path=/Chromium'
  name 'Chromium'
  homepage 'http://www.freesmug.org/chromium'

  app 'Chromium.app'
end


text:
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
import './renameInputField.css';
import { DisposableStore } from '../../../base/common/lifecycle';
import { Position } from '../../common/core/position';
import { Range } from '../../common/core/range';
import { localize } from '../../../nls';
import { IContextKeyService, RawContextKey } from '../../../platform/contextkey/common/contextkey';
import { inputBackground, inputBorder, inputForeground, widgetShadow, editorWidgetBackground } from '../../../platform/theme/common/colorRegistry';
import { IThemeService } from '../../../platform/theme/common/themeService';
import { IKeybindingService } from '../../../platform/keybinding/common/keybinding';
import { toggleClass } from '../../../base/browser/dom';
export var CONTEXT_RENAME_INPUT_VISIBLE = new RawContextKey('renameInputVisible', false);
var RenameInputField = /** @class */ (function () {
    function RenameInputField(_editor, _acceptKeybindings, _themeService, _keybindingService, contextKeyService) {
        var _this = this;
        this._editor = _editor;
        this._acceptKeybindings = _acceptKeybindings;
        this._themeService = _themeService;
        this._keybindingService = _keybindingService;
        this._disposables = new DisposableStore();
        this.allowEditorOverflow = true;
        this._visibleContextKey = CONTEXT_RENAME_INPUT_VISIBLE.bindTo(contextKeyService);
        this._editor.addContentWidget(this);
        this._disposables.add(this._editor.onDidChangeConfiguration(function (e) {
            if (e.hasChanged(34 /* fontInfo */)) {
                _this._updateFont();
            }
        }));
        this._disposables.add(_themeService.onThemeChange(this._updateStyles, this));
    }
    RenameInputField.prototype.dispose = function () {
        this._disposables.dispose();
        this._editor.removeContentWidget(this);
    };
    RenameInputField.prototype.getId = function () {
        return '__renameInputWidget';
    };
    RenameInputField.prototype.getDomNode = function () {
        var _this = this;
        if (!this._domNode) {
            this._domNode = document.createElement('div');
            this._domNode.className = 'monaco-editor rename-box';
            this._input = document.createElement('input');
            this._input.className = 'rename-input';
            this._input.type = 'text';
            this._input.setAttribute('aria-label', localize('renameAriaLabel', "Rename input. Type new name and press Enter to commit."));
            this._domNode.appendChild(this._input);
            this._label = document.createElement('div');
            this._label.className = 'rename-label';
            this._domNode.appendChild(this._label);
            var updateLabel = function () {
                var _a, _b;
                var _c = _this._acceptKeybindings, accept = _c[0], preview = _c[1];
                _this._keybindingService.lookupKeybinding(accept);
                _this._label.innerText = localize('label', "{0} to Rename, {1} to Preview", (_a = _this._keybindingService.lookupKeybinding(accept)) === null || _a === void 0 ? void 0 : _a.getLabel(), (_b = _this._keybindingService.lookupKeybinding(preview)) === null || _b === void 0 ? void 0 : _b.getLabel());
            };
            updateLabel();
            this._disposables.add(this._keybindingService.onDidUpdateKeybindings(updateLabel));
            this._updateFont();
            this._updateStyles(this._themeService.getTheme());
        }
        return this._domNode;
    };
    RenameInputField.prototype._updateStyles = function (theme) {
        var _a, _b, _c, _d;
        if (!this._input || !this._domNode) {
            return;
        }
        var widgetShadowColor = theme.getColor(widgetShadow);
        this._domNode.style.backgroundColor = String((_a = theme.getColor(editorWidgetBackground)) !== null && _a !== void 0 ? _a : '');
        this._domNode.style.boxShadow = widgetShadowColor ? " 0 2px 8px " + widgetShadowColor : '';
        this._domNode.style.color = String((_b = theme.getColor(inputForeground)) !== null && _b !== void 0 ? _b : '');
        this._input.style.backgroundColor = String((_c = theme.getColor(inputBackground)) !== null && _c !== void 0 ? _c : '');
        // this._input.style.color = String(theme.getColor(inputForeground) ?? '');
        var border = theme.getColor(inputBorder);
        this._input.style.borderWidth = border ? '1px' : '0px';
        this._input.style.borderStyle = border ? 'solid' : 'none';
        this._input.style.borderColor = (_d = border === null || border === void 0 ? void 0 : border.toString()) !== null && _d !== void 0 ? _d : 'none';
    };
    RenameInputField.prototype._updateFont = function () {
        if (!this._input || !this._label) {
            return;
        }
        var fontInfo = this._editor.getOption(34 /* fontInfo */);
        this._input.style.fontFamily = fontInfo.fontFamily;
        this._input.style.fontWeight = fontInfo.fontWeight;
        this._input.style.fontSize = fontInfo.fontSize + "px";
        this._label.style.fontSize = fontInfo.fontSize * 0.8 + "px";
    };
    RenameInputField.prototype.getPosition = function () {
        if (!this._visible) {
            return null;
        }
        return {
            position: this._position,
            preference: [2 /* BELOW */, 1 /* ABOVE */]
        };
    };
    RenameInputField.prototype.acceptInput = function (wantsPreview) {
        if (this._currentAcceptInput) {
            this._currentAcceptInput(wantsPreview);
        }
    };
    RenameInputField.prototype.cancelInput = function (focusEditor) {
        if (this._currentCancelInput) {
            this._currentCancelInput(focusEditor);
        }
    };
    RenameInputField.prototype.getInput = function (where, value, selectionStart, selectionEnd, supportPreview) {
        var _this = this;
        toggleClass(this._domNode, 'preview', supportPreview);
        this._position = new Position(where.startLineNumber, where.startColumn);
        this._input.value = value;
        this._input.setAttribute('selectionStart', selectionStart.toString());
        this._input.setAttribute('selectionEnd', selectionEnd.toString());
        this._input.size = Math.max((where.endColumn - where.startColumn) * 1.1, 20);
        var disposeOnDone = new DisposableStore();
        return new Promise(function (resolve) {
            _this._currentCancelInput = function (focusEditor) {
                _this._currentAcceptInput = undefined;
                _this._currentCancelInput = undefined;
                resolve(focusEditor);
                return true;
            };
            _this._currentAcceptInput = function (wantsPreview) {
                if (_this._input.value.trim().length === 0 || _this._input.value === value) {
                    // empty or whitespace only or not changed
                    _this.cancelInput(true);
                    return;
                }
                _this._currentAcceptInput = undefined;
                _this._currentCancelInput = undefined;
                resolve({
                    newName: _this._input.value,
                    wantsPreview: supportPreview && wantsPreview
                });
            };
            var onCursorChanged = function () {
                var editorPosition = _this._editor.getPosition();
                if (!editorPosition || !Range.containsPosition(where, editorPosition)) {
                    _this.cancelInput(true);
                }
            };
            disposeOnDone.add(_this._editor.onDidChangeCursorSelection(onCursorChanged));
            disposeOnDone.add(_this._editor.onDidBlurEditorWidget(function () { return _this.cancelInput(false); }));
            _this._show();
        }).finally(function () {
            disposeOnDone.dispose();
            _this._hide();
        });
    };
    RenameInputField.prototype._show = function () {
        var _this = this;
        this._editor.revealLineInCenterIfOutsideViewport(this._position.lineNumber, 0 /* Smooth */);
        this._visible = true;
        this._visibleContextKey.set(true);
        this._editor.layoutContentWidget(this);
        setTimeout(function () {
            _this._input.focus();
            _this._input.setSelectionRange(parseInt(_this._input.getAttribute('selectionStart')), parseInt(_this._input.getAttribute('selectionEnd')));
        }, 100);
    };
    RenameInputField.prototype._hide = function () {
        this._visible = false;
        this._visibleContextKey.reset();
        this._editor.layoutContentWidget(this);
    };
    RenameInputField = __decorate([
        __param(2, IThemeService),
        __param(3, IKeybindingService),
        __param(4, IContextKeyService)
    ], RenameInputField);
    return RenameInputField;
}());
export { RenameInputField };


text:
import dis
import os.path
import re
import subprocess
import sys
import types
import unittest

from test.support import findfile, run_unittest

def abspath(filename):
    return os.path.abspath(findfile(filename, subdir="dtracedata"))

def normalize_trace_output(output):
    """Normalize DTrace output for comparison.

    DTrace keeps a per-CPU buffer, and when showing the fired probes, buffers
    are concatenated. So if the operating system moves our thread around, the
    straight result can be "non-causal". So we add timestamps to the probe
    firing, sort by that field, then strip it from the output"""

    # When compiling with '--with-pydebug', strip '[# refs]' debug output.
    output = re.sub(r"\[[0-9]+ refs\]", "", output)
    try:
        result = [
            row.split("\t")
            for row in output.splitlines()
            if row and not row.startswith('#')
        ]
        result.sort(key=lambda row: int(row[0]))
        result = [row[1] for row in result]
        return "\n".join(result)
    except (IndexError, ValueError):
        raise AssertionError(
            "tracer produced unparseable output:\n{}".format(output)
        )

class TraceBackend:
    EXTENSION = None
    COMMAND = None
    COMMAND_ARGS = []

    def run_case(self, name, optimize_python=None):
        actual_output = normalize_trace_output(self.trace_python(
            script_file=abspath(name + self.EXTENSION),
            python_file=abspath(name + ".py"),
            optimize_python=optimize_python))

        with open(abspath(name + self.EXTENSION + ".expected")) as f:
            expected_output = f.read().rstrip()

        return (expected_output, actual_output)

    def generate_trace_command(self, script_file, subcommand=None):
        command = self.COMMAND + [script_file]
        if subcommand:
            command += ["-c", subcommand]
        return command

    def trace(self, script_file, subcommand=None):
        command = self.generate_trace_command(script_file, subcommand)
        stdout, _ = subprocess.Popen(command,
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.STDOUT,
                                     universal_newlines=True).communicate()
        return stdout

    def trace_python(self, script_file, python_file, optimize_python=None):
        python_flags = []
        if optimize_python:
            python_flags.extend(["-O"] * optimize_python)
        subcommand = " ".join([sys.executable] + python_flags + [python_file])
        return self.trace(script_file, subcommand)

    def assert_usable(self):
        try:
            output = self.trace(abspath("assert_usable" + self.EXTENSION))
            output = output.strip()
        except (FileNotFoundError, NotADirectoryError, PermissionError) as fnfe:
            output = str(fnfe)
        if output != "probe: success":
            raise unittest.SkipTest(
                "{}(1) failed: {}".format(self.COMMAND[0], output)
            )

class DTraceBackend(TraceBackend):
    EXTENSION = ".d"
    COMMAND = ["dtrace", "-q", "-s"]

class SystemTapBackend(TraceBackend):
    EXTENSION = ".stp"
    COMMAND = ["stap", "-g"]

class TraceTests(unittest.TestCase):
    # unittest.TestCase options
    maxDiff = None

    # TraceTests options
    backend = None
    optimize_python = 0

    @classmethod
    def setUpClass(self):
        self.backend.assert_usable()

    def run_case(self, name):
        actual_output, expected_output = self.backend.run_case(
            name, optimize_python=self.optimize_python)
        self.assertEqual(actual_output, expected_output)

    def test_function_entry_return(self):
        self.run_case("call_stack")

    def test_verify_call_opcodes(self):
        """Ensure our call stack test hits all function call opcodes"""

        opcodes = set(["CALL_FUNCTION", "CALL_FUNCTION_EX", "CALL_FUNCTION_KW"])

        with open(abspath("call_stack.py")) as f:
            code_string = f.read()

        def get_function_instructions(funcname):
            # Recompile with appropriate optimization setting
            code = compile(source=code_string,
                           filename="<string>",
                           mode="exec",
                           optimize=self.optimize_python)

            for c in code.co_consts:
                if isinstance(c, types.CodeType) and c.co_name == funcname:
                    return dis.get_instructions(c)
            return []

        for instruction in get_function_instructions('start'):
            opcodes.discard(instruction.opname)

        self.assertEqual(set(), opcodes)

    def test_gc(self):
        self.run_case("gc")

    def test_line(self):
        self.run_case("line")

class DTraceNormalTests(TraceTests):
    backend = DTraceBackend()
    optimize_python = 0

class DTraceOptimizedTests(TraceTests):
    backend = DTraceBackend()
    optimize_python = 2

class SystemTapNormalTests(TraceTests):
    backend = SystemTapBackend()
    optimize_python = 0

class SystemTapOptimizedTests(TraceTests):
    backend = SystemTapBackend()
    optimize_python = 2

def test_main():
    run_unittest(DTraceNormalTests, DTraceOptimizedTests, SystemTapNormalTests,
                 SystemTapOptimizedTests)

if __name__ == '__main__':
    test_main()


text:
package com.google.code.kaptcha;

public class Constants
{
	public final static String KAPTCHA_SESSION_KEY = "KAPTCHA_SESSION_KEY";

	public final static String KAPTCHA_SESSION_DATE = "KAPTCHA_SESSION_DATE";

	public final static String KAPTCHA_SESSION_CONFIG_KEY = "kaptcha.session.key";

	public final static String KAPTCHA_SESSION_CONFIG_DATE = "kaptcha.session.date";

	public final static String KAPTCHA_BORDER = "kaptcha.border";

	public final static String KAPTCHA_BORDER_COLOR = "kaptcha.border.color";

	public final static String KAPTCHA_BORDER_THICKNESS = "kaptcha.border.thickness";

	public final static String KAPTCHA_NOISE_COLOR = "kaptcha.noise.color";

	public final static String KAPTCHA_NOISE_IMPL = "kaptcha.noise.impl";

	public final static String KAPTCHA_OBSCURIFICATOR_IMPL = "kaptcha.obscurificator.impl";

	public final static String KAPTCHA_PRODUCER_IMPL = "kaptcha.producer.impl";

	public final static String KAPTCHA_TEXTPRODUCER_IMPL = "kaptcha.textproducer.impl";

	public final static String KAPTCHA_TEXTPRODUCER_CHAR_STRING = "kaptcha.textproducer.char.string";

	public final static String KAPTCHA_TEXTPRODUCER_CHAR_LENGTH = "kaptcha.textproducer.char.length";

	public final static String KAPTCHA_TEXTPRODUCER_FONT_NAMES = "kaptcha.textproducer.font.names";

	public final static String KAPTCHA_TEXTPRODUCER_FONT_COLOR = "kaptcha.textproducer.font.color";

	public final static String KAPTCHA_TEXTPRODUCER_FONT_SIZE = "kaptcha.textproducer.font.size";

	public final static String KAPTCHA_TEXTPRODUCER_CHAR_SPACE = "kaptcha.textproducer.char.space";

	public final static String KAPTCHA_WORDRENDERER_IMPL = "kaptcha.word.impl";

	public final static String KAPTCHA_BACKGROUND_IMPL = "kaptcha.background.impl";

	public static final String KAPTCHA_BACKGROUND_CLR_FROM = "kaptcha.background.clear.from";

	public static final String KAPTCHA_BACKGROUND_CLR_TO = "kaptcha.background.clear.to";

	public static final String KAPTCHA_IMAGE_WIDTH = "kaptcha.image.width";

	public static final String KAPTCHA_IMAGE_HEIGHT = "kaptcha.image.height";
}


text:
using System.Text;
using GitVersion.Extensions;

namespace GitVersion.Helpers
{
    public static class JsonSerializer
    {
        public static string Serialize(object obj)
        {
            var builder = new StringBuilder();
            builder.AppendLine("{");
            var first = true;
            foreach (var (key, value) in obj.GetProperties())
            {
                if (!first) builder.AppendLine(",");
                else first = false;

                builder.Append($"  \"{key}\":");

                // preserve leading zeros for padding
                if (NotAPaddedNumber(value) && int.TryParse(value, out var number))
                    builder.Append(number);
                else
                    builder.Append($"\"{value}\"");
            }

            builder.AppendLine().Append("}");
            return builder.ToString();
        }

        private static bool NotAPaddedNumber(string value) => value != null && (value == "0" || !value.StartsWith("0"));
    }
}


text:
package com.google.security.zynamics.binnavi.Gui.GraphSettings;

/**
 * Contains the graph settings dialog where the user can configure layout and behavior of graphs.
 */


text:
/*

################################################################################
Migration script to create a LOCATION and SNP_LOCATION

Designed for execution with Flyway database migrations tool; this should be
automatically run to completely generate the schema that is out-of-the-box
compatibile with the GOCI model (see
https://github.com/tburdett/goci/tree/2.x-dev/goci-core/goci-model for more).

author:  Emma Hastings
date:    June 17th 2015
version: 2.0.1.004
################################################################################

#######################################
#  CREATE NEW TABLES AND CONSTRAINTS  #
#######################################
*/

--------------------------------------------------------
--  Create Table LOCATION
--------------------------------------------------------

  CREATE TABLE "LOCATION" (
     "ID" NUMBER(19,0),
     "REGION_ID" NUMBER(19,0),
     "CHROMOSOME_NAME" VARCHAR2(255 CHAR),
     "CHROMOSOME_POSITION" VARCHAR2(255 CHAR));

--------------------------------------------------------
--  DDL for Index LOCATION_ID_PK
--------------------------------------------------------
  CREATE UNIQUE INDEX "LOCATION_ID_PK" ON "LOCATION" ("ID");

--------------------------------------------------------
--  Constraints for Table LOCATION
--------------------------------------------------------
  ALTER TABLE "LOCATION" ADD PRIMARY KEY ("ID") ENABLE;
  ALTER TABLE "LOCATION" MODIFY ("ID" NOT NULL ENABLE);

--------------------------------------------------------
--  Ref Constraints for Table LOCATION
--------------------------------------------------------
  ALTER TABLE "LOCATION" ADD CONSTRAINT "REGION_ID_FK" FOREIGN KEY ("REGION_ID")
    REFERENCES "REGION" ("ID") ENABLE;

--------------------------------------------------------
-- Create trigger on LOCATION
--------------------------------------------------------

CREATE OR REPLACE TRIGGER LOCATION_TRG
BEFORE INSERT ON "LOCATION"
FOR EACH ROW
    BEGIN
        IF :NEW.ID IS NULL THEN
            SELECT HIBERNATE_SEQUENCE.NEXTVAL INTO :NEW.ID FROM DUAL;
        END IF;
    END;
/
ALTER TRIGGER LOCATION_TRG ENABLE;

--------------------------------------------------------
--  Create Table SNP_LOCATION
--------------------------------------------------------
  CREATE TABLE "SNP_LOCATION" (
     "SNP_ID" NUMBER(19,0),
     "LOCATION_ID" NUMBER(19,0));

--------------------------------------------------------
--  Constraints for Table SNP_LOCATION
--------------------------------------------------------
ALTER TABLE "SNP_LOCATION" MODIFY ("LOCATION_ID" NOT NULL ENABLE);
ALTER TABLE "SNP_LOCATION" MODIFY ("SNP_ID" NOT NULL ENABLE);

--------------------------------------------------------
--  Ref Constraints for Table SNP_LOCATION
--------------------------------------------------------
ALTER TABLE "SNP_LOCATION" ADD CONSTRAINT "SNP_LOC_LOCATION_ID_FK" FOREIGN KEY ("LOCATION_ID")
REFERENCES "LOCATION" ("ID") ENABLE;
ALTER TABLE "SNP_LOCATION" ADD CONSTRAINT "SNP_LOC_SNP_ID_FK" FOREIGN KEY ("SNP_ID")
REFERENCES "SINGLE_NUCLEOTIDE_POLYMORPHISM" ("ID") ENABLE;


text:
package org.jenkinsci.remoting.protocol.impl;

import javax.annotation.Nonnull;
import java.io.ObjectInputStream;
import java.util.Map;
import java.util.TreeMap;

/**
 * Utility class to handle the encoding and decoding of the connection headers. Connections headers are encoded
 * as a flat JSON object with exclusively {@link String} values. We use a pure text based format as this information
 * will be used to decide whether to accept a connection with the remote end, thus, until the connection has been
 * accepted we should not trust {@link ObjectInputStream} or an equivalent based mechanism for exchange of
 * pre-connection headers. We could use a header format equivalent to that of HTTP headers, the JSON format
 * of mapping two/from a {@link Map} with {@link String} keys and values has the advantages
 *

 *

 * there is a 1:1 mapping between a {@code Map} and a JSON object
 *

 *

 * A JSON object cannot have {@code null} keys and neither can a {@link Map}
 *

 *

 * A JSON object can have {@code null} values and so can a {@link Map}
 *

 *

 * A JSON object can only have one value for any key whereas something like the HTTP Header format
 * allows for multiple values on any specific header
 *

 *

 * Tooling such as wireshark can detect JSON formatted data and present it nicely.
 * (We are assuming here that most usage of the headers will be after a TLS connection has been set-up
 * and thus anyone using wireshark to sniff the packets has access to both side's private keys
 * and as such is trusted to actually be peeking into the headers!)
 *

 *

 *
 * @since FIXME
 */
public final class ConnectionHeaders {

    /**
     * Do not instantiate utility classes.
     */
    private ConnectionHeaders() {
        throw new IllegalAccessError("Utility class");
    }

    /**
     * Converts the headers into the String format.
     *
     * @param data the headers.
     * @return the string encoded header.
     */
    @Nonnull
    public static String toString(@Nonnull Map<String, String> data) {
        StringBuilder b = new StringBuilder();
        b.append('{');
        boolean first = true;
        for (Map.Entry<String, String> e : data.entrySet()) {
            if (first) {
                first = false;
            } else {
                b.append(',');
            }
            b.append('"');
            appendEscaped(b, e.getKey());
            b.append("\":");
            if (e.getValue() == null) {
                b.append("null");
            } else {
                b.append('"');
                appendEscaped(b, e.getValue());
                b.append('"');
            }
        }
        b.append('}');
        return b.toString();
    }

    /**
     * Converts the headers from the String format.
     *
     * @param data the string encoded headers.
     * @return the headers.
     */
    @Nonnull
    public static Map<String, String> fromString(@Nonnull String data) throws ParseException {
        Map<String, String> result = new TreeMap<String, String>();
        int state = 0;
        StringBuilder key = new StringBuilder();
        StringBuilder val = new StringBuilder();
        for (int i = 0, n = data.length(); i < n; i++) {
            char c = data.charAt(i);
            switch (state) {
                case 0:
                    if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\b') {
                        continue;
                    }
                    if (c != '{') {
                        throw new ParseException("Expecting '{' but got '" + c + "'");
                    }
                    state = 1;
                    break;
                case 1:
                    if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\b') {
                        continue;
                    }
                    if (c == '}') {
                        state = 9;
                    } else if (c != '\"') {
                        throw new ParseException("Expecting '\"' but got '" + c + "'");
                    } else {
                        state = 2;
                    }
                    break;
                case 2:
                    if (c == '\\') {
                        state = 3;
                    } else if (c == '\"') {
                        state = 4;
                    } else {
                        key.append(c);
                    }
                    break;
                case 3:
                    i = decodeEscape(key, c, data, i, n);
                    state = 2;
                    break;
                case 4:
                    if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\b') {
                        continue;
                    }
                    if (c != ':') {
                        throw new ParseException("Expecting ':' but got '" + c + "'");
                    }
                    state = 5;
                    break;
                case 5:
                    if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\b') {
                        continue;
                    }
                    if (c == 'n' && i + 3 < n && data.charAt(i + 1) == 'u' && data.charAt(i + 2) == 'l'
                            && data.charAt(i + 3) == 'l') {
                        i += 3;
                        result.put(key.toString(), null);
                        key.setLength(0);
                        state = 8;
                        break;
                    }
                    if (c != '\"') {
                        throw new ParseException("Expecting '\"' or 'null' but got '" + c + "'");
                    }
                    state = 6;
                    break;
                case 6:
                    if (c == '\\') {
                        state = 7;
                    } else if (c == '\"') {
                        result.put(key.toString(), val.toString());
                        key.setLength(0);
                        val.setLength(0);
                        state = 8;
                    } else {
                        val.append(c);
                    }
                    break;
                case 7:
                    i = decodeEscape(val, c, data, i, n);
                    state = 6;
                    break;
                case 8:
                    if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\b') {
                        continue;
                    }
                    if (c == '}') {
                        state = 9;
                    } else if (c == ',') {
                        state = 10;
                    } else {
                        throw new ParseException("Expecting '}' or ',' but got '" + c + "'");
                    }
                    break;
                case 9:
                    if (!(c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\b')) {
                        throw new ParseException("Non-whitespace after '}'");
                    }
                    break;
                case 10:
                    if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\b') {
                        continue;
                    }
                    if (c != '\"') {
                        throw new ParseException("Expecting '\"' but got '" + c + "'");
                    } else {
                        state = 2;
                    }
                    break;
                default:
                    throw new ParseException("Unexpected parser state machine state: " + state);
            }
        }
        return result;
    }

    public static void appendEscaped(StringBuilder b, String str) {
        for (int i = 0, n = str.length(); i < n; i++) {
            char c = str.charAt(i);
            switch (c) {
                case '\b':
                    b.append("\\b");
                    break;
                case '\t':
                    b.append("\\t");
                    break;
                case '\f':
                    b.append("\\f");
                    break;
                case '\n':
                    b.append("\\n");
                    break;
                case '\r':
                    b.append("\\r");
                    break;
                case '"':
                case '\\':
                    b.append('\\').append(c);
                    break;
                default:
                    if (c <= 0x1f) {
                        // escape all control characters
                        b.append(encodeEscape(c));
                    } else {
                        b.append(c);
                    }
                    break;
            }
        }
    }

    private static int decodeEscape(StringBuilder val, char c, String str, int i, int n) throws ParseException {
        switch (c) {
            case '\"':
            case '\\':
            case '/':
                val.append(c);
                return i;
            case 'b':
                val.append('\b');
                return i;
            case 'f':
                val.append('\f');
                return i;
            case 'n':
                val.append('\n');
                return i;
            case 'r':
                val.append('\r');
                return i;
            case 't':
                val.append('\t');
                return i;
            case 'u':
                if (i + 4 < n) {
                    int n1 = Character.digit(str.charAt(i + 1), 16);
                    int n2 = Character.digit(str.charAt(i + 2), 16);
                    int n3 = Character.digit(str.charAt(i + 3), 16);
                    int n4 = Character.digit(str.charAt(i + 4), 16);
                    if (n1 == -1 || n2 == -1 || n3 == -1 || n4 == -1) {
                        throw new ParseException("Malformed unicode escape");
                    }
                    val.append((char) ((n1 << 12) | (n2 << 8) | (n3 << 4) | n4));
                    return i + 4;
                } else {
                    throw new ParseException("Malformed unicode escape");
                }
            default:
                throw new ParseException("Unknown character escape '" + c + "'");
        }

    }

    public static String encodeEscape(int c) {
        return "\\u" + Character.forDigit((c >> 12) & 15, 16)
                + Character.forDigit((c >> 8) & 15, 16)
                + Character.forDigit((c >> 4) & 15, 16)
                + Character.forDigit(c & 15, 16);
    }

    public static class ParseException extends Exception {
        public ParseException(String message) {
            super(message);
        }
    }
}


text:
<?php

namespace Magento\Framework\Cache\Frontend\Adapter;

/**
 * Adapter for Magento -> Zend cache frontend interfaces
 */
class Zend implements \Magento\Framework\Cache\FrontendInterface
{
    /**
     * @var \Zend_Cache_Core
     */
    protected $_frontend;

    /**
     * @param \Zend_Cache_Core $frontend
     */
    public function __construct(\Zend_Cache_Core $frontend)
    {
        $this->_frontend = $frontend;
    }

    /**
     * {@inheritdoc}
     */
    public function test($identifier)
    {
        return $this->_frontend->test($this->_unifyId($identifier));
    }

    /**
     * {@inheritdoc}
     */
    public function load($identifier)
    {
        return $this->_frontend->load($this->_unifyId($identifier));
    }

    /**
     * {@inheritdoc}
     */
    public function save($data, $identifier, array $tags = [], $lifeTime = null)
    {
        return $this->_frontend->save($data, $this->_unifyId($identifier), $this->_unifyIds($tags), $lifeTime);
    }

    /**
     * {@inheritdoc}
     */
    public function remove($identifier)
    {
        return $this->_frontend->remove($this->_unifyId($identifier));
    }

    /**
     * {@inheritdoc}
     *
     * @throws \InvalidArgumentException Exception is thrown when non-supported cleaning mode is specified
     */
    public function clean($mode = \Zend_Cache::CLEANING_MODE_ALL, array $tags = [])
    {
        // Cleaning modes 'old' and 'notMatchingTag' are prohibited as a trade off for decoration reliability
        if (!in_array(
            $mode,
            [
                \Zend_Cache::CLEANING_MODE_ALL,
                \Zend_Cache::CLEANING_MODE_MATCHING_TAG,
                \Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG
            ]
        )
        ) {
            throw new \InvalidArgumentException(
                "Magento cache frontend does not support the cleaning mode '{$mode}'."
            );
        }
        return $this->_frontend->clean($mode, $this->_unifyIds($tags));
    }

    /**
     * {@inheritdoc}
     */
    public function getBackend()
    {
        return $this->_frontend->getBackend();
    }

    /**
     * {@inheritdoc}
     */
    public function getLowLevelFrontend()
    {
        return $this->_frontend;
    }

    /**
     * Retrieve single unified identifier
     *
     * @param string $identifier
     * @return string
     */
    protected function _unifyId($identifier)
    {
        return strtoupper($identifier);
    }

    /**
     * Retrieve multiple unified identifiers
     *
     * @param array $ids
     * @return array
     */
    protected function _unifyIds(array $ids)
    {
        foreach ($ids as $key => $value) {
            $ids[$key] = $this->_unifyId($value);
        }
        return $ids;
    }
}


text:
package com.forsvarir.mud.commands;

import com.forsvarir.mud.Player;
import com.forsvarir.mud.Room;
import com.forsvarir.mud.RoomManager;
import com.forsvarir.mud.communications.MessageSender;
import org.springframework.stereotype.Service;

@Service
public class SayCommand implements MudCommand {
    private MessageSender messageSender;
    private RoomManager roomManager;

    public SayCommand(MessageSender messageSender, RoomManager roomManager) {
        this.messageSender = messageSender;
        this.roomManager = roomManager;
    }

    @Override
    public void processCommand(String arguments, Player sender) {
        final Room room = sender.getRoom();
        if (room == null) {
            // TODO: what should this do?
            return;
        }

        messageSender.sendToUser("You say '" + arguments + "'\n\r", sender.getPrincipal(), sender.getSessionId());

        for (var player : room.getPlayersInRoom()) {
            if (sender != player) {
                messageSender.sendToUser(sender.getName() + " says '" + arguments + "'\n\r", player.getPrincipal(), player.getSessionId());
            }
        }
    }
}


text:
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#ifdef HAVE_CRYPT_H
# include <crypt.h>
#endif

#ifndef OPENPAM
static char password_prompt[] = "Password:";
#endif

#ifndef PAM_EXTERN
#define PAM_EXTERN
#endif

// #include "fix_pw.h"

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/resource.h>
#include <syslog.h>
#include <pwd.h>
#include <shadow.h>
#include <time.h>       /* for time() */
#include <errno.h>
#include <sys/wait.h>

#include <security/_pam_macros.h>

/* indicate that the following groups are defined */

#define PAM_SM_ACCOUNT

#include <security/pam_modules.h>
#include <security/pam_ext.h>
#include <security/pam_modutil.h>

// #include "support.h"
// #include "passverify.h"

int _unix_run_verify_binary(pam_handle_t *pamh, unsigned int ctrl,
                            const char *user, int *daysleft)
{
    int retval=0, child, fds[2];
    struct sigaction newsa, oldsa;
    // D(("running verify_binary"));

    /* create a pipe for the messages */
    if (pipe(fds) != 0) {
        // D(("could not make pipe"));
        pam_syslog(pamh, LOG_ERR, "Could not make pipe: %m");
        return PAM_AUTH_ERR;
    }
    // D(("called."));

    if (off(UNIX_NOREAP, ctrl)) {
        /*
         * This code arranges that the demise of the child does not cause
         * the application to receive a signal it is not expecting - which
         * may kill the application or worse.
         *
         * The "noreap" module argument is provided so that the admin can
         * override this behavior.
         */
        memset(&newsa, '\0', sizeof(newsa));
        newsa.sa_handler = SIG_DFL;
        sigaction(SIGCHLD, &newsa, &oldsa);
    }

    /* fork */
    child = fork();
    if (child == 0) {
        static char *envp[] = { NULL };
        const char *args[] = { NULL, NULL, NULL, NULL };

        /* XXX - should really tidy up PAM here too */

        /* reopen stdout as pipe */
        if (dup2(fds[1], STDOUT_FILENO) != STDOUT_FILENO) {
            pam_syslog(pamh, LOG_ERR, "dup2 of %s failed: %m", "stdout");
            _exit(PAM_AUTHINFO_UNAVAIL);
        }

        if (pam_modutil_sanitize_helper_fds(pamh, PAM_MODUTIL_PIPE_FD,
                                            PAM_MODUTIL_IGNORE_FD,
                                            PAM_MODUTIL_PIPE_FD) < 0) {
            _exit(PAM_AUTHINFO_UNAVAIL);
        }

        if (geteuid() == 0) {
            /* must set the real uid to 0 so the helper will not error
               out if pam is called from setuid binary (su, sudo...) */
            if (setuid(0) == -1) {
                pam_syslog(pamh, LOG_ERR, "setuid failed: %m");
                printf("-1\n");
                fflush(stdout);
                _exit(PAM_AUTHINFO_UNAVAIL);
            }
        }

        /* exec binary helper */
        args[0] = CHKPWD_HELPER;
        args[1] = user;
        args[2] = "chkexpiry";

        execve(CHKPWD_HELPER, (char *const *) args, envp);

        pam_syslog(pamh, LOG_ERR, "helper binary execve failed: %m");
        /* should not get here: exit with error */
        // D(("helper binary is not available"));
        printf("-1\n");
        fflush(stdout);
        _exit(PAM_AUTHINFO_UNAVAIL);
    } else {
        close(fds[1]);
        if (child > 0) {
            char buf[32];
            int rc=0;
            /* wait for helper to complete: */
            while ((rc=waitpid(child, &retval, 0)) < 0 && errno == EINTR);
            if (rc<0) {
                pam_syslog(pamh, LOG_ERR, "unix_chkpwd waitpid returned %d: %m", rc)     retval = PAM_AUTH_ERR;
            } else if (!WIFEXITED(retval)) {
                pam_syslog(pamh, LOG_ERR, "unix_chkpwd abnormal exit: %d", retval);
                retval = PAM_AUTH_ERR;
            } else {
                retval = WEXITSTATUS(retval);
                rc = pam_modutil_read(fds[0], buf, sizeof(buf) - 1);
                if(rc > 0) {
                    buf[rc] = '\0';
                    if (sscanf(buf,"%d", daysleft) != 1 )
                        retval = PAM_AUTH_ERR;
                }
                else {
                    pam_syslog(pamh, LOG_ERR, "read unix_chkpwd output error %d: %m");
                    retval = PAM_AUTH_ERR;
                }
            }
        } else {
            pam_syslog(pamh, LOG_ERR, "Fork failed: %m");
            // D(("fork failed"));
            retval = PAM_AUTH_ERR;
        }
        close(fds[0]);
    }

    if (off(UNIX_NOREAP, ctrl)) {
        sigaction(SIGCHLD, &oldsa, NULL);   /* restore old signal handler */
    }

    // D(("Returning %d",retval));
    return retval;
}

/*
 * PAM framework looks for this entry-point to pass control to the
 * account management module.
 */

int
pam_sm_acct_mgmt(pam_handle_t *pamh, int flags, int argc, const char **argv)
{
    unsigned int ctrl;
    const void *void_uname;
    const char *uname;
    int retval, daysleft;
    struct spwd *spent;
    struct passwd *pwent;
    char buf[256];

    // D(("called."));

    ctrl = _set_ctrl(pamh, flags, NULL, NULL, NULL, argc, argv);

    retval = pam_get_item(pamh, PAM_USER, &void_uname);
    uname = void_uname;
    // D(("user = `%s'", uname));
    if (retval != PAM_SUCCESS || uname == NULL) {
        pam_syslog(pamh, LOG_ALERT,
                   "could not identify user (from uid=%lu)",
                   (unsigned long int)getuid());
        return PAM_USER_UNKNOWN;
    }

    retval = get_account_info(pamh, uname, &pwent, &spent);
    if (retval == PAM_USER_UNKNOWN) {
        pam_syslog(pamh, LOG_ALERT,
                   "could not identify user (from getpwnam(%s))",
                   uname);
        return retval;
    }

    if (retval == PAM_SUCCESS && spent == NULL)
        return PAM_SUCCESS;

    if (retval == PAM_UNIX_RUN_HELPER) {
        retval = _unix_run_verify_binary(pamh, ctrl, uname, &daysleft);
        if (retval == PAM_AUTHINFO_UNAVAIL &&
            on(UNIX_BROKEN_SHADOW, ctrl))
            return PAM_SUCCESS;
    } else if (retval != PAM_SUCCESS) {
        if (on(UNIX_BROKEN_SHADOW,ctrl))
            return PAM_SUCCESS;
        else
            return retval;
    } else
        retval = check_shadow_expiry(pamh, spent, &daysleft);

    if (on(UNIX_NO_PASS_EXPIRY, ctrl)) {
        const void *pretval = NULL;
        int authrv = PAM_AUTHINFO_UNAVAIL; /* authentication not called */

        if (pam_get_data(pamh, "unix_setcred_return", &pretval) == PAM_SUCCESS
            && pretval)
            authrv = *(const int *)pretval;

        if (authrv != PAM_SUCCESS
            && (retval == PAM_NEW_AUTHTOK_REQD || retval == PAM_AUTHTOK_EXPIRED))
            retval = PAM_SUCCESS;
    }

    switch (retval) {
    case PAM_ACCT_EXPIRED:
        pam_syslog(pamh, LOG_NOTICE,
                   "account %s has expired (account expired)",
                   uname);
        _make_remark(pamh, ctrl, PAM_ERROR_MSG,
                     _("Your account has expired; please contact your system adminis"));
        break;
    case PAM_NEW_AUTHTOK_REQD:
        if (daysleft == 0) {
            pam_syslog(pamh, LOG_NOTICE,
                       "expired password for user %s (root enforced)",
                       uname);
            _make_remark(pamh, ctrl, PAM_ERROR_MSG,
                         _("You are required to change your password immediately (ad enforced)"));
        } else {
            pam_syslog(pamh, LOG_DEBUG,
                       "expired password for user %s (password aged)",
                       uname);
            _make_remark(pamh, ctrl, PAM_ERROR_MSG,
                         _("You are required to change your password immediately (pa expired)"));
        }
        break;
    case PAM_AUTHTOK_EXPIRED:
        pam_syslog(pamh, LOG_NOTICE,
                   "account %s has expired (failed to change password)",
                   uname);
        _make_remark(pamh, ctrl, PAM_ERROR_MSG,
                     _("Your account has expired; please contact your system adminis"));
        break;
    case PAM_AUTHTOK_ERR:
        retval = PAM_SUCCESS;
        /* fallthrough */
    case PAM_SUCCESS:
        if (daysleft >= 0) {
            pam_syslog(pamh, LOG_DEBUG,
                       "password for user %s will expire in %d days",
                       uname, daysleft);
#if defined HAVE_DNGETTEXT && defined ENABLE_NLS
            snprintf (buf, sizeof (buf),
                      dngettext(PACKAGE,
                                "Warning: your password will expire in %d day",
                                "Warning: your password will expire in %d days",
                                daysleft),
                      daysleft);
#else
            if (daysleft == 1)
                snprintf(buf, sizeof (buf),
                         _("Warning: your password will expire in %d day"),
                         daysleft);
            else
                snprintf(buf, sizeof (buf),
                         /* TRANSLATORS: only used if dngettext is not supported */
                         _("Warning: your password will expire in %d days"),
                         daysleft);
#endif
            _make_remark(pamh, ctrl, PAM_TEXT_INFO, buf);
        }
    }

    // D(("all done"));

    return retval;
}

PAM_EXTERN int
pam_sm_authenticate(pam_handle_t *pamh, int flags,
                    int argc, const char *argv[])
{
#ifndef OPENPAM
	struct pam_conv *conv;
	struct pam_message msg;
	const struct pam_message *msgp;
	struct pam_response *resp;
#endif
	struct passwd *pwd;
	const char *user;
	const char *crypt_password, *password;
	int pam_err, retry;

	(void)argc;
	(void)argv;
    printf("Using new (typotplerant) pam module! (openpam)\n");
	/* identify user */
	if ((pam_err = pam_get_user(pamh, &user, NULL)) != PAM_SUCCESS)
		return (pam_err);
	if ((pwd = getpwnam(user)) == NULL)
		return (PAM_USER_UNKNOWN);

	/* get password */
#ifndef OPENPAM
	pam_err = pam_get_item(pamh, PAM_CONV, (const void **)&conv);
	if (pam_err != PAM_SUCCESS)
		return (PAM_SYSTEM_ERR);
	msg.msg_style = PAM_PROMPT_ECHO_OFF;
	msg.msg = password_prompt;
	msgp = &msg;
#endif
	for (retry = 0; retry < 3; ++retry) {
#ifdef OPENPAM
		pam_err = pam_get_authtok(pamh, PAM_AUTHTOK,
                                  &password, NULL);
#else
		resp = NULL;
		pam_err = (*conv->conv)(1, &msgp, &resp, conv->appdata_ptr);
		if (resp != NULL) {
			if (pam_err == PAM_SUCCESS)
				password = resp->resp;
			else
				free(resp->resp);
			free(resp);
		}
#endif
		if (pam_err == PAM_SUCCESS)
			break;
	}
	if (pam_err == PAM_CONV_ERR)
		return (pam_err);
	if (pam_err != PAM_SUCCESS)
		return (PAM_AUTH_ERR);
	/* compare passwords */
    /* If the entered password is null, fail immediately */
    int success = 0;
	if (!pwd->pw_passwd[0] && (flags & PAM_DISALLOW_NULL_AUTHTOK))
        success = 0;
    else {
        /* Check the original first */
        printf("pwd->pw_passwd: %s\n", pwd->pw_passwd);
        if (((crypt_password = crypt(password, pwd->pw_passwd)) != NULL) &&
            strcmp(crypt_password, pwd->pw_passwd) == 0) {
            success = 1;  // If it succeeds, then set pam_success and don't do anything
            printf("Failed: %s\t\t<%s>\t\t%s\n", password, pwd->pw_passwd,crypt_password);
        } else { // if the comparison with entered password fails, try possible fixes
            printf("Trying possible typo fixes!!\n Total %d combinations.\n", NFIXES);
            int i = 0;
            char **fixed = fix_passwords(password); // obtain possible fixes
            for(i = 0; i<NFIXES; i++) {
                printf("trying corrected pw: <%s>\t\t<%s>\n", fixed[i], pwd->pw_passwd);
                if(!fixed[i] || fixed[i][0] == '\0') // probably malformed fix
                    continue;
                crypt_password = crypt(fixed[i], pwd->pw_passwd);
                if ((crypt_password != NULL) && (strcmp(crypt_password, pwd->pw_passwd) == 0)) {
                    success = 1;
                    break;
                }
                printf("Failed: %s\t\t%s\t\t%s\n", password, pwd->pw_passwd,crypt_password);
            }
        }
    }
    printf("Success: %d\n", success);
    if (success == 1)
        pam_err = PAM_SUCCESS;
    else
        pam_err = PAM_AUTH_ERR;
#ifndef OPENPAM
	free(password);
#endif
	return (pam_err);
}

PAM_EXTERN int
pam_sm_setcred(pam_handle_t *pamh, int flags,
               int argc, const char *argv[])
{

	(void)pamh;
	(void)flags;
	(void)argc;
	(void)argv;
	return (PAM_SUCCESS);
}

PAM_EXTERN int
pam_sm_acct_mgmt(pam_handle_t *pamh, int flags,
                 int argc, const char *argv[])
{

	(void)pamh;
	(void)flags;
	(void)argc;
	(void)argv;
	return (PAM_SUCCESS);
}

PAM_EXTERN int
pam_sm_open_session(pam_handle_t *pamh, int flags,
                    int argc, const char *argv[])
{

	(void)pamh;
	(void)flags;
	(void)argc;
	(void)argv;
	return (PAM_SUCCESS);
}

PAM_EXTERN int
pam_sm_close_session(pam_handle_t *pamh, int flags,
	int argc, const char *argv[])
{

	(void)pamh;
	(void)flags;
	(void)argc;
	(void)argv;
	return (PAM_SUCCESS);
}

PAM_EXTERN int
pam_sm_chauthtok(pam_handle_t *pamh, int flags,
	int argc, const char *argv[])
{

	(void)pamh;
	(void)flags;
	(void)argc;
	(void)argv;
	return (PAM_SERVICE_ERR);
}

#ifdef PAM_MODULE_ENTRY
PAM_MODULE_ENTRY("pam_typopw");
#endif


text:
package org.ejml.alg.dense.decompose.qr;

import org.ejml.data.CDenseMatrix64F;
import org.ejml.data.Complex64F;
import org.ejml.ops.CCommonOps;
import org.ejml.ops.CMatrixFeatures;
import org.ejml.ops.CRandomMatrices;
import org.ejml.ops.ComplexMath64F;
import org.junit.Test;

import java.util.Random;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 * @author Peter Abeles
 */
public class TestQrHelperFunctions_CD64 {

    Random rand = new Random(234);

    @Test
    public void findMax() {
        double u[] = new double[50];

        for (int i = 0; i < u.length; i++) {
            u[i] = (rand.nextDouble()-0.5)*20;
        }

        int offset = 4;
        int length = 5;

        double max = 0;
        for (int i = 0; i < length; i++) {
            double real = u[i*2+offset*2];
            double img = u[i*2+offset*2+1];

            if( real*real + img*img > max ) {
                max = real*real + img*img;
            }
        }

        max = Math.sqrt(max);

        assertEquals(max,QrHelperFunctions_CD64.findMax(u,offset,length),1e-8);
    }

    @Test
    public void divideElements_startU() {
        double u[] = new double[12*2];
        for (int i = 0; i < u.length; i++ ) {
            u[i] = (rand.nextDouble()*0.5-1.0)*2;
        }
        double found[] = u.clone();

        Complex64F A = new Complex64F(rand.nextDouble(),rand.nextDouble());
        Complex64F U = new Complex64F();
        Complex64F expected = new Complex64F();

        int j = 3;
        int numRows = 8;
        int startU = 2;

        QrHelperFunctions_CD64.divideElements(j,numRows,found,startU,A.real,A.imaginary);

        for (int i = 0; i < 12; i++) {
            int index = i * 2;

            if( i >= j+startU && i < numRows+startU ) {
                U.real = u[index];
                U.imaginary = u[index + 1];
                ComplexMath64F.divide(U, A, expected);

                assertEquals(expected.real, found[index], 1e-8);
                assertEquals(expected.imaginary, found[index + 1], 1e-8);
            } else {
                assertEquals(u[index],found[index],1e-8);
                assertEquals(u[index+1],found[index+1],1e-8);
            }
        }
    }

    @Test
    public void computeTauGammaAndDivide() {
        double u[] = new double[12*2];
        for (int i = 0; i < u.length; i++ ) {
            u[i] = (rand.nextDouble()*0.5-1.0)*2;
        }

        double max = 2.0;
        int j = 2;
        int numRows = 6;

        Complex64F expectedTau = new Complex64F();
        double expectedGamma = 0;
        double[] expectedU = u.clone();

        for (int i = j; i < numRows; i++) {
            Complex64F U = new Complex64F(u[i*2],u[i*2+1]);
            Complex64F div = new Complex64F();
            ComplexMath64F.divide(U,new Complex64F(max,0),div);

            expectedU[i*2] = div.real;
            expectedU[i*2+1] = div.imaginary;
        }
        double normX = 0;
        for (int i = j; i < numRows; i++) {
            normX += expectedU[i*2]*expectedU[i*2] + expectedU[i*2+1]*expectedU[i*2+1];
        }
        normX = Math.sqrt(normX);
        double realX0 = expectedU[j*2];
        double imagX0 = expectedU[j*2+1];

        double magX0 = Math.sqrt(realX0*realX0 + imagX0*imagX0);
        expectedTau.real      = realX0*normX/magX0;
        expectedTau.imaginary = imagX0*normX/magX0;

        double realU0 = realX0 + expectedTau.real;
        double imagU0 = imagX0 + expectedTau.imaginary;

        //
        double normU = 1;
        Complex64F B = new Complex64F(realU0,imagU0);
        for (int i = j+1; i < numRows; i++) {
            Complex64F A = new Complex64F( expectedU[i*2], expectedU[i*2+1]);
            Complex64F result = new Complex64F();
            ComplexMath64F.divide(A,B,result);
            normU += result.getMagnitude2();
        }
        expectedGamma = 2.0/normU;

        Complex64F foundTau = new Complex64F();
        double[] foundU = u.clone();
        double foundGamma = QrHelperFunctions_CD64.computeTauGammaAndDivide(j,numRows,foundU,max,foundTau);

        for (int i = 0; i < expectedU.length; i++) {
            assertEquals(expectedU[i],foundU[i],1e-8);
        }

        assertEquals(expectedTau.real,foundTau.real,1e-8);
        assertEquals(expectedTau.imaginary,foundTau.imaginary,1e-8);

        assertEquals(expectedGamma,foundGamma,1e-8);
    }

    @Test
    public void rank1UpdateMultR() {
        double u[] = new double[12*2];
        double uoff[] = new double[12*2+2];
        double subU[] = new double[12*2];
        double _temp[] = new double[u.length];
        double gamma = 0.6;

        for (int i = 0; i < u.length; i++) {
            u[i] = uoff[i+2] = (rand.nextDouble()*0.5-1.0)*2;
        }

        for (int i = 1; i < 12; i++) {
            CDenseMatrix64F A = CRandomMatrices.createRandom(i,i,rand);

            for (int j = 1; j <= i; j += 2) {
                CDenseMatrix64F subA = CCommonOps.extract(A,A.numRows-j,A.numRows,A.numRows-j,A.numRows);
                System.arraycopy(u,(A.numRows-j)*2,subU,0,j*2);
                CDenseMatrix64F expected = rank1UpdateMultR(subA, gamma,subU);

                CDenseMatrix64F found = A.copy();
                QrHelperFunctions_CD64.rank1UpdateMultR(found, uoff, 1, gamma,
                        A.numRows - j, A.numRows - j, A.numRows, _temp);

                CDenseMatrix64F subFound = CCommonOps.extract(found,A.numRows-j,A.numRows,A.numRows-j,A.numRows);

                outsideIdentical(A, found, j);
                assertTrue(CMatrixFeatures.isEquals(expected, subFound, 1e-8));
            }
        }
    }

    private CDenseMatrix64F rank1UpdateMultR( CDenseMatrix64F A , double gamma,  double u[] ) {
        CDenseMatrix64F U = new CDenseMatrix64F(A.numCols,1);
        U.data = u;
        CDenseMatrix64F Ut = new CDenseMatrix64F(1,A.numCols);
        CCommonOps.transposeConjugate(U,Ut);

        CDenseMatrix64F UUt = new CDenseMatrix64F(A.numCols,A.numCols);
        CCommonOps.mult(gamma,0,U,Ut,UUt);

        CDenseMatrix64F I = CCommonOps.identity(A.numCols);
        CDenseMatrix64F inner = new CDenseMatrix64F(A.numCols,A.numCols);
        CDenseMatrix64F expected = new CDenseMatrix64F(A.numCols,A.numCols);

        CCommonOps.subtract(I,UUt,inner);
        CCommonOps.mult(inner,A,expected);

        return expected;
    }

    @Test
    public void rank1UpdateMultL() {
        double u[] = new double[12*2];
        double subU[] = new double[12*2];
        Complex64F gamma = new Complex64F(0.5,-0.2);

        for (int i = 0; i < u.length; i++) {
            u[i] = (rand.nextDouble()*0.5-1.0)*2;
        }

        for (int i = 1; i < 12; i++) {
            CDenseMatrix64F A = CRandomMatrices.createRandom(i,i,rand);

            for (int j = 1; j <= i; j += 2) {
                CDenseMatrix64F subA = CCommonOps.extract(A,A.numRows-j,A.numRows,A.numRows-j,A.numRows);
                System.arraycopy(u,(A.numRows-j)*2,subU,0,j*2);
                CDenseMatrix64F expected = rank1UpdateMultL(subA,gamma,subU);

                CDenseMatrix64F found = A.copy();
                QrHelperFunctions_CD64.rank1UpdateMultL(found,u,gamma.real,gamma.imaginary,
                        A.numRows-j,A.numRows-j,A.numRows);

                CDenseMatrix64F subFound = CCommonOps.extract(found,A.numRows-j,A.numRows,A.numRows-j,A.numRows);

                outsideIdentical(A, found, j);
                assertTrue(CMatrixFeatures.isEquals(expected, subFound, 1e-8));
            }
        }
    }

    private CDenseMatrix64F rank1UpdateMultL( CDenseMatrix64F A , Complex64F gamma,  double u[] ) {
        CDenseMatrix64F U = new CDenseMatrix64F(A.numCols,1);
        U.data = u;
        CDenseMatrix64F Ut = new CDenseMatrix64F(1,A.numCols);
        CCommonOps.transposeConjugate(U,Ut);

        CDenseMatrix64F UUt = new CDenseMatrix64F(A.numCols,A.numCols);
        CCommonOps.mult(gamma.real,gamma.imaginary,U,Ut,UUt);

        CDenseMatrix64F I = CCommonOps.identity(A.numCols);
        CDenseMatrix64F inner = new CDenseMatrix64F(A.numCols,A.numCols);
        CDenseMatrix64F expected = new CDenseMatrix64F(A.numCols,A.numCols);

        CCommonOps.subtract(I,UUt,inner);
        CCommonOps.mult(A,inner,expected);

        return expected;
    }

    private void outsideIdentical( CDenseMatrix64F A , CDenseMatrix64F B , int width ) {

        int outside = A.numRows-width;

        for (int i = 0; i < A.numRows; i++) {
            for (int j = 0; j < A.numCols; j++) {
                if( i < outside || j < outside ) {
                    assertEquals(A.getReal(i,j),B.getReal(i,j),1e-8);
                    assertEquals(A.getImaginary(i, j), B.getImaginary(i,j),1e-8);
                }
            }
        }
    }
}


text:
package hmi.graphics.collada;

import hmi.xml.XMLFormatting;
import hmi.xml.XMLTokenizer;

import java.io.IOException;
import java.util.ArrayList;

/**
 * Declares the morph targets, their weights, and user defined attributes.
 * @author Job Zwiers
 */
public class Targets extends ColladaElement {

   // attributes: none

   //child elements:
   // at least two Inputs are required, with semantics= "MORPH_TARGET" and semantics="MORPH_WEIGHT".
   private ArrayList<Input> inputs = new ArrayList<Input>();
   private ArrayList<Extra> extras = new ArrayList<Extra>();

   /**
    * Default constructor
    */
   public Targets() {
      super();
   }

   /**
    * Constructor used to create a Targets Object from XML
    */
   public Targets(Collada collada, XMLTokenizer tokenizer) throws IOException {
      super(collada);
      readXML(tokenizer);
   }

   /**
    * Returns the source url for the input with semantic == MORPH_TARGET, or an empty string
    * when there is no such Input element.
    */
   public String getMorphTargetSource() {
      for (Input inp : inputs) {
         if (inp.getSemantic().equals("MORPH_TARGET")) {
             return inp.getSource();
         }
      }
      return "";
  }

   @Override
   public StringBuilder appendContent(StringBuilder buf, XMLFormatting fmt) {
      appendXMLStructureList(buf, fmt, inputs);
      appendXMLStructureList(buf, fmt, extras);
      return buf;
   }

   @Override
   public void decodeContent(XMLTokenizer tokenizer) throws IOException {
      while (tokenizer.atSTag()) {
         String tag = tokenizer.getTagName();
         if (tag.equals(Input.xmlTag()))  {
                 inputs.add(new Input(getCollada(), tokenizer));
         } else if (tag.equals(Extra.xmlTag()))  {
                 extras.add(new Extra(getCollada(), tokenizer));
         } else {
            getCollada().warning(tokenizer.getErrorMessage("Targets: skip : " + tokenizer.getTagName()));
            tokenizer.skipTag();
         }
      }
      addColladaNodes(inputs);
      addColladaNodes(extras);
   }

   /*
    * The XML Stag for XML encoding
    */
   private static final String XMLTAG = "targets";

   /**
    * The XML Stag for XML encoding
    */
   public static String xmlTag() { return XMLTAG; }

   /**
    * returns the XML Stag for XML encoding
    */
   @Override
   public String getXMLTag() {
      return XMLTAG;
   }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="CoreNLP-to-HTML.xsl" type="text/xsl"?>
<root>
  <document>
    <sentences>
      <sentence id="1">
        <tokens>
          <token id="1">
            <word>first</word>
            <lemma>first</lemma>
            <CharacterOffsetBegin>0</CharacterOffsetBegin>
            <CharacterOffsetEnd>5</CharacterOffsetEnd>
            <POS>RB</POS>
          </token>
          <token id="2">
            <word>appearance</word>
            <lemma>appearance</lemma>
            <CharacterOffsetBegin>6</CharacterOffsetBegin>
            <CharacterOffsetEnd>16</CharacterOffsetEnd>
            <POS>NN</POS>
          </token>
          <token id="3">
            <word>of</word>
            <lemma>of</lemma>
            <CharacterOffsetBegin>17</CharacterOffsetBegin>
            <CharacterOffsetEnd>19</CharacterOffsetEnd>
            <POS>IN</POS>
          </token>
          <token id="4">
            <word>Superboy</word>
            <lemma>Superboy</lemma>
            <CharacterOffsetBegin>20</CharacterOffsetBegin>
            <CharacterOffsetEnd>28</CharacterOffsetEnd>
            <POS>NNP</POS>
          </token>
          <token id="5">
            <word>debut</word>
            <lemma>debut</lemma>
            <CharacterOffsetBegin>29</CharacterOffsetBegin>
            <CharacterOffsetEnd>34</CharacterOffsetEnd>
            <POS>NN</POS>
          </token>
        </tokens>
        <parse>(ROOT (NP (NP (RB first) (NN appearance)) (PP (IN of) (NP (NNP Superboy) (NN debut))))) </parse>
        <dependencies type="basic-dependencies">
          <dep type="root">
            <governor idx="0">ROOT</governor>
            <dependent idx="2">appearance</dependent>
          </dep>
          <dep type="advmod">
            <governor idx="2">appearance</governor>
            <dependent idx="1">first</dependent>
          </dep>
          <dep type="prep">
            <governor idx="2">appearance</governor>
            <dependent idx="3">of</dependent>
          </dep>
          <dep type="nn">
            <governor idx="5">debut</governor>
            <dependent idx="4">Superboy</dependent>
          </dep>
          <dep type="pobj">
            <governor idx="3">of</governor>
            <dependent idx="5">debut</dependent>
          </dep>
        </dependencies>
        <dependencies type="collapsed-dependencies">
          <dep type="root">
            <governor idx="0">ROOT</governor>
            <dependent idx="2">appearance</dependent>
          </dep>
          <dep type="advmod">
            <governor idx="2">appearance</governor>
            <dependent idx="1">first</dependent>
          </dep>
          <dep type="nn">
            <governor idx="5">debut</governor>
            <dependent idx="4">Superboy</dependent>
          </dep>
          <dep type="prep_of">
            <governor idx="2">appearance</governor>
            <dependent idx="5">debut</dependent>
          </dep>
        </dependencies>
        <dependencies type="collapsed-ccprocessed-dependencies">
          <dep type="root">
            <governor idx="0">ROOT</governor>
            <dependent idx="2">appearance</dependent>
          </dep>
          <dep type="advmod">
            <governor idx="2">appearance</governor>
            <dependent idx="1">first</dependent>
          </dep>
          <dep type="nn">
            <governor idx="5">debut</governor>
            <dependent idx="4">Superboy</dependent>
          </dep>
          <dep type="prep_of">
            <governor idx="2">appearance</governor>
            <dependent idx="5">debut</dependent>
          </dep>
        </dependencies>
      </sentence>
    </sentences>
  </document>
</root>


text:
#pragma once
#include "watchman_system.h"
#include <chrono>

/* Return a timespec holding the equivalent of the supplied duration */
template <class Rep, class Period>
inline timespec
durationToTimeSpecDuration(const std::chrono::duration<Rep, Period> &d) {
  timespec ts{0,0};

  ts.tv_sec = std::chrono::duration_cast<std::chrono::seconds>(d).count();
  ts.tv_nsec = std::chrono::duration_cast<std::chrono::nanoseconds>(
                   d - std::chrono::seconds(ts.tv_sec))
                   .count();
  return ts;
}

/* Return a timespec holding an absolute time equivalent to the provided
 * system_clock timepoint */
inline timespec
systemClockToTimeSpec(const std::chrono::system_clock::time_point &p) {
  /* It just so happens that the epoch for system_clock is the same as the
   * epoch for timespec, so we can use our duration helper on the duration
   * since the epoch. */
  return durationToTimeSpecDuration(p.time_since_epoch());
}

void w_timeoutms_to_abs_timespec(int timeoutms, struct timespec *deadline);

/* compare two timevals and return -1 if a is < b, 0 if a == b,
 * or 1 if b > a */
static inline int w_timeval_compare(struct timeval a, struct timeval b)
{
  if (a.tv_sec < b.tv_sec) {
    return -1;
  }
  if (a.tv_sec > b.tv_sec) {
    return 1;
  }
  if (a.tv_usec < b.tv_usec) {
    return -1;
  }
  if (a.tv_usec > b.tv_usec) {
    return 1;
  }
  return 0;
}

#define WATCHMAN_USEC_IN_SEC 1000000
#define WATCHMAN_NSEC_IN_USEC 1000
#define WATCHMAN_NSEC_IN_SEC (1000 * 1000 * 1000)
#define WATCHMAN_NSEC_IN_MSEC 1000000

#if defined(__APPLE__) || defined(__FreeBSD__) \
 || (defined(__NetBSD__) && (__NetBSD_Version__ < 6099000000))
/* BSD-style subsecond timespec */
#define WATCHMAN_ST_TIMESPEC(type) st_##type##timespec
#else
/* POSIX standard timespec */
#define WATCHMAN_ST_TIMESPEC(type) st_##type##tim
#endif

static inline void w_timeval_add(const struct timeval a,
    const struct timeval b, struct timeval *result)
{
  result->tv_sec = a.tv_sec + b.tv_sec;
  result->tv_usec = a.tv_usec + b.tv_usec;

  if (result->tv_usec > WATCHMAN_USEC_IN_SEC) {
    result->tv_sec++;
    result->tv_usec -= WATCHMAN_USEC_IN_SEC;
  }
}

static inline void w_timeval_sub(const struct timeval a,
    const struct timeval b, struct timeval *result)
{
  result->tv_sec = a.tv_sec - b.tv_sec;
  result->tv_usec = a.tv_usec - b.tv_usec;

  if (result->tv_usec < 0) {
    result->tv_sec--;
    result->tv_usec += WATCHMAN_USEC_IN_SEC;
  }
}

static inline void w_timeval_to_timespec(
    const struct timeval a, struct timespec *ts)
{
  ts->tv_sec = a.tv_sec;
  ts->tv_nsec = a.tv_usec * WATCHMAN_NSEC_IN_USEC;
}

static inline void w_timespec_to_timeval(
    const struct timespec ts, struct timeval *tv) {
  tv->tv_sec = ts.tv_sec;
  tv->tv_usec = ts.tv_nsec / WATCHMAN_NSEC_IN_USEC;
}

// Convert a timeval to a double that holds the fractional number of seconds
static inline double w_timeval_abs_seconds(struct timeval tv){
  double val = (double)tv.tv_sec;
  val += ((double)tv.tv_usec)/WATCHMAN_USEC_IN_SEC;
  return val;
}

static inline double w_timeval_diff(struct timeval start, struct timeval end)
{
  double s = start.tv_sec + ((double)start.tv_usec)/WATCHMAN_USEC_IN_SEC;
  double e = end.tv_sec + ((double)end.tv_usec)/WATCHMAN_USEC_IN_SEC;

  return e - s;
}


text:
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {StoreModule} from '@ngrx/store';
import {EffectsModule} from '@ngrx/effects';
import {RoleDirective} from './directive/role.directive';
import {ClarityModule} from '@clr/angular';
import {SharedModule} from '../shared/shared.module';
import {RolesMissingComponent} from './component/roles-missing.component';
import {FeatureDisabledComponent} from './component/feature-disabled.component';
import {AuthenticationRequiredComponent} from './component/authentication-required.component';
import {SecurityRoutingModule} from './security-routing.module';
import {SecurityGuard} from './support/security.guard';
import {HTTP_INTERCEPTORS} from '@angular/common/http';
import * as fromSecurity from './store/security.reducer';
import {SecurityEffect} from './store/security.effect';
import {SecurityInterceptor} from './support/security.interceptor';

@NgModule({
  declarations: [RoleDirective, RolesMissingComponent, FeatureDisabledComponent, AuthenticationRequiredComponent],
  imports: [
    CommonModule,
    ClarityModule,
    SharedModule,
    SecurityRoutingModule,
    StoreModule.forFeature(fromSecurity.securityFeatureKey, fromSecurity.reducer),
    EffectsModule.forFeature([SecurityEffect])
  ],
  providers: [
    SecurityGuard,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: SecurityInterceptor,
      multi: true
    }
  ],
  exports: [RoleDirective]
})
export class SecurityModule {}