text:
// Code generated by the Pulumi SDK Generator DO NOT EDIT.
// *** WARNING: Do not edit by hand unless you're certain you know what you are doing! ***

package cloudwatch

import (
	"context"
	"reflect"

	"errors"
	"github.com/pulumi/pulumi-aws-native/sdk/go/aws/internal"
	"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)

// Resource Type definition for AWS::CloudWatch::Alarm
type Alarm struct {
	pulumi.CustomResourceState

	// Indicates whether actions should be executed during any changes to the alarm state. The default is TRUE.
	ActionsEnabled pulumi.BoolPtrOutput `pulumi:"actionsEnabled"`
	// The list of actions to execute when this alarm transitions into an ALARM state from any other state.
	AlarmActions pulumi.StringArrayOutput `pulumi:"alarmActions"`
	// The description of the alarm.
	AlarmDescription pulumi.StringPtrOutput `pulumi:"alarmDescription"`
	// The name of the alarm.
	AlarmName pulumi.StringPtrOutput `pulumi:"alarmName"`
	// Amazon Resource Name is a unique name for each resource.
	Arn pulumi.StringOutput `pulumi:"arn"`
	// The arithmetic operation to use when comparing the specified statistic and threshold.
	ComparisonOperator pulumi.StringOutput `pulumi:"comparisonOperator"`
	// The number of datapoints that must be breaching to trigger the alarm.
	DatapointsToAlarm pulumi.IntPtrOutput `pulumi:"datapointsToAlarm"`
	// The dimensions for the metric associated with the alarm. For an alarm based on a math expression, you can't specify Dimensions. Instead, you use Metrics.
	Dimensions AlarmDimensionArrayOutput `pulumi:"dimensions"`
	// Used only for alarms based on percentiles.
	EvaluateLowSampleCountPercentile pulumi.StringPtrOutput `pulumi:"evaluateLowSampleCountPercentile"`
	// The number of periods over which data is compared to the specified threshold.
	EvaluationPeriods pulumi.IntOutput `pulumi:"evaluationPeriods"`
	// The percentile statistic for the metric associated with the alarm. Specify a value between p0.0 and p100.
	ExtendedStatistic pulumi.StringPtrOutput `pulumi:"extendedStatistic"`
	// The actions to execute when this alarm transitions to the INSUFFICIENT_DATA state from any other state.
	InsufficientDataActions pulumi.StringArrayOutput `pulumi:"insufficientDataActions"`
	// The name of the metric associated with the alarm.
	MetricName pulumi.StringPtrOutput `pulumi:"metricName"`
	// An array that enables you to create an alarm based on the result of a metric math expression.
	Metrics AlarmMetricDataQueryArrayOutput `pulumi:"metrics"`
	// The namespace of the metric associated with the alarm.
	Namespace pulumi.StringPtrOutput `pulumi:"namespace"`
	// The actions to execute when this alarm transitions to the OK state from any other state.
	OkActions pulumi.StringArrayOutput `pulumi:"okActions"`
	// The period in seconds, over which the statistic is applied.
	Period pulumi.IntPtrOutput `pulumi:"period"`
	// The statistic for the metric associated with the alarm, other than percentile.
	Statistic pulumi.StringPtrOutput `pulumi:"statistic"`
	// In an alarm based on an anomaly detection model, this is the ID of the ANOMALY_DETECTION_BAND function used as the threshold for the alarm.
	Threshold pulumi.Float64PtrOutput `pulumi:"threshold"`
	// In an alarm based on an anomaly detection model, this is the ID of the ANOMALY_DETECTION_BAND function used as the threshold for the alarm.
	ThresholdMetricId pulumi.StringPtrOutput `pulumi:"thresholdMetricId"`
	// Sets how this alarm is to handle missing data points. Valid values are breaching, notBreaching, ignore, and missing.
	TreatMissingData pulumi.StringPtrOutput `pulumi:"treatMissingData"`
	// The unit of the metric associated with the alarm.
	Unit pulumi.StringPtrOutput `pulumi:"unit"`
}

// NewAlarm registers a new resource with the given unique name, arguments, and options.
func NewAlarm(ctx *pulumi.Context,
	name string, args *AlarmArgs, opts ...pulumi.ResourceOption) (*Alarm, error) {
	if args == nil {
		return nil, errors.New("missing one or more required arguments")
	}

	if args.ComparisonOperator == nil {
		return nil, errors.New("invalid value for required argument 'ComparisonOperator'")
	}
	if args.EvaluationPeriods == nil {
		return nil, errors.New("invalid value for required argument 'EvaluationPeriods'")
	}
	opts = internal.PkgResourceDefaultOpts(opts)
	var resource Alarm
	err := ctx.RegisterResource("aws-native:cloudwatch:Alarm", name, args, &resource, opts...)
	if err != nil {
		return nil, err
	}
	return &resource, nil
}

// GetAlarm gets an existing Alarm resource's state with the given name, ID, and optional
// state properties that are used to uniquely qualify the lookup (nil if not required).
func GetAlarm(ctx *pulumi.Context,
	name string, id pulumi.IDInput, state *AlarmState, opts ...pulumi.ResourceOption) (*Alarm, error) {
	var resource Alarm
	err := ctx.ReadResource("aws-native:cloudwatch:Alarm", name, id, state, &resource, opts...)
	if err != nil {
		return nil, err
	}
	return &resource, nil
}

// Input properties used for looking up and filtering Alarm resources.
type alarmState struct {
}

type AlarmState struct {
}

func (AlarmState) ElementType() reflect.Type {
	return reflect.TypeOf((*alarmState)(nil)).Elem()
}

type alarmArgs struct {
	// Indicates whether actions should be executed during any changes to the alarm state. The default is TRUE.
	ActionsEnabled *bool `pulumi:"actionsEnabled"`
	// The list of actions to execute when this alarm transitions into an ALARM state from any other state.
	AlarmActions []string `pulumi:"alarmActions"`
	// The description of the alarm.
	AlarmDescription *string `pulumi:"alarmDescription"`
	// The name of the alarm.
	AlarmName *string `pulumi:"alarmName"`
	// The arithmetic operation to use when comparing the specified statistic and threshold.
	ComparisonOperator string `pulumi:"comparisonOperator"`
	// The number of datapoints that must be breaching to trigger the alarm.
	DatapointsToAlarm *int `pulumi:"datapointsToAlarm"`
	// The dimensions for the metric associated with the alarm. For an alarm based on a math expression, you can't specify Dimensions. Instead, you use Metrics.
	Dimensions []AlarmDimension `pulumi:"dimensions"`
	// Used only for alarms based on percentiles.
	EvaluateLowSampleCountPercentile *string `pulumi:"evaluateLowSampleCountPercentile"`
	// The number of periods over which data is compared to the specified threshold.
	EvaluationPeriods int `pulumi:"evaluationPeriods"`
	// The percentile statistic for the metric associated with the alarm. Specify a value between p0.0 and p100.
	ExtendedStatistic *string `pulumi:"extendedStatistic"`
	// The actions to execute when this alarm transitions to the INSUFFICIENT_DATA state from any other state.
	InsufficientDataActions []string `pulumi:"insufficientDataActions"`
	// The name of the metric associated with the alarm.
	MetricName *string `pulumi:"metricName"`
	// An array that enables you to create an alarm based on the result of a metric math expression.
	Metrics []AlarmMetricDataQuery `pulumi:"metrics"`
	// The namespace of the metric associated with the alarm.
	Namespace *string `pulumi:"namespace"`
	// The actions to execute when this alarm transitions to the OK state from any other state.
	OkActions []string `pulumi:"okActions"`
	// The period in seconds, over which the statistic is applied.
	Period *int `pulumi:"period"`
	// The statistic for the metric associated with the alarm, other than percentile.
	Statistic *string `pulumi:"statistic"`
	// In an alarm based on an anomaly detection model, this is the ID of the ANOMALY_DETECTION_BAND function used as the threshold for the alarm.
	Threshold *float64 `pulumi:"threshold"`
	// In an alarm based on an anomaly detection model, this is the ID of the ANOMALY_DETECTION_BAND function used as the threshold for the alarm.
	ThresholdMetricId *string `pulumi:"thresholdMetricId"`
	// Sets how this alarm is to handle missing data points. Valid values are breaching, notBreaching, ignore, and missing.
	TreatMissingData *string `pulumi:"treatMissingData"`
	// The unit of the metric associated with the alarm.
	Unit *string `pulumi:"unit"`
}

// The set of arguments for constructing a Alarm resource.
type AlarmArgs struct {
	// Indicates whether actions should be executed during any changes to the alarm state. The default is TRUE.
	ActionsEnabled pulumi.BoolPtrInput
	// The list of actions to execute when this alarm transitions into an ALARM state from any other state.
	AlarmActions pulumi.StringArrayInput
	// The description of the alarm.
	AlarmDescription pulumi.StringPtrInput
	// The name of the alarm.
	AlarmName pulumi.StringPtrInput
	// The arithmetic operation to use when comparing the specified statistic and threshold.
	ComparisonOperator pulumi.StringInput
	// The number of datapoints that must be breaching to trigger the alarm.
	DatapointsToAlarm pulumi.IntPtrInput
	// The dimensions for the metric associated with the alarm. For an alarm based on a math expression, you can't specify Dimensions. Instead, you use Metrics.
	Dimensions AlarmDimensionArrayInput
	// Used only for alarms based on percentiles.
	EvaluateLowSampleCountPercentile pulumi.StringPtrInput
	// The number of periods over which data is compared to the specified threshold.
	EvaluationPeriods pulumi.IntInput
	// The percentile statistic for the metric associated with the alarm. Specify a value between p0.0 and p100.
	ExtendedStatistic pulumi.StringPtrInput
	// The actions to execute when this alarm transitions to the INSUFFICIENT_DATA state from any other state.
	InsufficientDataActions pulumi.StringArrayInput
	// The name of the metric associated with the alarm.
	MetricName pulumi.StringPtrInput
	// An array that enables you to create an alarm based on the result of a metric math expression.
	Metrics AlarmMetricDataQueryArrayInput
	// The namespace of the metric associated with the alarm.
	Namespace pulumi.StringPtrInput
	// The actions to execute when this alarm transitions to the OK state from any other state.
	OkActions pulumi.StringArrayInput
	// The period in seconds, over which the statistic is applied.
	Period pulumi.IntPtrInput
	// The statistic for the metric associated with the alarm, other than percentile.
	Statistic pulumi.StringPtrInput
	// In an alarm based on an anomaly detection model, this is the ID of the ANOMALY_DETECTION_BAND function used as the threshold for the alarm.
	Threshold pulumi.Float64PtrInput
	// In an alarm based on an anomaly detection model, this is the ID of the ANOMALY_DETECTION_BAND function used as the threshold for the alarm.
	ThresholdMetricId pulumi.StringPtrInput
	// Sets how this alarm is to handle missing data points. Valid values are breaching, notBreaching, ignore, and missing.
	TreatMissingData pulumi.StringPtrInput
	// The unit of the metric associated with the alarm.
	Unit pulumi.StringPtrInput
}

func (AlarmArgs) ElementType() reflect.Type {
	return reflect.TypeOf((*alarmArgs)(nil)).Elem()
}

type AlarmInput interface {
	pulumi.Input

	ToAlarmOutput() AlarmOutput
	ToAlarmOutputWithContext(ctx context.Context) AlarmOutput
}

func (*Alarm) ElementType() reflect.Type {
	return reflect.TypeOf((**Alarm)(nil)).Elem()
}

func (i *Alarm) ToAlarmOutput() AlarmOutput {
	return i.ToAlarmOutputWithContext(context.Background())
}

func (i *Alarm) ToAlarmOutputWithContext(ctx context.Context) AlarmOutput {
	return pulumi.ToOutputWithContext(ctx, i).(AlarmOutput)
}

type AlarmOutput struct{ *pulumi.OutputState }

func (AlarmOutput) ElementType() reflect.Type {
	return reflect.TypeOf((**Alarm)(nil)).Elem()
}

func (o AlarmOutput) ToAlarmOutput() AlarmOutput {
	return o
}

func (o AlarmOutput) ToAlarmOutputWithContext(ctx context.Context) AlarmOutput {
	return o
}

// Indicates whether actions should be executed during any changes to the alarm state. The default is TRUE.
func (o AlarmOutput) ActionsEnabled() pulumi.BoolPtrOutput {
	return o.ApplyT(func(v *Alarm) pulumi.BoolPtrOutput { return v.ActionsEnabled }).(pulumi.BoolPtrOutput)
}

// The list of actions to execute when this alarm transitions into an ALARM state from any other state.
func (o AlarmOutput) AlarmActions() pulumi.StringArrayOutput {
	return o.ApplyT(func(v *Alarm) pulumi.StringArrayOutput { return v.AlarmActions }).(pulumi.StringArrayOutput)
}

// The description of the alarm.
func (o AlarmOutput) AlarmDescription() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Alarm) pulumi.StringPtrOutput { return v.AlarmDescription }).(pulumi.StringPtrOutput)
}

// The name of the alarm.
func (o AlarmOutput) AlarmName() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Alarm) pulumi.StringPtrOutput { return v.AlarmName }).(pulumi.StringPtrOutput)
}

// Amazon Resource Name is a unique name for each resource.
func (o AlarmOutput) Arn() pulumi.StringOutput {
	return o.ApplyT(func(v *Alarm) pulumi.StringOutput { return v.Arn }).(pulumi.StringOutput)
}

// The arithmetic operation to use when comparing the specified statistic and threshold.
func (o AlarmOutput) ComparisonOperator() pulumi.StringOutput {
	return o.ApplyT(func(v *Alarm) pulumi.StringOutput { return v.ComparisonOperator }).(pulumi.StringOutput)
}

// The number of datapoints that must be breaching to trigger the alarm.
func (o AlarmOutput) DatapointsToAlarm() pulumi.IntPtrOutput {
	return o.ApplyT(func(v *Alarm) pulumi.IntPtrOutput { return v.DatapointsToAlarm }).(pulumi.IntPtrOutput)
}

// The dimensions for the metric associated with the alarm. For an alarm based on a math expression, you can't specify Dimensions. Instead, you use Metrics.
func (o AlarmOutput) Dimensions() AlarmDimensionArrayOutput {
	return o.ApplyT(func(v *Alarm) AlarmDimensionArrayOutput { return v.Dimensions }).(AlarmDimensionArrayOutput)
}

// Used only for alarms based on percentiles.
func (o AlarmOutput) EvaluateLowSampleCountPercentile() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Alarm) pulumi.StringPtrOutput { return v.EvaluateLowSampleCountPercentile }).(pulumi.StringPtrOutput)
}

// The number of periods over which data is compared to the specified threshold.
func (o AlarmOutput) EvaluationPeriods() pulumi.IntOutput {
	return o.ApplyT(func(v *Alarm) pulumi.IntOutput { return v.EvaluationPeriods }).(pulumi.IntOutput)
}

// The percentile statistic for the metric associated with the alarm. Specify a value between p0.0 and p100.
func (o AlarmOutput) ExtendedStatistic() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Alarm) pulumi.StringPtrOutput { return v.ExtendedStatistic }).(pulumi.StringPtrOutput)
}

// The actions to execute when this alarm transitions to the INSUFFICIENT_DATA state from any other state.
func (o AlarmOutput) InsufficientDataActions() pulumi.StringArrayOutput {
	return o.ApplyT(func(v *Alarm) pulumi.StringArrayOutput { return v.InsufficientDataActions }).(pulumi.StringArrayOutput)
}

// The name of the metric associated with the alarm.
func (o AlarmOutput) MetricName() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Alarm) pulumi.StringPtrOutput { return v.MetricName }).(pulumi.StringPtrOutput)
}

// An array that enables you to create an alarm based on the result of a metric math expression.
func (o AlarmOutput) Metrics() AlarmMetricDataQueryArrayOutput {
	return o.ApplyT(func(v *Alarm) AlarmMetricDataQueryArrayOutput { return v.Metrics }).(AlarmMetricDataQueryArrayOutput)
}

// The namespace of the metric associated with the alarm.
func (o AlarmOutput) Namespace() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Alarm) pulumi.StringPtrOutput { return v.Namespace }).(pulumi.StringPtrOutput)
}

// The actions to execute when this alarm transitions to the OK state from any other state.
func (o AlarmOutput) OkActions() pulumi.StringArrayOutput {
	return o.ApplyT(func(v *Alarm) pulumi.StringArrayOutput { return v.OkActions }).(pulumi.StringArrayOutput)
}

// The period in seconds, over which the statistic is applied.
func (o AlarmOutput) Period() pulumi.IntPtrOutput {
	return o.ApplyT(func(v *Alarm) pulumi.IntPtrOutput { return v.Period }).(pulumi.IntPtrOutput)
}

// The statistic for the metric associated with the alarm, other than percentile.
func (o AlarmOutput) Statistic() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Alarm) pulumi.StringPtrOutput { return v.Statistic }).(pulumi.StringPtrOutput)
}

// In an alarm based on an anomaly detection model, this is the ID of the ANOMALY_DETECTION_BAND function used as the threshold for the alarm.
func (o AlarmOutput) Threshold() pulumi.Float64PtrOutput {
	return o.ApplyT(func(v *Alarm) pulumi.Float64PtrOutput { return v.Threshold }).(pulumi.Float64PtrOutput)
}

// In an alarm based on an anomaly detection model, this is the ID of the ANOMALY_DETECTION_BAND function used as the threshold for the alarm.
func (o AlarmOutput) ThresholdMetricId() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Alarm) pulumi.StringPtrOutput { return v.ThresholdMetricId }).(pulumi.StringPtrOutput)
}

// Sets how this alarm is to handle missing data points. Valid values are breaching, notBreaching, ignore, and missing.
func (o AlarmOutput) TreatMissingData() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Alarm) pulumi.StringPtrOutput { return v.TreatMissingData }).(pulumi.StringPtrOutput)
}

// The unit of the metric associated with the alarm.
func (o AlarmOutput) Unit() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Alarm) pulumi.StringPtrOutput { return v.Unit }).(pulumi.StringPtrOutput)
}

func init() {
	pulumi.RegisterInputType(reflect.TypeOf((*AlarmInput)(nil)).Elem(), &Alarm{})
	pulumi.RegisterOutputType(AlarmOutput{})
}

repository: pulumi/pulumi-aws-native

repo_name: pulumi/pulumi-aws-native

gha_language: Go


text:
#pragma once

// Copyright (c) 2015 University of Waterloo
//
// The contents of this file are covered under the licence agreement in
// the file "LICENCE" distributed with this repository.

#include <utility>
#include <vector>

#include "merge.h"

#include "data/range.h"

/// Default (do nothing) "on index change" behaviour for `for_each_combo`
template<typename Q>
struct default_on_index_change {

    /// Called before first combination, queues in `qs` guaranteed to be all non-empty.
    void init( const std::vector<Q>& qs ) {}

    /// Called before incrementing the counter for queue `i` of `qs`, currently valued `j`
    void inc( const std::vector<Q>& qs, unsigned i, unsigned j ) {}

    /// Called before resetting the counter for queue `i` of `qs` (currently valued `j`) to zero.
    void reset( const std::vector<Q>& qs, unsigned i, unsigned j ) {}
};

/// Given a vector of random-access queues of `T`, for each combination of elements from the
/// input queues, call a function on the queue elements.
///
/// @param T	        The type of the queue elements.
/// @param Q	        The type of the queues of `T`
/// @param F	        The function to apply to the combinations;
/// 			        given a reference to `qs` and a std::vector<unsigned> holding the indices.
/// @param OnChange     The behaviour to apply on index change.
///                     Has functions matching the signatures of default_on_index_change<Q>.
///
/// @param qs	        The queues to take combinations from
/// @param f	        A function of type `F` to call
/// @param on_change    Behaviour to apply on index change.
template<typename T, typename Q, typename F, typename OnChange>
void for_each_combo( const std::vector<Q>& qs, F f, OnChange& on_change ) {
	unsigned n = qs.size();  // number of queues to merge

    for ( auto& q : qs ) if ( q.empty() ) return;
    Indices inds( n, 0 );  // indices into merging queues

    on_change.init( qs );

    while (true) {
        f( qs, inds );  // run loop iteration

        // iterate to next index
        unsigned i = n-1;
        while (true) {
            unsigned j = inds[i];

            // increment index if can be done without rollover
            if ( j+1 < qs[i].size() ) {
                on_change.inc( qs, i, j );
                inds[i] += 1;
                break;
            }

            // seen all combinations if about to roll over zero-queue
            if ( i == 0 ) return;

            // otherwise roll over to next queue
            on_change.reset( qs, i, j );
            inds[i] = 0;
            --i;
        }
    }
}

/// `for_each_combo` specialized to use default (no-op) OnChange.
template<typename T, typename Q, typename F>
inline void for_each_combo( const std::vector<Q>& qs, F f ) {
    default_on_index_change<Q> on_change;
    for_each_combo<T>( qs, std::forward(f), on_change );
}

/// Wraps a vector with an added default first element.
/// Provided functions are sufficient for use in for_each_combo and friends.
///
/// @param T    Element type of the vector
/// @param Q    Underlying vector type
template<typename T, typename Q = std::vector<T>>
class defaulted_vector {
    const T& head;  ///< First (default) element
    const Q& tail;  ///< Remainder of vector

public:
    using size_type = typename Q::size_type;

    defaulted_vector( const T& head, const Q& tail ) : head(head), tail(tail) {}

    const T& operator[] ( size_type i ) const { return ( i == 0 ) ? head : tail[i-1]; }

    size_type size() const { return tail.size() + 1; }

    bool empty() const { return false; }
};

/// Wraps a range with an added default first element.
/// Provided functions are sufficient for use in for_each_combo and friends.
///
/// @param T    Element type of the range
/// @param I    Underlying range iterator type
template<typename T, typename I>
class defaulted_range {
    const T& head;  ///< First (default) element
    range<I> tail;  ///< Remainder of range

public:
    using size_type = typename range<I>::size_type;

    defaulted_range( const T& head, range<I>&& tail ) : head(head), tail( std::move(tail) ) {}

    const T& operator[] ( size_type i ) const { return ( i == 0 ) ? head : tail[i-1]; }

    size_type size() const { return tail.size() + 1; }

    bool empty() const { return false; }
};

repository: cforall/resolv-proto

license_type: permissive

repo_name: cforall/resolv-proto

branch_name: refs/heads/master

extension: h


text:
#include <windows.h>

#include "detours.h"

#include <vector>
#include <iostream>

std::vector<unsigned long long> g_handles;

#define UPDATE_ACCESS CTL_CODE(FILE_DEVICE_UNKNOWN, 0x800, METHOD_OUT_DIRECT, FILE_ANY_ACCESS)

typedef struct _handle_information
{
	unsigned long process_id;
	unsigned long access;
	unsigned long long handle;
}handle_information, * phandle_information;

bool push_kernel_system(unsigned long long handle)
{
	HANDLE h = CreateFileA("\\\\.\\handle_access", 0, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
	if (h == INVALID_HANDLE_VALUE) return false;

	handle_information info{ 0 };
	info.process_id = GetCurrentProcessId();
	info.access = 0x1fffff;
	info.handle = handle;

	DWORD r = 0;
	BOOL ret = DeviceIoControl(h, UPDATE_ACCESS, &info, sizeof(info), 0, 0, &r, 0);

	CloseHandle(h);
	return ret == TRUE;
}

/*
开启一个线程来不断提权
有的反作弊系统会不定时扫描句柄权限,发现有读写权限就会抹去权限,抹去的话我们有加回来,来场拉锯战吧
我就不信反作弊系统的检测线程比我还频繁
*/
unsigned long __stdcall grant_access_thread(void*)
{
	while (true)
	{
		for (const auto& it : g_handles) push_kernel_system(it);
		Sleep(50);
	}
}

typedef HANDLE(WINAPI* FOpenProcess)(DWORD, BOOL, DWORD);
FOpenProcess _OpenProcess = OpenProcess;

HANDLE WINAPI MyOpenProcess(
	_In_ DWORD dwDesiredAccess,
	_In_ BOOL bInheritHandle,
	_In_ DWORD dwProcessId)
{
	// 以最低的权限打开进程(不然反作弊系统会拦截)
	// 拿到低权限句柄后再进行提权操作
	HANDLE h = _OpenProcess(PROCESS_QUERY_INFORMATION, bInheritHandle, dwProcessId);
	if (h)
	{
		unsigned long long handle = (unsigned long long)h;
		push_kernel_system(handle);
		g_handles.push_back(handle);
	}
	return h;
}

typedef BOOL(WINAPI* FCloseHandle)(HANDLE);
FCloseHandle _CloseHandle = CloseHandle;

BOOL WINAPI MyCloseHandle(
	_In_ _Post_ptr_invalid_ HANDLE hObject)
{
	for (auto it = g_handles.begin(); it != g_handles.end(); it++)
	{
		if (*it == (unsigned long long)hObject)
		{
			g_handles.erase(it);
			break;
		}
	}

	return _CloseHandle(hObject);
}

bool init()
{
	DetourTransactionBegin();
	DetourUpdateThread(GetCurrentThread());
	DetourAttach(&(PVOID&)_OpenProcess, MyOpenProcess);
	DetourAttach(&(PVOID&)_CloseHandle, MyCloseHandle);
	DetourTransactionCommit();

	CreateThread(0, 0, grant_access_thread, 0, 0, 0);
	MessageBoxA(0, "提权模块加载", "温馨提示", MB_OK | MB_ICONINFORMATION);
	return true;
}

static bool g = init();

license: MIT

branch_name: refs/heads/main

extension: cpp


text:
package rove

import (
	"fmt"

	"github.com/josephspurrier/rove/pkg/changeset"
)

// Status will output all changesets from the database table and will return
// an error, the last changeset, or a blank string. Check in that order.
func (r *Rove) Status() (*changeset.Record, error) {
	var last *changeset.Record

	// Get an array of changesets from the database.
	results, err := r.db.Changesets(false)
	if err != nil {
		return nil, err
	}

	if len(results) == 0 {
		if r.Verbose {
			fmt.Println("No changesets applied to the database.")
		}
		return nil, nil
	}

	if r.Verbose {
		fmt.Println("Changesets applied:")
	}

	// Loop through each changeset.
	for _, rs := range results {
		last = &rs
		if r.Verbose {
			fmt.Printf("%v\n", rs.String())
		}
	}

	return last, nil
}

repository: josephspurrier/rove

repo_name: josephspurrier/rove

gha_license_id: MIT

extension: go


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

public class Fantasma : IEnemy {

    private GameObject player;

    [SerializeField]
    private float followSpeed;
    [SerializeField]
    private float playerSpeedModifier;

	// Use this for initialization
	void Start () {
        player = GameObject.Find("Player");
        currentHP = maxHP;
	}

	// Update is called once per frame
	void Update () {
        Move();
	}

    void Move()
    {
        float originalZ = transform.position.z;

        transform.position = Vector2.MoveTowards(transform.position, player.transform.position, followSpeed);
        transform.position = new Vector3(transform.position.x, transform.position.y, originalZ);

        transform.position += new Vector3(0, Mathf.Sin(Time.time * 3)/120 ,0);
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Weapon"))
        {
            TakeDamage(collision.gameObject, collision.gameObject.GetComponent<IWeapon>().GetKnockback(), collision.gameObject.GetComponent<IWeapon>().GetWeaponDamage());

            if (collision.gameObject.name == "PlayerArrow(Clone)")
            {
                GameObject.Destroy(collision.gameObject);
            }
        }

        if (collision.gameObject.name == "Player")
        {
            collision.gameObject.GetComponent<PlayerMovement>().walkSpeed /= playerSpeedModifier;
        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.gameObject.name == "Player")
        {
            collision.gameObject.GetComponent<PlayerMovement>().walkSpeed *= playerSpeedModifier;
        }
    }
}

repository: VDSMath/NAMELESS

repo_name: VDSMath/NAMELESS

extension: cs


text:
@InProceedings{orozco-soto:case:2022,
  author    = {Orozco-Soto, Santos M. and Ibarra-Zannnatha, Juan M. and Kheddar, Abderrahmane},
  title     = {Robust Position Regulation of a Seesaw Actuated by a Humanoid},
  booktitle = {IEEE International Conference on Automation Science and Engineering},
  year      = {2022},
  address   = {Mexico City, Mexico},
  month     = {August 20-August 24},
  url       = {https://ieeexplore.ieee.org/document/9926663},
  doi       = {10.1109/CASE49997.2022.9926663}
}

gha_language: TeX

extension: bib


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

namespace EnterpriseWebLibrary.EnterpriseWebFramework.Controls {
	/// <summary>
	/// An element that hovers over the page in the center of the browser window and prevents interaction with the page. There can only be one modal window
	/// visible at a time. This control is intended to be used with LaunchWindowLink.
	/// </summary>
	public class ModalWindow: EtherealControl {
		internal class CssElementCreator: ControlCssElementCreator {
			internal const string CssClass = "ewfModal";

			IReadOnlyCollection<CssElement> ControlCssElementCreator.CreateCssElements() {
				return new[] { new CssElement( "ModalSectionContainer", "div." + CssClass ) };
			}
		}

		private readonly WebControl control;
		private readonly bool open;

		/// <summary>
		/// Creates a modal window.
		/// </summary>
		public ModalWindow( Control parent, Control content, string title = "", bool open = false ): this( parent, content, title: title, postBack: null, open: open ) {}

		internal ModalWindow( Control parent, Control content, string title = "", PostBack postBack = null, bool open = false ) {
			control = new Block( new Section( title, content.ToCollection().Concat( getButtonTable( postBack ) ) ) ) { CssClass = CssElementCreator.CssClass };
			this.open = open;

			EwfPage.Instance.AddEtherealControl( parent, this );
		}

		private IEnumerable<Control> getButtonTable( PostBack postBack ) {
			if( postBack == null )
				return new Control[ 0 ];

			var table = EwfTable.Create( style: EwfTableStyle.StandardLayoutOnly );
			table.AddItem(
				new EwfTableItem(
					new ControlLine(
						new CustomButton( () => "$.modal.close()" ) { ActionControlStyle = new ButtonActionControlStyle( "Cancel" ) },
						new PostBackButton( new ButtonActionControlStyle( "Continue" ), usesSubmitBehavior: false, postBack: postBack ) ).ToCell(
							new TableCellSetup( textAlignment: TextAlignment.Right ) ) ) );
			return table.ToCollection();
		}

		WebControl EtherealControl.Control => control;

		string EtherealControl.GetJsInitStatements() {
			return open ? GetJsOpenStatement() : "";
		}

		internal string GetJsOpenStatement() {
			return "$( '#" + control.ClientID + "' ).modal( {} );";
		}
	}
}

repository: samrueby/enterprise-web-library

repo_name: samrueby/enterprise-web-library

branch_name: refs/heads/canonical


text:
include(CheckCCompilerFlag)
include(CheckIncludeFile)
include(CheckFunctionExists)
include(CheckCSourceRuns)

function(generate_config_file)
    check_function_exists("explicit_bzero" HAVE_EXPLICIT_BZERO)
    check_function_exists("explicit_memset" HAVE_EXPLICIT_MEMSET)
    check_c_source_compiles(
        "int main(void) {int a = 42; int *pnt = &a; __asm__ __volatile__ (\"\" : : \"r\"(pnt) : \"memory\");}"
        HAVE_INLINE_ASM
    )
    check_include_file("mbedtls/sha512.h" HAVE_MBEDTLS_SHA512_H)
    check_function_exists("mmap" HAVE_MMAP)
    check_function_exists("posix_memalign" HAVE_POSIX_MEMALIGN)
    check_include_file("sys/mman.h" HAVE_SYS_MMAN_H)
    if(CMAKE_CROSSCOMPILING)
        unset(HAVE_UNALIGNED_ACCESS)
    else()
        check_c_source_runs(
            "int main(void){static int a[2];return *((int*)(((char*)a)+1)) != 0;}" HAVE_UNALIGNED_ACCESS
        )
    endif()
    set(PACKAGE \"${CMAKE_PROJECT_NAME}\")
    set(PACKAGE_BUGREPORT \"\")
    set(PACKAGE_NAME \"${CMAKE_PROJECT_NAME}\")
    set(PACKAGE_STRING "\"${CMAKE_PROJECT_NAME} ${CMAKE_PROJECT_VERSION}\"")
    set(PACKAGE_TARNAME \"${CMAKE_PROJECT_NAME}\")
    set(PACKAGE_URL \"${CMAKE_PROJECT_URL}\")
    set(PACKAGE_VERSION \"${CMAKE_PROJECT_VERSION}\")
    set(VERSION \"${CMAKE_PROJECT_VERSION}\")

    configure_file(cmake/config.h.in config.h)
endfunction()

repository: ElementsProject/libwally-core

repo_name: ElementsProject/libwally-core

gha_license_id: NOASSERTION

gha_language: C

extension: cmake


text:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Timers;
using Newtonsoft.Json.Linq;
using NLog;

namespace Gerrit_Check.Model
{
    public class ReviewsModel
    {
        public ReviewsModel()
        {
            Server = string.Empty;
            Project = string.Empty;
            Username = string.Empty;
            _updateTimer = new Timer();
        }

        public delegate void UpdateEvent(UpdateStatus status);

        public event UpdateEvent OnUpdated;

        private readonly Timer _updateTimer;
        private const double UpdateTimerInterval = 300000;
        private static Logger logger = LogManager.GetCurrentClassLogger();
        private readonly Dictionary<string, int> _pendingReviewToRevisions = new Dictionary<string, int>();

        private UpdateStatus _updateStatus;

        public int SubmittableReviews { get; set; }

        public int PendingReviews { get; set; }

        public string Server { get; set; }

        public string Project { get; set; }

        public string Username { get; set; }

        public void InitModel(string server, string project, string user)
        {
            PendingReviews = 0;
            SubmittableReviews = 0;
            Server = server;
            Project = project;
            Username = user;

            _updateTimer.AutoReset = false;
            _updateTimer.Interval = UpdateTimerInterval;
            _updateTimer.Elapsed += UpdateTimerOnElapsed;

            UpdateModel();
        }

        private void UpdateTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
        {
            UpdateModel();
        }

        private void UpdateModel()
        {
            if (Server == string.Empty || Project == string.Empty || Username == string.Empty)
            {
                logger.Error("Invalid settings");
                logger.Error($"Server: {Server}");
                logger.Error($"Project: {Project}");
                logger.Error($"Username: {Username}");

                return;
            }

            if (_updateStatus?.InProgress ?? false)
            {
                logger.Trace("Cancel model update... update already in progress");
                return;
            }

            logger.Trace("Updating model...");

            var client = CreateGerritRequest();
            var pendingReviewsParameters = $"?q=status:open+project:{Project}+reviewer:{Username}&o=all_revisions";
            var submittableReviewsParameters = $"?q=status:open+project:{Project}+owner:{Username}";

            _updateStatus = new UpdateStatus {InProgress = true};

            logger.Trace($"Base address: {client.BaseAddress}");
            logger.Trace($"Pending query: {pendingReviewsParameters}");
            logger.Trace($"Submittable query: {submittableReviewsParameters}");

            client.GetAsync(pendingReviewsParameters).ContinueWith(ProcessPendingResult);
            client.GetAsync(submittableReviewsParameters).ContinueWith(ProcessSubmittableResult);
        }

        private void UpdateModelComplete()
        {
            _updateStatus.InProgress = false;
            logger.Trace("Model update complete!");
            OnUpdated?.Invoke(_updateStatus);
            logger.Trace("Notified model listeners");
            _updateTimer.Start();
        }

        private void ProcessSubmittableResult(Task<HttpResponseMessage> task)
        {
            var response = task.Result;
            if (!response.IsSuccessStatusCode)
            {
                logger.Error($"Submittable query unsuccessful: {response.ReasonPhrase}");
                return;
            }
            var responseContent = response.Content.ReadAsStringAsync();
            responseContent.ContinueWith(contentTask =>
            {
                var content = contentTask.Result;
                var submittableCount = 0;
                var oldSubmittableCount = SubmittableReviews;
                content = CleanResult(content);
                try
                {
                    var reviews = JArray.Parse(content);
                    foreach (var review in reviews)
                    {
                        if (review["submittable"].Value<bool>())
                            submittableCount++;
                    }

                    if (oldSubmittableCount == submittableCount) return;

                    _updateStatus.HasNewSubmittable = true;
                    SubmittableReviews = submittableCount;
                }
                catch (Exception e)
                {
                    logger.Error(e, "Error while parsing submittable query response");
                }
                finally
                {
                    _updateStatus.SubmittableReviewsComplete = true;
                    if (_updateStatus.UpdateComplete) UpdateModelComplete();
                }
            });
        }

        private void ProcessPendingResult(Task<HttpResponseMessage> task)
        {
            var response = task.Result;
            if (!response.IsSuccessStatusCode)
            {
                logger.Error($"Pending query unsuccessful: {response.ReasonPhrase}");
                return;
            }
            var responseContent = response.Content.ReadAsStringAsync();
            responseContent.ContinueWith(contentTask =>
            {
                var oldPendingCount = PendingReviews;
                var newPendingCount = 0;
                var content = contentTask.Result;
                content = CleanResult(content);

                try
                {
                    var reviews = JArray.Parse(content);
                    foreach (var review in reviews)
                    {
                        if (review["submittable"].Value<bool>()) continue;

                        newPendingCount++;
                        var revisions = review["revisions"] as JArray;
                        var reviewNumber = review["_number"].ToString();
                        var oldRevisionCount = _pendingReviewToRevisions.ContainsKey(reviewNumber)
                            ? _pendingReviewToRevisions[reviewNumber]
                            : 0;
                        var newRevisionCount = revisions?.Count ?? 0;

                        if (oldRevisionCount == newRevisionCount) continue;

                        _pendingReviewToRevisions[reviewNumber] = newRevisionCount;
                        _updateStatus.HasNewPending = true;
                    }
                    _updateStatus.HasNewPending |= oldPendingCount < newPendingCount;
                    PendingReviews = newPendingCount;
                }
                catch (Exception e)
                {
                    logger.Error(e, "Error while parsing pending query response");
                }
                finally
                {
                    _updateStatus.PendingReviewsComplete = true;
                    if (_updateStatus.UpdateComplete) UpdateModelComplete();
                }
            });
        }

        /// <summary>
        /// Gerrit pads the beginning of the response content
        /// for security reasons. This removes it so we can
        /// parse the rest as JSON.
        /// </summary>
        /// <param name="content">The response content</param>
        /// <returns>Cleansed content</returns>
        private static string CleanResult(string content)
        {
            var cleanResult = content.Replace(")]}'", "");
            logger.Trace($"JSON response: {cleanResult}");
            return cleanResult;
        }

        private HttpClient CreateGerritRequest()
        {
            var client = new HttpClient();
            var baseAddress = $"{Server}/changes/";
            client.BaseAddress = new Uri(baseAddress);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            return client;
        }
    }
}

repository: timtmok/gerrit-check-win

repo_name: timtmok/gerrit-check-win


text:
package sdo

import "fmt"

type SdoError struct {
	err       error
	AbortCode uint32
}

func (e *SdoError) Error() string {
	return fmt.Sprintf("%s: %#x %s", e.err, e.AbortCode, e.AbortString())
}

func (e *SdoError) AbortString() (name string) {
	name = sdoAbortCodes[e.AbortCode]
	return
}

var sdoAbortCodes = map[uint32]string{
	0x00000000: "OK",
	0x05030000: "TOGGLE_MISMATCH",
	0x05040000: "SDO_TIMEOUT",
	0x05040001: "SDO_UNKNOWN_CCS",
	0x05040002: "SDO_WRONG_BLOCKSIZE",
	0x05040003: "SDO_WRONG_SEQ_NR",
	0x05040004: "SDO_CRC_ERROR",
	0x05040005: "OUT_OF_MEMORY",
	0x06010000: "SDO_TRANSFER_NOT_SUPPORTED",
	0x06010001: "NO_READ_PERM",
	0x06010002: "NO_WRITE_PERM",
	0x06020000: "IDX_NOT_FOUND",
	0x06040041: "MAP_ERROR",
	0x06040042: "MAP_LEN_ERROR",
	0x06040043: "PARAMETER_INCOMPATIBLE",
	0x06040047: "OD_ACCESS_ERROR",
	0x06060000: "HARDWARE_ERROR",
	0x06070010: "SDO_DATA_TYPE_NOT_MATCH",
	0x06090011: "SUBIDX_NOT_FOUND",
	0x06090030: "SDO_INVALID_VALUE",
	0x08000020: "ERROR_STORE",
	0x08000022: "ERROR_PRESENT_DEVICE_STATE",
	0x08000024: "VALUE_NOT_AVAILABLE",
}

repository: ast-dd/canopen

repo_name: ast-dd/canopen


text:
package exfat

import (
	"fmt"
	"reflect"
	"testing"

	"github.com/dsoprea/go-logging"
)

func TestTree_List(t *testing.T) {
	f, er := getTestFileAndParser()

	defer f.Close()

	err := er.Parse()
	log.PanicIf(err)

	tree := NewTree(er)

	err = tree.Load()
	log.PanicIf(err)

	files, nodes, err := tree.List()
	log.PanicIf(err)

	for _, filepath := range files {
		fmt.Printf("%s\n", filepath)
		fmt.Printf("%s\n", nodes[filepath].sede.GeneralSecondaryFlags)
		fmt.Printf("\n")
	}

	// Check filenames.

	expectedFiles := []string{
		"testdirectory",
		"testdirectory\\300daec8-cec3-11e9-bfa2-0f240e41d1d8",
		"testdirectory2",
		"testdirectory2\\00c57ab0-cec3-11e9-b750-bbed8d2244c8",
		"testdirectory2\\ff7b94be-cec2-11e9-b7b1-6b2e61bd775c",
		"testdirectory2\\file1",
		"testdirectory2\\file2",
		"testdirectory3",
		"testdirectory3\\10422c86-cec3-11e9-953f-4f501efd2640",
		"064cbfd4-cec3-11e9-926d-c362c80fab7b",
		"2-delahaye-type-165-cabriolet-dsc_8025.jpg",
		"79c6d31a-cca1-11e9-8325-9746d045e868",
		"8fd71ab132c59bf33cd7890c0acebf12.jpg",
	}

	if reflect.DeepEqual(files, expectedFiles) != true {
		for i, filepath := range files {
			fmt.Printf("ACTUAL: (%d) [%s]\n", i, filepath)
		}

		for i, filepath := range expectedFiles {
			fmt.Printf("EXPECTED: (%d) [%s]\n", i, filepath)
		}

		t.Fatalf("Files not correct.")
	}

	// Check nodes.

	actualTypes := make(map[string]bool)

	for path, node := range nodes {
		actualTypes[path] = node.IsDirectory()
	}

	expectedTypes := map[string]bool{
		"testdirectory": true,
		"testdirectory\\300daec8-cec3-11e9-bfa2-0f240e41d1d8": false,
		"testdirectory2":        true,
		"testdirectory2\\file1": false,
		"testdirectory2\\file2": false,
		"testdirectory2\\ff7b94be-cec2-11e9-b7b1-6b2e61bd775c": false,
		"testdirectory2\\00c57ab0-cec3-11e9-b750-bbed8d2244c8": false,
		"testdirectory3": true,
		"testdirectory3\\10422c86-cec3-11e9-953f-4f501efd2640": false,
		"8fd71ab132c59bf33cd7890c0acebf12.jpg":                 false,
		"064cbfd4-cec3-11e9-926d-c362c80fab7b":                 false,
		"79c6d31a-cca1-11e9-8325-9746d045e868":                 false,
		"2-delahaye-type-165-cabriolet-dsc_8025.jpg":           false,
	}

	if reflect.DeepEqual(actualTypes, expectedTypes) != true {
		t.Fatalf("File-entry types not correct.")
	}
}

func TestTree_Lookup__File__Hit(t *testing.T) {
	f, er := getTestFileAndParser()

	defer f.Close()

	err := er.Parse()
	log.PanicIf(err)

	tree := NewTree(er)

	err = tree.Load()
	log.PanicIf(err)

	node, err := tree.Lookup([]string{"testdirectory2", "ff7b94be-cec2-11e9-b7b1-6b2e61bd775c"})
	log.PanicIf(err)

	if node == nil {
		t.Fatalf("Did not find the node.")
	}

	if node.Name() != "ff7b94be-cec2-11e9-b7b1-6b2e61bd775c" {
		t.Fatalf("Found node not correct (hit).")
	}
}

func TestTree_Lookup__File__Miss(t *testing.T) {
	f, er := getTestFileAndParser()

	defer f.Close()

	err := er.Parse()
	log.PanicIf(err)

	tree := NewTree(er)

	err = tree.Load()
	log.PanicIf(err)

	node, err := tree.Lookup([]string{"testdirectory2", "invalid_file"})
	log.PanicIf(err)

	if node != nil {
		t.Fatalf("Found node not correct (miss).")
	}
}

func TestTree_Lookup__Folder__Hit(t *testing.T) {
	f, er := getTestFileAndParser()

	defer f.Close()

	err := er.Parse()
	log.PanicIf(err)

	tree := NewTree(er)

	err = tree.Load()
	log.PanicIf(err)

	node, err := tree.Lookup([]string{"testdirectory2"})
	log.PanicIf(err)

	if node == nil {
		t.Fatalf("Did not find the node.")
	}

	if node.Name() != "testdirectory2" {
		t.Fatalf("Found node not correct (hit).")
	}
}

func TestTree_Lookup__Folder__Miss(t *testing.T) {
	f, er := getTestFileAndParser()

	defer f.Close()

	err := er.Parse()
	log.PanicIf(err)

	tree := NewTree(er)

	err = tree.Load()
	log.PanicIf(err)

	node, err := tree.Lookup([]string{"testdirectory2", "invalid_path", "invalid_file"})
	log.PanicIf(err)

	if node != nil {
		t.Fatalf("Expected to not find any nodes.")
	}
}

func TestTree_Lookup__Root__Hit(t *testing.T) {
	f, er := getTestFileAndParser()

	defer f.Close()

	err := er.Parse()
	log.PanicIf(err)

	tree := NewTree(er)

	err = tree.Load()
	log.PanicIf(err)

	node, err := tree.Lookup([]string{})
	log.PanicIf(err)

	if node != tree.rootNode {
		t.Fatalf("Expected root node to be returned.")
	}
}

func TestTree_Lookup__Root__EntryMiss(t *testing.T) {
	f, er := getTestFileAndParser()

	defer f.Close()

	err := er.Parse()
	log.PanicIf(err)

	tree := NewTree(er)

	err = tree.Load()
	log.PanicIf(err)

	node, err := tree.Lookup([]string{"invalid_file"})
	log.PanicIf(err)

	if node != nil {
		t.Fatalf("Expected no node to be found.")
	}
}

func TestTree_IndexedDirectoryEntry(t *testing.T) {
	f, er := getTestFileAndParser()

	defer f.Close()

	err := er.Parse()
	log.PanicIf(err)

	tree := NewTree(er)

	err = tree.Load()
	log.PanicIf(err)

	node, err := tree.Lookup([]string{"2-delahaye-type-165-cabriolet-dsc_8025.jpg"})
	log.PanicIf(err)

	ide := node.IndexedDirectoryEntry()
	if reflect.DeepEqual(ide, node.ide) != true {
		t.Fatalf("IndexedDirectoryEntry did not return IDE.")
	}
}

func TestTree_loadDirectory(t *testing.T) {
	f, er := getTestFileAndParser()

	defer f.Close()

	err := er.Parse()
	log.PanicIf(err)

	tree := NewTree(er)

	err = tree.Load()
	log.PanicIf(err)

	// Load our directory.

	node, err := tree.Lookup([]string{"testdirectory"})
	log.PanicIf(err)

	err = tree.loadDirectory(node.sede.FirstCluster, node)
	log.PanicIf(err)

	// Do the test.

	rootNode, err := tree.Lookup([]string{})
	log.PanicIf(err)

	_, _, foundNode := rootNode.Lookup([]string{"testdirectory", "300daec8-cec3-11e9-bfa2-0f240e41d1d8"})
	log.PanicIf(err)

	if foundNode.Name() != "300daec8-cec3-11e9-bfa2-0f240e41d1d8" {
		t.Fatalf("Found node not correct.")
	}
}

func TestNewTreeNode(t *testing.T) {
	fde := new(ExfatFileDirectoryEntry)
	sede := new(ExfatStreamExtensionDirectoryEntry)

	tn := NewTreeNode("some name", true, IndexedDirectoryEntry{}, fde, sede)

	if tn.name != "some name" {
		t.Fatalf("name not set correctly.")
	} else if tn.IsDirectory() != true {
		t.Fatalf("IsDirectory not set correctly.")
	}

	if tn.fde != fde {
		t.Fatalf("ExfatFileDirectoryEntry not set correctly.")
	} else if tn.sede != sede {
		t.Fatalf("ExfatStreamExtensionDirectoryEntry not set correctly.")
	}
}

func TestTreeNode_AddChild(t *testing.T) {
	rootNode := NewTreeNode("root", true, IndexedDirectoryEntry{}, nil, nil)
	childNode := rootNode.AddChild("child name", false, nil, nil, IndexedDirectoryEntry{})

	if reflect.DeepEqual(rootNode.ChildFiles(), []string{"child name"}) != true {
		t.Fatalf("New child not registered in parent.")
	}

	recoveredChild := rootNode.GetChild("child name")
	if recoveredChild != childNode {
		t.Fatalf("Recovered child node not correct.")
	}

	if childNode.Name() != "child name" {
		t.Fatalf("New child does not have the right name.")
	}
}

func TestTreeNode_Name(t *testing.T) {
	tn := NewTreeNode("some name", true, IndexedDirectoryEntry{}, nil, nil)

	if tn.Name() != "some name" {
		t.Fatalf("Name not correct.")
	}
}

func TestTreeNode_FileDirectoryEntry(t *testing.T) {
	fde := new(ExfatFileDirectoryEntry)

	tn := NewTreeNode("some name", true, IndexedDirectoryEntry{}, fde, nil)

	if tn.FileDirectoryEntry() != fde {
		t.Fatalf("FileDirectoryEntry not correct.")
	}
}

func TestTreeNode_StreamDirectoryEntry(t *testing.T) {
	sede := new(ExfatStreamExtensionDirectoryEntry)

	tn := NewTreeNode("some name", true, IndexedDirectoryEntry{}, nil, sede)

	if tn.StreamDirectoryEntry() != sede {
		t.Fatalf("StreamDirectoryEntry not correct.")
	}
}

func TestTreeNode_IsDirectory__true(t *testing.T) {
	tn := NewTreeNode("some name", true, IndexedDirectoryEntry{}, nil, nil)

	if tn.IsDirectory() != true {
		t.Fatalf("IsDirectory not correct.")
	}
}

func TestTreeNode_IsDirectory__false(t *testing.T) {
	tn := NewTreeNode("some name", false, IndexedDirectoryEntry{}, nil, nil)

	if tn.IsDirectory() != false {
		t.Fatalf("IsDirectory not correct.")
	}
}

func TestTreeNode_ChildFolders__Root(t *testing.T) {
	f, er := getTestFileAndParser()

	defer f.Close()

	err := er.Parse()
	log.PanicIf(err)

	tree := NewTree(er)

	err = tree.Load()
	log.PanicIf(err)

	rootNode, err := tree.Lookup([]string{})
	log.PanicIf(err)

	expectedFolders := []string{
		"testdirectory",
		"testdirectory2",
		"testdirectory3",
	}

	if reflect.DeepEqual(rootNode.ChildFolders(), expectedFolders) != true {
		t.Fatalf("Child folders not correct: %v", rootNode.ChildFolders())
	}
}

func TestTreeNode_ChildFolders__Subfolder(t *testing.T) {
	f, er := getTestFileAndParser()

	defer f.Close()

	err := er.Parse()
	log.PanicIf(err)

	tree := NewTree(er)

	err = tree.Load()
	log.PanicIf(err)

	node, err := tree.Lookup([]string{"testdirectory"})
	log.PanicIf(err)

	expectedFolders := []string{}

	if reflect.DeepEqual(node.ChildFolders(), expectedFolders) != true {
		t.Fatalf("Child folders not correct: %v", node.ChildFolders())
	}
}

func TestTreeNode_ChildFiles__Root(t *testing.T) {
	f, er := getTestFileAndParser()

	defer f.Close()

	err := er.Parse()
	log.PanicIf(err)

	tree := NewTree(er)

	err = tree.Load()
	log.PanicIf(err)

	rootNode, err := tree.Lookup([]string{})
	log.PanicIf(err)

	expectedFiles := []string{
		"064cbfd4-cec3-11e9-926d-c362c80fab7b",
		"2-delahaye-type-165-cabriolet-dsc_8025.jpg",
		"79c6d31a-cca1-11e9-8325-9746d045e868",
		"8fd71ab132c59bf33cd7890c0acebf12.jpg",
	}

	if reflect.DeepEqual(rootNode.ChildFiles(), expectedFiles) != true {
		t.Fatalf("Child files not correct: %v", rootNode.ChildFiles())
	}
}

func TestTreeNode_ChildFiles__Subfolder(t *testing.T) {
	f, er := getTestFileAndParser()

	defer f.Close()

	err := er.Parse()
	log.PanicIf(err)

	tree := NewTree(er)

	err = tree.Load()
	log.PanicIf(err)

	node, err := tree.Lookup([]string{"testdirectory"})
	log.PanicIf(err)

	expectedFiles := []string{
		"300daec8-cec3-11e9-bfa2-0f240e41d1d8",
	}

	if reflect.DeepEqual(node.ChildFiles(), expectedFiles) != true {
		t.Fatalf("Child files not correct: %v", node.ChildFiles())
	}
}

func TestTreeNode_GetChild(t *testing.T) {
	f, er := getTestFileAndParser()

	defer f.Close()

	err := er.Parse()
	log.PanicIf(err)

	tree := NewTree(er)

	err = tree.Load()
	log.PanicIf(err)

	node, err := tree.Lookup([]string{"testdirectory"})
	log.PanicIf(err)

	childNode := node.GetChild("300daec8-cec3-11e9-bfa2-0f240e41d1d8")

	if childNode != node.childrenMap["300daec8-cec3-11e9-bfa2-0f240e41d1d8"] {
		t.Fatalf("Child not correct.")
	}
}

func TestTreeNode_Lookup__Folder__Hit(t *testing.T) {
	f, er := getTestFileAndParser()

	defer f.Close()

	err := er.Parse()
	log.PanicIf(err)

	tree := NewTree(er)

	err = tree.Load()
	log.PanicIf(err)

	node, err := tree.Lookup([]string{"testdirectory"})
	log.PanicIf(err)

	_, _, foundNode := node.Lookup([]string{"300daec8-cec3-11e9-bfa2-0f240e41d1d8"})
	log.PanicIf(err)

	if foundNode.Name() != "300daec8-cec3-11e9-bfa2-0f240e41d1d8" {
		t.Fatalf("Found node not correct.")
	}
}

func TestTreeNode_Lookup__Folder__Miss(t *testing.T) {
	f, er := getTestFileAndParser()

	defer f.Close()

	err := er.Parse()
	log.PanicIf(err)

	tree := NewTree(er)

	err = tree.Load()
	log.PanicIf(err)

	node, err := tree.Lookup([]string{"testdirectory"})
	log.PanicIf(err)

	lastPathParts, lastNode, foundNode := node.Lookup([]string{"invalid_path", "invalid_file"})
	log.PanicIf(err)

	if foundNode != nil {
		t.Fatalf("Expected no node to be returned for miss.")
	} else if reflect.DeepEqual(lastPathParts, []string{"invalid_path", "invalid_file"}) != true {
		t.Fatalf("Expected missing file to still be in the path-parts.")
	} else if lastNode != node {
		t.Fatalf("Last-node not correct.")
	}
}

func TestTreeNode_Lookup__File__Hit(t *testing.T) {
	f, er := getTestFileAndParser()

	defer f.Close()

	err := er.Parse()
	log.PanicIf(err)

	tree := NewTree(er)

	err = tree.Load()
	log.PanicIf(err)

	// Load our directory.

	node, err := tree.Lookup([]string{"testdirectory"})
	log.PanicIf(err)

	err = tree.loadDirectory(node.sede.FirstCluster, node)
	log.PanicIf(err)

	// Do the test.

	rootNode, err := tree.Lookup([]string{})
	log.PanicIf(err)

	_, _, foundNode := rootNode.Lookup([]string{"testdirectory", "300daec8-cec3-11e9-bfa2-0f240e41d1d8"})
	log.PanicIf(err)

	if foundNode.Name() != "300daec8-cec3-11e9-bfa2-0f240e41d1d8" {
		t.Fatalf("Found node not correct.")
	}
}

func TestTreeNode_Lookup__File__Miss(t *testing.T) {
	f, er := getTestFileAndParser()

	defer f.Close()

	err := er.Parse()
	log.PanicIf(err)

	tree := NewTree(er)

	err = tree.Load()
	log.PanicIf(err)

	node, err := tree.Lookup([]string{"testdirectory"})
	log.PanicIf(err)

	lastPathParts, lastNode, foundNode := node.Lookup([]string{"invalid_file"})
	log.PanicIf(err)

	if foundNode != nil {
		t.Fatalf("Expected no node to be returned for miss.")
	} else if reflect.DeepEqual(lastPathParts, []string{"invalid_file"}) != true {
		t.Fatalf("Expected missing file to still be in the path-parts.")
	} else if lastNode != node {
		t.Fatalf("Last-node not correct.")
	}
}

func TestTree_Load(t *testing.T) {
	f, er := getTestFileAndParser()

	defer f.Close()

	err := er.Parse()
	log.PanicIf(err)

	tree := NewTree(er)

	err = tree.Load()
	log.PanicIf(err)

	rootNode, err := tree.Lookup([]string{})
	log.PanicIf(err)

	expectedFolders := []string{
		"testdirectory",
		"testdirectory2",
		"testdirectory3",
	}

	if reflect.DeepEqual(rootNode.ChildFolders(), expectedFolders) != true {
		t.Fatalf("Child folders not correct: %v", rootNode.ChildFolders())
	}

	expectedFiles := []string{
		"064cbfd4-cec3-11e9-926d-c362c80fab7b",
		"2-delahaye-type-165-cabriolet-dsc_8025.jpg",
		"79c6d31a-cca1-11e9-8325-9746d045e868",
		"8fd71ab132c59bf33cd7890c0acebf12.jpg",
	}

	if reflect.DeepEqual(rootNode.ChildFiles(), expectedFiles) != true {
		t.Fatalf("Child files not correct: %v", rootNode.ChildFiles())
	}
}

func TestTree_Visit(t *testing.T) {
	f, er := getTestFileAndParser()

	defer f.Close()

	err := er.Parse()
	log.PanicIf(err)

	tree := NewTree(er)

	err = tree.Load()
	log.PanicIf(err)

	collected := make([][]string, 0)

	cb := func(pathParts []string, node *TreeNode) (err error) {
		collected = append(collected, pathParts)
		return nil
	}

	err = tree.Visit(cb)
	log.PanicIf(err)

	expectedCollected := [][]string{
		[]string{},
		[]string{"testdirectory"},
		[]string{"testdirectory", "300daec8-cec3-11e9-bfa2-0f240e41d1d8"},
		[]string{"testdirectory2"},
		[]string{"testdirectory2", "00c57ab0-cec3-11e9-b750-bbed8d2244c8"},
		[]string{"testdirectory2", "ff7b94be-cec2-11e9-b7b1-6b2e61bd775c"},
		[]string{"testdirectory2", "file1"},
		[]string{"testdirectory2", "file2"},
		[]string{"testdirectory3"},
		[]string{"testdirectory3", "10422c86-cec3-11e9-953f-4f501efd2640"},
		[]string{"064cbfd4-cec3-11e9-926d-c362c80fab7b"},
		[]string{"2-delahaye-type-165-cabriolet-dsc_8025.jpg"},
		[]string{"79c6d31a-cca1-11e9-8325-9746d045e868"},
		[]string{"8fd71ab132c59bf33cd7890c0acebf12.jpg"},
	}

	if reflect.DeepEqual(collected, expectedCollected) != true {
		for i, pathParts := range collected {
			fmt.Printf("ACTUAL (%d): %v\n", i, pathParts)
		}

		for i, pathParts := range expectedCollected {
			fmt.Printf("EXPECTED (%d): %v\n", i, pathParts)
		}

		t.Fatalf("Collected paths not correct.")
	}
}

func TestTree_visit(t *testing.T) {
	f, er := getTestFileAndParser()

	defer f.Close()

	err := er.Parse()
	log.PanicIf(err)

	tree := NewTree(er)

	err = tree.Load()
	log.PanicIf(err)

	collected := make([][]string, 0)

	cb := func(pathParts []string, node *TreeNode) (err error) {
		collected = append(collected, pathParts)
		return nil
	}

	pathParts := make([]string, 0)

	err = tree.visit(pathParts, tree.rootNode, cb)
	log.PanicIf(err)

	expectedCollected := [][]string{
		[]string{},
		[]string{"testdirectory"},
		[]string{"testdirectory", "300daec8-cec3-11e9-bfa2-0f240e41d1d8"},
		[]string{"testdirectory2"},
		[]string{"testdirectory2", "00c57ab0-cec3-11e9-b750-bbed8d2244c8"},
		[]string{"testdirectory2", "ff7b94be-cec2-11e9-b7b1-6b2e61bd775c"},
		[]string{"testdirectory2", "file1"},
		[]string{"testdirectory2", "file2"},
		[]string{"testdirectory3"},
		[]string{"testdirectory3", "10422c86-cec3-11e9-953f-4f501efd2640"},
		[]string{"064cbfd4-cec3-11e9-926d-c362c80fab7b"},
		[]string{"2-delahaye-type-165-cabriolet-dsc_8025.jpg"},
		[]string{"79c6d31a-cca1-11e9-8325-9746d045e868"},
		[]string{"8fd71ab132c59bf33cd7890c0acebf12.jpg"},
	}

	if reflect.DeepEqual(collected, expectedCollected) != true {
		for i, pathParts := range collected {
			fmt.Printf("ACTUAL (%d): %v\n", i, pathParts)
		}

		for i, pathParts := range expectedCollected {
			fmt.Printf("EXPECTED (%d): %v\n", i, pathParts)
		}

		t.Fatalf("Collected paths not correct.")
	}
}

repository: backwardn/go-exfat

repo_name: backwardn/go-exfat


text:
@article{AmiorHalket13,
 abstract = {Are households more likely to be homeowners when “housing risk” is higher? We show that home‐ownership rates and loan‐to‐value (LTV) ratios at the city level are strongly negatively correlated with local house price volatility. However, causal inference is confounded by house price levels, which are systematically correlated with housing risk in an intuitive way: in cities where the land value is larger relative to the local cost of structures, house prices are higher and more volatile. We disentangle the contributions of high price levels from high volatilities by building a life‐cycle model of home‐ownership choices. We find that higher price levels can explain most of the lower home‐ownership. Higher risk in the model leads to slightly lower home‐ownership and LTV ratios in high land value cities. The relationship between LTV and risk is corroborated by LTV's negative correlation with price volatility in the data and highlights the importance of including other means of incomplete insurance in models of home‐ownership.},
 author = {Michael Amior and Jonathan Halket},
 doi = {10.3982/qe346},
 journal = {Quantitative Economics},
 month = {NOV},
 number = {3},
 pages = {631--674},
 publisher = {The Econometric Society},
 title = {Do Households Use Homeownership To Insure Themselves? Evidence Across U.S. Cities},
 url = {https://onlinelibrary.wiley.com/doi/10.3982/QE346},
 volume = {5},
 year = {2014}
}

repository: jrhalket/Website-academic

repo_name: jrhalket/Website-academic


text:
package main

import (
	"github.com/micro/go-micro/v2"
	"github.com/micro/go-micro/v2/registry"
	"github.com/micro/go-micro/v2/registry/etcd"

	_ "gomicro_note/p28/appInit"
	"gomicro_note/p28/controllers"
	"gomicro_note/p28/models"
)

func main() {
	etcdReg := etcd.NewRegistry(
		registry.Addrs("127.0.0.1:2379"),
	)

	app := micro.NewService(
		micro.Name("api.hzde.com.user"),
		micro.Address(":8000"),
		micro.Registry(etcdReg),
	)

	models.RegisterUserServiceHandler(app.Server(), new(controllers.UserService))
	app.Init()

	app.Run()
}