"use strict";

var tz = require("../../").tz;

var tempLinks = {},
	tempZones = {},
	tempNames = {};

function moveProperties (a, b) {
	var key;
	for (key in a) {
		if (a.hasOwnProperty(key)) {
			b[key] = a[key];
			delete a[key];
		}
	}

}

exports.link = {
	setUp : function (done) {
		moveProperties(tz._links, tempLinks);
		moveProperties(tz._zones, tempZones);
		moveProperties(tz._names, tempNames);
		done();
	},

	tearDown : function (done) {
		moveProperties(tz._links, {});
		moveProperties(tz._zones, {});
		moveProperties(tz._names, {});
		moveProperties(tempLinks, tz._links);
		moveProperties(tempZones, tz._zones);
		moveProperties(tempNames, tz._names);
		done();
	},

	linking : function (test) {
		test.ok(!tz.zone('Zone1'),  "Zones should have been reset.");
		test.ok(!tz.zone('Alias1'), "Links should have been reset.");
		test.ok(!tz.zone('Alias2'), "Links should have been reset.");
		test.ok(!tz.zone('Alias3'), "Links should have been reset.");
		test.ok(!tz._zones.zone1,   "Zones should have been reset.");
		test.ok(!tz._links.alias1,  "Links should have been reset.");
		test.ok(!tz._links.alias2,  "Links should have been reset.");
		test.ok(!tz._links.alias3,  "Links should have been reset.");

		tz.add("Zone1|ASDF|0|0|0");

		tz.link("Alias1|Zone1");
		tz.link(["Alias2|Zone1", "Alias3|Zone1"]);

		test.ok(tz.zone('Zone1'),  "Should be able to add a zone.");
		test.ok(tz.zone('Alias1'), "Should be able to add an alias with 'Alias|Zone' format.");
		test.ok(tz.zone('Alias2'), "Should be able to add an alias with ['Alias|Zone'] format.");
		test.ok(tz.zone('Alias3'), "Should be able to add an alias with ['Alias|Zone'] format");

		test.equal(tz.zone('Zone1').name,  'Zone1', "Should get the right zone.");
		test.equal(tz.zone('Alias1').name, 'Alias1', "Should get the right zone from an alias.");
		test.equal(tz.zone('Alias2').name, 'Alias2', "Should get the right zone from an alias.");
		test.equal(tz.zone('Alias3').name, 'Alias3', "Should get the right zone from an alias.");

		test.done();
	},

	reversed : function (test) {
		test.ok(!tz.zone('Zone1'),  "Zones should have been reset.");
		test.ok(!tz.zone('Alias1'), "Links should have been reset.");
		test.ok(!tz.zone('Alias2'), "Links should have been reset.");
		test.ok(!tz.zone('Alias3'), "Links should have been reset.");
		test.ok(!tz._zones.zone1,   "Zones should have been reset.");
		test.ok(!tz._links.alias1,  "Links should have been reset.");
		test.ok(!tz._links.alias2,  "Links should have been reset.");
		test.ok(!tz._links.alias3,  "Links should have been reset.");

		tz.add("Zone1|ASDF|0|0|0");

		tz.link("Zone1|Alias1");
		tz.link(["Zone1|Alias2", "Zone1|Alias3"]);

		test.ok(tz.zone('Zone1'),  "Should be able to add a zone.");
		test.ok(tz.zone('Alias1'), "Should be able to add an alias with 'Zone|Alias' format.");
		test.ok(tz.zone('Alias2'), "Should be able to add an alias with ['Zone|Alias'] format.");
		test.ok(tz.zone('Alias3'), "Should be able to add an alias with ['Zone|Alias'] format");

		test.equal(tz.zone('Zone1').name,  'Zone1', "Should get the right zone.");
		test.equal(tz.zone('Alias1').name, 'Alias1', "Should get the right zone from an alias.");
		test.equal(tz.zone('Alias2').name, 'Alias2', "Should get the right zone from an alias.");
		test.equal(tz.zone('Alias3').name, 'Alias3', "Should get the right zone from an alias.");

		test.done();
	},

	outOfOrder : function (test) {
		test.ok(!tz.zone('Zone1'),  "Zones should have been reset.");
		test.ok(!tz.zone('Alias1'), "Links should have been reset.");
		test.ok(!tz.zone('Alias2'), "Links should have been reset.");
		test.ok(!tz.zone('Alias3'), "Links should have been reset.");

		tz.link("Alias1|Zone1");
		tz.add("Zone1|ASDF|0|0|0");

		test.ok(tz.zone('Zone1'),  "Should be able to add a zone.");
		test.ok(tz.zone('Alias1'), "Should be able to add an alias before adding the zone.");

		test.equal(tz.zone('Zone1').name,  'Zone1', "Should get the right zone.");
		test.equal(tz.zone('Alias1').name, 'Alias1', "Should get the right zone from an alias.");

		tz.link("Alias2|Zone2");
		test.ok(!tz.zone('Alias2'), "Aliases without zones should be null.");

		test.done();
	},

	namesOfAliases : function (test) {
		test.ok(!tz.zone('Zone1'),  "Zones should have been reset.");
		test.ok(!tz.zone('Alias1'), "Links should have been reset.");
		test.ok(!tz.zone('Alias2'), "Links should have been reset.");
		test.ok(!tz.zone('Alias3'), "Links should have been reset.");

		tz.link("Alias1|Zone1");
		tz.add("Zone1|ASDF|0|0|0");
		test.deepEqual(tz.names(), ["Alias1", "Zone1"], "Should be able to get the names of aliased zones.");

		tz.link("Alias2|Zone1");
		test.deepEqual(tz.names(), ["Alias1", "Alias2", "Zone1"], "Should be able to get the names of aliased zones.");

		tz.link("Alias3|Zone2");
		test.deepEqual(tz.names(), ["Alias1", "Alias2", "Zone1"], "Should be able to get the names of aliased zones.");

		tz.link("Alias3|Zone1");
		test.deepEqual(tz.names(), ["Alias1", "Alias2", "Alias3", "Zone1"], "Should be able to get the names of aliased zones.");

		test.done();
	},

	zoneAndAliasNotLoaded : function (test) {
		test.ok(!tz.zone('Zone1'),  "Zones should have been reset.");
		test.ok(!tz.zone('Alias1'), "Links should have been reset.");

		tz.link("Alias1|Zone1");

		test.ok(!tz.zone('Zone1'),  "Zone should not exist if it wasn't loaded.");
		test.ok(!tz.zone('Alias1'), "Link should not exist if its zone wasn't loaded.");

		test.done();
	}
};

{'repo_name': 'moment/moment-timezone', 'stars': '3474', 'repo_language': 'JavaScript', 'file_name': '2016f.json', 'mime_type': 'text/plain', 'hash': 2566312663676899641, 'source_dataset': 'data'}


// +build !ignore_autogenerated

/*
Copyright 2018 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// This file was autogenerated by defaulter-gen. Do not edit it manually!

package v1beta1

import (
	runtime "k8s.io/apimachinery/pkg/runtime"
)

// RegisterDefaults adds defaulters functions to the given scheme.
// Public to allow building arbitrary schemes.
// All generated defaulters are covering - they call all nested defaulters.
func RegisterDefaults(scheme *runtime.Scheme) error {
	scheme.AddTypeDefaultingFunc(&CustomResourceDefinition{}, func(obj interface{}) { SetObjectDefaults_CustomResourceDefinition(obj.(*CustomResourceDefinition)) })
	scheme.AddTypeDefaultingFunc(&CustomResourceDefinitionList{}, func(obj interface{}) {
		SetObjectDefaults_CustomResourceDefinitionList(obj.(*CustomResourceDefinitionList))
	})
	return nil
}

func SetObjectDefaults_CustomResourceDefinition(in *CustomResourceDefinition) {
	SetDefaults_CustomResourceDefinition(in)
	SetDefaults_CustomResourceDefinitionSpec(&in.Spec)
}

func SetObjectDefaults_CustomResourceDefinitionList(in *CustomResourceDefinitionList) {
	for i := range in.Items {
		a := &in.Items[i]
		SetObjectDefaults_CustomResourceDefinition(a)
	}
}

{'repo_name': 'sapcc/kubernetes-operators', 'stars': '116', 'repo_language': 'Go', 'file_name': 'main.go', 'mime_type': 'text/x-c', 'hash': -201713162064900236, 'source_dataset': 'data'}


// @flow

import prometheus from 'prom-client';

import type Router from 'koa-router';
import type Route from '.';

export function metrics(router: Router): Route {
  return router.get('metrics', '/metrics', ctx => {
    ctx.body = prometheus.register.getMetricsAsJSON();
  });
}

{'repo_name': 'zalando-incubator/tessellate', 'stars': '136', 'repo_language': 'JavaScript', 'file_name': 'after_success.sh', 'mime_type': 'text/x-shellscript', 'hash': 2847294926595918277, 'source_dataset': 'data'}


#!/usr/bin/env bash
#
# Licensed under the terms of the GNU GPL License version 2 or later.
#
# Author: Peter Tyser <ptyser@xes-inc.com>
#
# U-Boot firmware supports the booting of images in the Flattened Image
# Tree (FIT) format.  The FIT format uses a device tree structure to
# describe a kernel image, device tree blob, ramdisk, etc.  This script
# creates an Image Tree Source (.its file) which can be passed to the
# 'mkimage' utility to generate an Image Tree Blob (.itb file).  The .itb
# file can then be booted by U-Boot (or other bootloaders which support
# FIT images).  See doc/uImage.FIT/howto.txt in U-Boot source code for
# additional information on FIT images.
#

usage() {
	echo "Usage: $(basename $0) -A arch -C comp -a addr -e entry" \
		"-v version -k kernel [-D name -d dtb] -o its_file"
	echo -e "\t-A ==> set architecture to 'arch'"
	echo -e "\t-C ==> set compression type 'comp'"
	echo -e "\t-c ==> set config name 'config'"
	echo -e "\t-a ==> set load address to 'addr' (hex)"
	echo -e "\t-e ==> set entry point to 'entry' (hex)"
	echo -e "\t-v ==> set kernel version to 'version'"
	echo -e "\t-k ==> include kernel image 'kernel'"
	echo -e "\t-D ==> human friendly Device Tree Blob 'name'"
	echo -e "\t-d ==> include Device Tree Blob 'dtb'"
	echo -e "\t-o ==> create output file 'its_file'"
	exit 1
}

while getopts ":A:a:c:C:D:d:e:k:o:v:" OPTION
do
	case $OPTION in
		A ) ARCH=$OPTARG;;
		a ) LOAD_ADDR=$OPTARG;;
		c ) CONFIG=$OPTARG;;
		C ) COMPRESS=$OPTARG;;
		D ) DEVICE=$OPTARG;;
		d ) DTB=$OPTARG;;
		e ) ENTRY_ADDR=$OPTARG;;
		k ) KERNEL=$OPTARG;;
		o ) OUTPUT=$OPTARG;;
		v ) VERSION=$OPTARG;;
		* ) echo "Invalid option passed to '$0' (options:$@)"
		usage;;
	esac
done

# Make sure user entered all required parameters
if [ -z "${ARCH}" ] || [ -z "${COMPRESS}" ] || [ -z "${LOAD_ADDR}" ] || \
	[ -z "${ENTRY_ADDR}" ] || [ -z "${VERSION}" ] || [ -z "${KERNEL}" ] || \
	[ -z "${OUTPUT}" ] || [ -z "${CONFIG}" ]; then
	usage
fi

ARCH_UPPER=$(echo $ARCH | tr '[:lower:]' '[:upper:]')

# Conditionally create fdt information
if [ -n "${DTB}" ]; then
	FDT_NODE="
		fdt@1 {
			description = \"${ARCH_UPPER} OpenWrt ${DEVICE} device tree blob\";
			data = /incbin/(\"${DTB}\");
			type = \"flat_dt\";
			arch = \"${ARCH}\";
			compression = \"none\";
			hash@1 {
				algo = \"crc32\";
			};
			hash@2 {
				algo = \"sha1\";
			};
		};
"
	FDT_PROP="fdt = \"fdt@1\";"
fi

# Create a default, fully populated DTS file
DATA="/dts-v1/;

/ {
	description = \"${ARCH_UPPER} OpenWrt FIT (Flattened Image Tree)\";
	#address-cells = <1>;

	images {
		kernel@1 {
			description = \"${ARCH_UPPER} OpenWrt Linux-${VERSION}\";
			data = /incbin/(\"${KERNEL}\");
			type = \"kernel\";
			arch = \"${ARCH}\";
			os = \"linux\";
			compression = \"${COMPRESS}\";
			load = <${LOAD_ADDR}>;
			entry = <${ENTRY_ADDR}>;
			hash@1 {
				algo = \"crc32\";
			};
			hash@2 {
				algo = \"sha1\";
			};
		};
${FDT_NODE}
	};

	configurations {
		default = \"${CONFIG}\";
		${CONFIG} {
			description = \"OpenWrt\";
			kernel = \"kernel@1\";
			${FDT_PROP}
		};
	};
};"

# Write .its file to disk
echo "$DATA" > ${OUTPUT}

{'repo_name': 'coolsnowwolf/lede', 'stars': '11432', 'repo_language': 'C', 'file_name': 'traverse-ls1043s.dts', 'mime_type': 'text/x-c', 'hash': 2937382318271620079, 'source_dataset': 'data'}


#!/bin/bash
# check : shorthand for make and ctest -R

if [[ $# != 1 || $1 == *help ]]
then
  echo "usage: $0 regexp"
  echo "  Builds and runs tests matching the regexp."
  echo "  The EIGEN_MAKE_ARGS environment variable allows to pass args to 'make'."
  echo "    For example, to launch 5 concurrent builds, use EIGEN_MAKE_ARGS='-j5'"
  echo "  The EIGEN_CTEST_ARGS environment variable allows to pass args to 'ctest'."
  echo "    For example, with CTest 2.8, you can use EIGEN_CTEST_ARGS='-j5'."
  exit 0
fi

if [ -n "${EIGEN_CTEST_ARGS:+x}" ]
then
  ./buildtests.sh "$1" && ctest -R "$1" ${EIGEN_CTEST_ARGS}
else
  ./buildtests.sh "$1" && ctest -R "$1"
fi
exit $?

{'repo_name': 'miyosuda/TensorFlowAndroidMNIST', 'stars': '264', 'repo_language': 'C++', 'file_name': 'beginner.py', 'mime_type': 'text/x-python', 'hash': -3683299550862796316, 'source_dataset': 'data'}


import cProfile
import os
from colorsys import hsv_to_rgb
from pstats import Stats

from django.utils.html import format_html
from django.utils.translation import gettext_lazy as _

from debug_toolbar import settings as dt_settings
from debug_toolbar.panels import Panel

# Occasionally the disable method on the profiler is listed before
# the actual view functions. This function call should be ignored as
# it leads to an error within the tests.
INVALID_PROFILER_FUNC = "_lsprof.Profiler"

def contains_profiler(func_tuple):
    """Helper function that checks to see if the tuple contains
    the INVALID_PROFILE_FUNC in any string value of the tuple."""
    has_profiler = False
    for value in func_tuple:
        if isinstance(value, str):
            has_profiler |= INVALID_PROFILER_FUNC in value
    return has_profiler

class DjangoDebugToolbarStats(Stats):
    __root = None

    def get_root_func(self):
        if self.__root is None:
            for func, (cc, nc, tt, ct, callers) in self.stats.items():
                if len(callers) == 0 and not contains_profiler(func):
                    self.__root = func
                    break
        return self.__root

class FunctionCall:
    def __init__(
        self, statobj, func, depth=0, stats=None, id=0, parent_ids=[], hsv=(0, 0.5, 1)
    ):
        self.statobj = statobj
        self.func = func
        if stats:
            self.stats = stats
        else:
            self.stats = statobj.stats[func][:4]
        self.depth = depth
        self.id = id
        self.parent_ids = parent_ids
        self.hsv = hsv

    def parent_classes(self):
        return self.parent_classes

    def background(self):
        r, g, b = hsv_to_rgb(*self.hsv)
        return "rgb({:f}%,{:f}%,{:f}%)".format(r * 100, g * 100, b * 100)

    def func_std_string(self):  # match what old profile produced
        func_name = self.func
        if func_name[:2] == ("~", 0):
            # special case for built-in functions
            name = func_name[2]
            if name.startswith("<") and name.endswith(">"):
                return "{%s}" % name[1:-1]
            else:
                return name
        else:
            file_name, line_num, method = self.func
            idx = file_name.find("/site-packages/")
            if idx > -1:
                file_name = file_name[(idx + 14) :]

            split_path = file_name.rsplit(os.sep, 1)
            if len(split_path) > 1:
                file_path, file_name = file_name.rsplit(os.sep, 1)
            else:
                file_path = "<module>"

            return format_html(
                '{0}/'
                '{1}'
                ' in {3}'
                '({2})',
                file_path,
                file_name,
                line_num,
                method,
            )

    def subfuncs(self):
        i = 0
        h, s, v = self.hsv
        count = len(self.statobj.all_callees[self.func])
        for func, stats in self.statobj.all_callees[self.func].items():
            i += 1
            h1 = h + (i / count) / (self.depth + 1)
            if stats[3] == 0:
                s1 = 0
            else:
                s1 = s * (stats[3] / self.stats[3])
            yield FunctionCall(
                self.statobj,
                func,
                self.depth + 1,
                stats=stats,
                id=str(self.id) + "_" + str(i),
                parent_ids=self.parent_ids + [self.id],
                hsv=(h1, s1, 1),
            )

    def count(self):
        return self.stats[1]

    def tottime(self):
        return self.stats[2]

    def cumtime(self):
        cc, nc, tt, ct = self.stats
        return self.stats[3]

    def tottime_per_call(self):
        cc, nc, tt, ct = self.stats

        if nc == 0:
            return 0

        return tt / nc

    def cumtime_per_call(self):
        cc, nc, tt, ct = self.stats

        if cc == 0:
            return 0

        return ct / cc

    def indent(self):
        return 16 * self.depth

class ProfilingPanel(Panel):
    """
    Panel that displays profiling information.
    """

    title = _("Profiling")

    template = "debug_toolbar/panels/profiling.html"

    def process_request(self, request):
        self.profiler = cProfile.Profile()
        return self.profiler.runcall(super().process_request, request)

    def add_node(self, func_list, func, max_depth, cum_time=0.1):
        func_list.append(func)
        func.has_subfuncs = False
        if func.depth < max_depth:
            for subfunc in func.subfuncs():
                if subfunc.stats[3] >= cum_time:
                    func.has_subfuncs = True
                    self.add_node(func_list, subfunc, max_depth, cum_time=cum_time)

    def generate_stats(self, request, response):
        if not hasattr(self, "profiler"):
            return None
        # Could be delayed until the panel content is requested (perf. optim.)
        self.profiler.create_stats()
        self.stats = DjangoDebugToolbarStats(self.profiler)
        self.stats.calc_callees()

        root_func = self.stats.get_root_func()
        # Ensure root function exists before continuing with function call analysis
        if root_func:
            root = FunctionCall(self.stats, root_func, depth=0)
            func_list = []
            self.add_node(
                func_list,
                root,
                dt_settings.get_config()["PROFILER_MAX_DEPTH"],
                root.stats[3] / 8,
            )
            self.record_stats({"func_list": func_list})

{'repo_name': 'jazzband/django-debug-toolbar', 'stars': '6020', 'repo_language': 'Python', 'file_name': 'config', 'mime_type': 'text/plain', 'hash': -7202755297023606490, 'source_dataset': 'data'}


// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package ssh

// Session implements an interactive session described in
// "RFC 4254, section 6".

import (
	"bytes"
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"sync"
)

type Signal string

// POSIX signals as listed in RFC 4254 Section 6.10.
const (
	SIGABRT Signal = "ABRT"
	SIGALRM Signal = "ALRM"
	SIGFPE  Signal = "FPE"
	SIGHUP  Signal = "HUP"
	SIGILL  Signal = "ILL"
	SIGINT  Signal = "INT"
	SIGKILL Signal = "KILL"
	SIGPIPE Signal = "PIPE"
	SIGQUIT Signal = "QUIT"
	SIGSEGV Signal = "SEGV"
	SIGTERM Signal = "TERM"
	SIGUSR1 Signal = "USR1"
	SIGUSR2 Signal = "USR2"
)

var signals = map[Signal]int{
	SIGABRT: 6,
	SIGALRM: 14,
	SIGFPE:  8,
	SIGHUP:  1,
	SIGILL:  4,
	SIGINT:  2,
	SIGKILL: 9,
	SIGPIPE: 13,
	SIGQUIT: 3,
	SIGSEGV: 11,
	SIGTERM: 15,
}

type TerminalModes map[uint8]uint32

// POSIX terminal mode flags as listed in RFC 4254 Section 8.
const (
	tty_OP_END    = 0
	VINTR         = 1
	VQUIT         = 2
	VERASE        = 3
	VKILL         = 4
	VEOF          = 5
	VEOL          = 6
	VEOL2         = 7
	VSTART        = 8
	VSTOP         = 9
	VSUSP         = 10
	VDSUSP        = 11
	VREPRINT      = 12
	VWERASE       = 13
	VLNEXT        = 14
	VFLUSH        = 15
	VSWTCH        = 16
	VSTATUS       = 17
	VDISCARD      = 18
	IGNPAR        = 30
	PARMRK        = 31
	INPCK         = 32
	ISTRIP        = 33
	INLCR         = 34
	IGNCR         = 35
	ICRNL         = 36
	IUCLC         = 37
	IXON          = 38
	IXANY         = 39
	IXOFF         = 40
	IMAXBEL       = 41
	ISIG          = 50
	ICANON        = 51
	XCASE         = 52
	ECHO          = 53
	ECHOE         = 54
	ECHOK         = 55
	ECHONL        = 56
	NOFLSH        = 57
	TOSTOP        = 58
	IEXTEN        = 59
	ECHOCTL       = 60
	ECHOKE        = 61
	PENDIN        = 62
	OPOST         = 70
	OLCUC         = 71
	ONLCR         = 72
	OCRNL         = 73
	ONOCR         = 74
	ONLRET        = 75
	CS7           = 90
	CS8           = 91
	PARENB        = 92
	PARODD        = 93
	TTY_OP_ISPEED = 128
	TTY_OP_OSPEED = 129
)

// A Session represents a connection to a remote command or shell.
type Session struct {
	// Stdin specifies the remote process's standard input.
	// If Stdin is nil, the remote process reads from an empty
	// bytes.Buffer.
	Stdin io.Reader

	// Stdout and Stderr specify the remote process's standard
	// output and error.
	//
	// If either is nil, Run connects the corresponding file
	// descriptor to an instance of ioutil.Discard. There is a
	// fixed amount of buffering that is shared for the two streams.
	// If either blocks it may eventually cause the remote
	// command to block.
	Stdout io.Writer
	Stderr io.Writer

	ch        Channel // the channel backing this session
	started   bool    // true once Start, Run or Shell is invoked.
	copyFuncs []func() error
	errors    chan error // one send per copyFunc

	// true if pipe method is active
	stdinpipe, stdoutpipe, stderrpipe bool

	// stdinPipeWriter is non-nil if StdinPipe has not been called
	// and Stdin was specified by the user; it is the write end of
	// a pipe connecting Session.Stdin to the stdin channel.
	stdinPipeWriter io.WriteCloser

	exitStatus chan error
}

// SendRequest sends an out-of-band channel request on the SSH channel
// underlying the session.
func (s *Session) SendRequest(name string, wantReply bool, payload []byte) (bool, error) {
	return s.ch.SendRequest(name, wantReply, payload)
}

func (s *Session) Close() error {
	return s.ch.Close()
}

// RFC 4254 Section 6.4.
type setenvRequest struct {
	Name  string
	Value string
}

// Setenv sets an environment variable that will be applied to any
// command executed by Shell or Run.
func (s *Session) Setenv(name, value string) error {
	msg := setenvRequest{
		Name:  name,
		Value: value,
	}
	ok, err := s.ch.SendRequest("env", true, Marshal(&msg))
	if err == nil && !ok {
		err = errors.New("ssh: setenv failed")
	}
	return err
}

// RFC 4254 Section 6.2.
type ptyRequestMsg struct {
	Term     string
	Columns  uint32
	Rows     uint32
	Width    uint32
	Height   uint32
	Modelist string
}

// RequestPty requests the association of a pty with the session on the remote host.
func (s *Session) RequestPty(term string, h, w int, termmodes TerminalModes) error {
	var tm []byte
	for k, v := range termmodes {
		kv := struct {
			Key byte
			Val uint32
		}{k, v}

		tm = append(tm, Marshal(&kv)...)
	}
	tm = append(tm, tty_OP_END)
	req := ptyRequestMsg{
		Term:     term,
		Columns:  uint32(w),
		Rows:     uint32(h),
		Width:    uint32(w * 8),
		Height:   uint32(h * 8),
		Modelist: string(tm),
	}
	ok, err := s.ch.SendRequest("pty-req", true, Marshal(&req))
	if err == nil && !ok {
		err = errors.New("ssh: pty-req failed")
	}
	return err
}

// RFC 4254 Section 6.5.
type subsystemRequestMsg struct {
	Subsystem string
}

// RequestSubsystem requests the association of a subsystem with the session on the remote host.
// A subsystem is a predefined command that runs in the background when the ssh session is initiated
func (s *Session) RequestSubsystem(subsystem string) error {
	msg := subsystemRequestMsg{
		Subsystem: subsystem,
	}
	ok, err := s.ch.SendRequest("subsystem", true, Marshal(&msg))
	if err == nil && !ok {
		err = errors.New("ssh: subsystem request failed")
	}
	return err
}

// RFC 4254 Section 6.7.
type ptyWindowChangeMsg struct {
	Columns uint32
	Rows    uint32
	Width   uint32
	Height  uint32
}

// WindowChange informs the remote host about a terminal window dimension change to h rows and w columns.
func (s *Session) WindowChange(h, w int) error {
	req := ptyWindowChangeMsg{
		Columns: uint32(w),
		Rows:    uint32(h),
		Width:   uint32(w * 8),
		Height:  uint32(h * 8),
	}
	_, err := s.ch.SendRequest("window-change", false, Marshal(&req))
	return err
}

// RFC 4254 Section 6.9.
type signalMsg struct {
	Signal string
}

// Signal sends the given signal to the remote process.
// sig is one of the SIG* constants.
func (s *Session) Signal(sig Signal) error {
	msg := signalMsg{
		Signal: string(sig),
	}

	_, err := s.ch.SendRequest("signal", false, Marshal(&msg))
	return err
}

// RFC 4254 Section 6.5.
type execMsg struct {
	Command string
}

// Start runs cmd on the remote host. Typically, the remote
// server passes cmd to the shell for interpretation.
// A Session only accepts one call to Run, Start or Shell.
func (s *Session) Start(cmd string) error {
	if s.started {
		return errors.New("ssh: session already started")
	}
	req := execMsg{
		Command: cmd,
	}

	ok, err := s.ch.SendRequest("exec", true, Marshal(&req))
	if err == nil && !ok {
		err = fmt.Errorf("ssh: command %v failed", cmd)
	}
	if err != nil {
		return err
	}
	return s.start()
}

// Run runs cmd on the remote host. Typically, the remote
// server passes cmd to the shell for interpretation.
// A Session only accepts one call to Run, Start, Shell, Output,
// or CombinedOutput.
//
// The returned error is nil if the command runs, has no problems
// copying stdin, stdout, and stderr, and exits with a zero exit
// status.
//
// If the remote server does not send an exit status, an error of type
// *ExitMissingError is returned. If the command completes
// unsuccessfully or is interrupted by a signal, the error is of type
// *ExitError. Other error types may be returned for I/O problems.
func (s *Session) Run(cmd string) error {
	err := s.Start(cmd)
	if err != nil {
		return err
	}
	return s.Wait()
}

// Output runs cmd on the remote host and returns its standard output.
func (s *Session) Output(cmd string) ([]byte, error) {
	if s.Stdout != nil {
		return nil, errors.New("ssh: Stdout already set")
	}
	var b bytes.Buffer
	s.Stdout = &b
	err := s.Run(cmd)
	return b.Bytes(), err
}

type singleWriter struct {
	b  bytes.Buffer
	mu sync.Mutex
}

func (w *singleWriter) Write(p []byte) (int, error) {
	w.mu.Lock()
	defer w.mu.Unlock()
	return w.b.Write(p)
}

// CombinedOutput runs cmd on the remote host and returns its combined
// standard output and standard error.
func (s *Session) CombinedOutput(cmd string) ([]byte, error) {
	if s.Stdout != nil {
		return nil, errors.New("ssh: Stdout already set")
	}
	if s.Stderr != nil {
		return nil, errors.New("ssh: Stderr already set")
	}
	var b singleWriter
	s.Stdout = &b
	s.Stderr = &b
	err := s.Run(cmd)
	return b.b.Bytes(), err
}

// Shell starts a login shell on the remote host. A Session only
// accepts one call to Run, Start, Shell, Output, or CombinedOutput.
func (s *Session) Shell() error {
	if s.started {
		return errors.New("ssh: session already started")
	}

	ok, err := s.ch.SendRequest("shell", true, nil)
	if err == nil && !ok {
		return errors.New("ssh: could not start shell")
	}
	if err != nil {
		return err
	}
	return s.start()
}

func (s *Session) start() error {
	s.started = true

	type F func(*Session)
	for _, setupFd := range []F{(*Session).stdin, (*Session).stdout, (*Session).stderr} {
		setupFd(s)
	}

	s.errors = make(chan error, len(s.copyFuncs))
	for _, fn := range s.copyFuncs {
		go func(fn func() error) {
			s.errors <- fn()
		}(fn)
	}
	return nil
}

// Wait waits for the remote command to exit.
//
// The returned error is nil if the command runs, has no problems
// copying stdin, stdout, and stderr, and exits with a zero exit
// status.
//
// If the remote server does not send an exit status, an error of type
// *ExitMissingError is returned. If the command completes
// unsuccessfully or is interrupted by a signal, the error is of type
// *ExitError. Other error types may be returned for I/O problems.
func (s *Session) Wait() error {
	if !s.started {
		return errors.New("ssh: session not started")
	}
	waitErr := <-s.exitStatus

	if s.stdinPipeWriter != nil {
		s.stdinPipeWriter.Close()
	}
	var copyError error
	for _ = range s.copyFuncs {
		if err := <-s.errors; err != nil && copyError == nil {
			copyError = err
		}
	}
	if waitErr != nil {
		return waitErr
	}
	return copyError
}

func (s *Session) wait(reqs <-chan *Request) error {
	wm := Waitmsg{status: -1}
	// Wait for msg channel to be closed before returning.
	for msg := range reqs {
		switch msg.Type {
		case "exit-status":
			wm.status = int(binary.BigEndian.Uint32(msg.Payload))
		case "exit-signal":
			var sigval struct {
				Signal     string
				CoreDumped bool
				Error      string
				Lang       string
			}
			if err := Unmarshal(msg.Payload, &sigval); err != nil {
				return err
			}

			// Must sanitize strings?
			wm.signal = sigval.Signal
			wm.msg = sigval.Error
			wm.lang = sigval.Lang
		default:
			// This handles keepalives and matches
			// OpenSSH's behaviour.
			if msg.WantReply {
				msg.Reply(false, nil)
			}
		}
	}
	if wm.status == 0 {
		return nil
	}
	if wm.status == -1 {
		// exit-status was never sent from server
		if wm.signal == "" {
			// signal was not sent either.  RFC 4254
			// section 6.10 recommends against this
			// behavior, but it is allowed, so we let
			// clients handle it.
			return &ExitMissingError{}
		}
		wm.status = 128
		if _, ok := signals[Signal(wm.signal)]; ok {
			wm.status += signals[Signal(wm.signal)]
		}
	}

	return &ExitError{wm}
}

// ExitMissingError is returned if a session is torn down cleanly, but
// the server sends no confirmation of the exit status.
type ExitMissingError struct{}

func (e *ExitMissingError) Error() string {
	return "wait: remote command exited without exit status or exit signal"
}

func (s *Session) stdin() {
	if s.stdinpipe {
		return
	}
	var stdin io.Reader
	if s.Stdin == nil {
		stdin = new(bytes.Buffer)
	} else {
		r, w := io.Pipe()
		go func() {
			_, err := io.Copy(w, s.Stdin)
			w.CloseWithError(err)
		}()
		stdin, s.stdinPipeWriter = r, w
	}
	s.copyFuncs = append(s.copyFuncs, func() error {
		_, err := io.Copy(s.ch, stdin)
		if err1 := s.ch.CloseWrite(); err == nil && err1 != io.EOF {
			err = err1
		}
		return err
	})
}

func (s *Session) stdout() {
	if s.stdoutpipe {
		return
	}
	if s.Stdout == nil {
		s.Stdout = ioutil.Discard
	}
	s.copyFuncs = append(s.copyFuncs, func() error {
		_, err := io.Copy(s.Stdout, s.ch)
		return err
	})
}

func (s *Session) stderr() {
	if s.stderrpipe {
		return
	}
	if s.Stderr == nil {
		s.Stderr = ioutil.Discard
	}
	s.copyFuncs = append(s.copyFuncs, func() error {
		_, err := io.Copy(s.Stderr, s.ch.Stderr())
		return err
	})
}

// sessionStdin reroutes Close to CloseWrite.
type sessionStdin struct {
	io.Writer
	ch Channel
}

func (s *sessionStdin) Close() error {
	return s.ch.CloseWrite()
}

// StdinPipe returns a pipe that will be connected to the
// remote command's standard input when the command starts.
func (s *Session) StdinPipe() (io.WriteCloser, error) {
	if s.Stdin != nil {
		return nil, errors.New("ssh: Stdin already set")
	}
	if s.started {
		return nil, errors.New("ssh: StdinPipe after process started")
	}
	s.stdinpipe = true
	return &sessionStdin{s.ch, s.ch}, nil
}

// StdoutPipe returns a pipe that will be connected to the
// remote command's standard output when the command starts.
// There is a fixed amount of buffering that is shared between
// stdout and stderr streams. If the StdoutPipe reader is
// not serviced fast enough it may eventually cause the
// remote command to block.
func (s *Session) StdoutPipe() (io.Reader, error) {
	if s.Stdout != nil {
		return nil, errors.New("ssh: Stdout already set")
	}
	if s.started {
		return nil, errors.New("ssh: StdoutPipe after process started")
	}
	s.stdoutpipe = true
	return s.ch, nil
}

// StderrPipe returns a pipe that will be connected to the
// remote command's standard error when the command starts.
// There is a fixed amount of buffering that is shared between
// stdout and stderr streams. If the StderrPipe reader is
// not serviced fast enough it may eventually cause the
// remote command to block.
func (s *Session) StderrPipe() (io.Reader, error) {
	if s.Stderr != nil {
		return nil, errors.New("ssh: Stderr already set")
	}
	if s.started {
		return nil, errors.New("ssh: StderrPipe after process started")
	}
	s.stderrpipe = true
	return s.ch.Stderr(), nil
}

// newSession returns a new interactive session on the remote host.
func newSession(ch Channel, reqs <-chan *Request) (*Session, error) {
	s := &Session{
		ch: ch,
	}
	s.exitStatus = make(chan error, 1)
	go func() {
		s.exitStatus <- s.wait(reqs)
	}()

	return s, nil
}

// An ExitError reports unsuccessful completion of a remote command.
type ExitError struct {
	Waitmsg
}

func (e *ExitError) Error() string {
	return e.Waitmsg.String()
}

// Waitmsg stores the information about an exited remote command
// as reported by Wait.
type Waitmsg struct {
	status int
	signal string
	msg    string
	lang   string
}

// ExitStatus returns the exit status of the remote command.
func (w Waitmsg) ExitStatus() int {
	return w.status
}

// Signal returns the exit signal of the remote command if
// it was terminated violently.
func (w Waitmsg) Signal() string {
	return w.signal
}

// Msg returns the exit message given by the remote command
func (w Waitmsg) Msg() string {
	return w.msg
}

// Lang returns the language tag. See RFC 3066
func (w Waitmsg) Lang() string {
	return w.lang
}

func (w Waitmsg) String() string {
	str := fmt.Sprintf("Process exited with status %v", w.status)
	if w.signal != "" {
		str += fmt.Sprintf(" from signal %v", w.signal)
	}
	if w.msg != "" {
		str += fmt.Sprintf(". Reason was: %v", w.msg)
	}
	return str
}

{'repo_name': 'etcd-io/etcdlabs', 'stars': '133', 'repo_language': 'Go', 'file_name': 'main.go', 'mime_type': 'text/x-c', 'hash': 2648235374435067568, 'source_dataset': 'data'}


package mindustry.world;

import arc.*;
import arc.math.*;
import arc.math.geom.*;
import arc.util.*;
import mindustry.annotations.Annotations.*;
import mindustry.content.*;
import mindustry.entities.*;
import mindustry.game.EventType.*;
import mindustry.game.*;
import mindustry.world.blocks.*;
import mindustry.world.blocks.ConstructBlock.*;

import static mindustry.Vars.*;

public class Build{

    @Remote(called = Loc.server)
    public static void beginBreak(Team team, int x, int y){
        if(!validBreak(team, x, y)){
            return;
        }

        Tile tile = world.tileBuilding(x, y);
        //this should never happen, but it doesn't hurt to check for links
        float prevPercent = 1f;

        if(tile.build != null){
            prevPercent = tile.build.healthf();
        }

        int rotation = tile.build != null ? tile.build.rotation : 0;
        Block previous = tile.block();
        Block sub = ConstructBlock.get(previous.size);

        tile.setBlock(sub, team, rotation);
        tile.<ConstructBuild>bc().setDeconstruct(previous);
        tile.build.health(tile.build.maxHealth() * prevPercent);

        Core.app.post(() -> Events.fire(new BlockBuildBeginEvent(tile, team, true)));
    }

    /** Places a BuildBlock at this location. */
    @Remote(called = Loc.server)
    public static void beginPlace(Block result, Team team, int x, int y, int rotation){
        if(!validPlace(result, team, x, y, rotation)){
            return;
        }

        Tile tile = world.tile(x, y);

        //just in case
        if(tile == null) return;

        Block previous = tile.block();
        Block sub = ConstructBlock.get(result.size);

        result.beforePlaceBegan(tile, previous);

        tile.setBlock(sub, team, rotation);
        tile.<ConstructBuild>bc().setConstruct(previous.size == sub.size ? previous : Blocks.air, result);

        result.placeBegan(tile, previous);

        Core.app.post(() -> Events.fire(new BlockBuildBeginEvent(tile, team, false)));
    }

    /** Returns whether a tile can be placed at this location by this team. */
    public static boolean validPlace(Block type, Team team, int x, int y, int rotation){
        //the wave team can build whatever they want as long as it's visible - banned blocks are not applicable
        if(type == null || (!type.isPlaceable() && !(state.rules.waves && team == state.rules.waveTeam && type.isVisible()))){
            return false;
        }

        if((type.solid || type.solidifes) && Units.anyEntities(x * tilesize + type.offset - type.size*tilesize/2f, y * tilesize + type.offset - type.size*tilesize/2f, type.size * tilesize, type.size*tilesize)){
            return false;
        }

        if(state.teams.eachEnemyCore(team, core -> Mathf.dst(x * tilesize + type.offset, y * tilesize + type.offset, core.x, core.y) < state.rules.enemyCoreBuildRadius + type.size * tilesize / 2f)){
            return false;
        }

        Tile tile = world.tile(x, y);

        if(tile == null) return false;

        //campaign darkness check
        if(world.getDarkness(x, y) >= 3){
            return false;
        }

        if(!type.requiresWater && !contactsShallows(tile.x, tile.y, type) && !type.placeableLiquid){
            return false;
        }

        if(!type.canPlaceOn(tile, team)){
            return false;
        }

        int offsetx = -(type.size - 1) / 2;
        int offsety = -(type.size - 1) / 2;

        for(int dx = 0; dx < type.size; dx++){
            for(int dy = 0; dy < type.size; dy++){
                int wx = dx + offsetx + tile.x, wy = dy + offsety + tile.y;

                Tile check = world.tile(wx, wy);
                if(
                check == null || //nothing there
                (check.floor().isDeep() && !type.floating && !type.requiresWater && !type.placeableLiquid) || //deep water
                (type == check.block() && check.build != null && rotation == check.build.rotation && type.rotate) || //same block, same rotation
                !check.interactable(team) || //cannot interact
                !check.floor().placeableOn || //solid wall
                    !((type.canReplace(check.block()) || //can replace type
                        (check.block instanceof ConstructBlock && check.<ConstructBuild>bc().cblock == type && check.centerX() == tile.x && check.centerY() == tile.y)) && //same type in construction
                    type.bounds(tile.x, tile.y, Tmp.r1).grow(0.01f).contains(check.block.bounds(check.centerX(), check.centerY(), Tmp.r2))) || //no replacement
                (type.requiresWater && check.floor().liquidDrop != Liquids.water) //requires water but none found
                ) return false;
            }
        }

        return true;
    }

    public static boolean contactsGround(int x, int y, Block block){
        if(block.isMultiblock()){
            for(Point2 point : Edges.getEdges(block.size)){
                Tile tile = world.tile(x + point.x, y + point.y);
                if(tile != null && !tile.floor().isLiquid) return true;
            }
        }else{
            for(Point2 point : Geometry.d4){
                Tile tile = world.tile(x + point.x, y + point.y);
                if(tile != null && !tile.floor().isLiquid) return true;
            }
        }
        return false;
    }

    public static boolean contactsShallows(int x, int y, Block block){
        if(block.isMultiblock()){
            for(Point2 point : Edges.getInsideEdges(block.size)){
                Tile tile = world.tile(x + point.x, y + point.y);
                if(tile != null && !tile.floor().isDeep()) return true;
            }

            for(Point2 point : Edges.getEdges(block.size)){
                Tile tile = world.tile(x + point.x, y + point.y);
                if(tile != null && !tile.floor().isDeep()) return true;
            }
        }else{
            for(Point2 point : Geometry.d4){
                Tile tile = world.tile(x + point.x, y + point.y);
                if(tile != null && !tile.floor().isDeep()) return true;
            }
            Tile tile = world.tile(x, y);
            return tile != null && !tile.floor().isDeep();
        }
        return false;
    }

    /** Returns whether the tile at this position is breakable by this team */
    public static boolean validBreak(Team team, int x, int y){
        Tile tile = world.tile(x, y);
        return tile != null && tile.block().canBreak(tile) && tile.breakable() && tile.interactable(team);
    }
}

{'repo_name': 'Anuken/Mindustry', 'stars': '4788', 'repo_language': 'Java', 'file_name': 'run_server.bat', 'mime_type': 'text/x-msdos-batch', 'hash': -5669323321377879983, 'source_dataset': 'data'}


using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using Ookii.Dialogs;
using RocksmithToolkitLib;
using RocksmithToolkitLib.Extensions;
using RocksmithToolkitLib.XmlRepository;

namespace RocksmithToolkitGUI.Config
{
    public partial class GeneralConfig : UserControl
    {
        private const string MESSAGEBOX_CAPTION = "General Config";
        private bool loading = false;

        public string GetConfigVersion() // also used by AutoUpdater and AssemblyCaller
        {
            // increment the Version here to force RocksmithToolkitUpdater to do a fresh install of RocksmithToolkitLib.*.xml
            return (string)"3";
        }

        // only gets called one time
        public GeneralConfig()
        {
            InitializeComponent();

            // fix readonly textbox/cuebox background colors
            general_rs1path.BackColor = SystemColors.Window;
            general_rs2014path.BackColor = SystemColors.Window;
            general_wwisepath.BackColor = SystemColors.Window;
            creator_defaulttone.BackColor = SystemColors.Window;
            creator_defaultproject.BackColor = SystemColors.Window;

            general_defaultauthor.Validating += ValidateSortName;
            loading = true;

            try
            {
                PopulateAppIdCombo(general_defaultappid_RS2012, GameVersion.RS2012);
                PopulateAppIdCombo(general_defaultappid_RS2014, GameVersion.RS2014);
                PopulateEnumCombo(general_defaultgameversion, typeof(GameVersion));
                PopulateEnumCombo(general_defaultplatform, typeof(GamePlatform));
                PopulateEnumCombo(converter_source, typeof(GamePlatform));
                PopulateEnumCombo(converter_target, typeof(GamePlatform));
                PopulateRampUp();
                PopulateConfigDDC();

                // CRITICAL - force static Wwise path and settings for Mac Mono/Wine packages on first run
                if ((Environment.OSVersion.Platform == PlatformID.MacOSX || GeneralExtension.IsWine()) && ConfigRepository.Instance().GetBoolean("general_firstrun"))
                {
                    ConfigRepository.Instance()["general_autoupdate"] = "false";
                    ConfigRepository.Instance()["general_replacerepo"] = "true";
                    ConfigRepository.Instance()["general_defaultauthor"] = "CST_Mac";
                    ConfigRepository.Instance()["general_wwisepath"] = "C:\\Program Files (x86)\\Audiokinetic\\Wwise\\Authoring"; // interestingly the full path is not needed here
                    ConfigRepository.Instance()["general_replacerepo"] = "false";
                    ConfigRepository.Instance()["general_defaultplatform"] = "Mac";
                    // TODO: identify these Mac paths if static (they are not static)
                    ConfigRepository.Instance()["general_rs2014path"] = "";
                    ConfigRepository.Instance()["general_rs1path"] = "";
                }

                LoadAndSetupConfiguration(this.Controls);
            }
            catch { /*For mono compatibility*/ }

            loading = false;
        }

        private void ValidateSortName(object sender, CancelEventArgs e)
        {
            var tb = sender as TextBox;
            if (tb != null)
                tb.Text = tb.Text.Trim().GetValidSortableName();
        }

        private void LoadAndSetupConfiguration(ControlCollection controls)
        {
            foreach (var control in controls)
            {
                if (control is TextBox || control is CueTextBox)
                {
                    var tb = (TextBox)control;
                    tb.Text = (string)ConfigRepository.Instance()[tb.Name];
                }
                else if (control is ComboBox)
                {
                    var cb = (ComboBox)control;
                    var value = ConfigRepository.Instance()[cb.Name];
                    if (!String.IsNullOrEmpty(cb.ValueMember))
                        cb.SelectedValue = value;
                    else
                        cb.SelectedItem = value;
                }
                else if (control is CheckBox)
                {
                    var ch = (CheckBox)control;
                    ch.Checked = ConfigRepository.Instance().GetBoolean(ch.Name);
                }
                else if (control is NumericUpDown)
                {
                    var nud = (NumericUpDown)control;
                    nud.Value = ConfigRepository.Instance().GetDecimal(nud.Name);
                }
                else if (control is GroupBox)
                    LoadAndSetupConfiguration(((GroupBox)control).Controls);
            }

            // hide First Run
            if (ConfigRepository.Instance()["general_firstrun"] == "false")
                lblFirstRun.Visible = false;
        }

        private void PopulateAppIdCombo(ComboBox combo, GameVersion gameVersion)
        {
            var appIdList = SongAppIdRepository.Instance().Select(gameVersion).ToArray();
            combo.DataSource = appIdList;
            combo.DisplayMember = "DisplayName";
            combo.ValueMember = "AppId";
        }

        private void PopulateEnumCombo(ComboBox combo, Type typeEnum)
        {
            var enumList = Enum.GetNames(typeEnum).ToList<string>();
            enumList.Remove("None");
            combo.DataSource = enumList;
        }

        private void PopulateRampUp()
        {
            if (Directory.Exists(@".\ddc\"))
            {
                ddc_rampup.Items.Clear();
                foreach (var xml in Directory.EnumerateFiles(@".\ddc\", "*.xml", SearchOption.AllDirectories))
                {
                    var name = Path.GetFileNameWithoutExtension(xml);
                    if (name.StartsWith("user_"))
                        name = name.Remove(0, 5);
                    ddc_rampup.Items.Add(name);
                    ddc_rampup.SelectedItem = ConfigRepository.Instance()[ddc_rampup.Name];
                }
            }
        }

        private void PopulateConfigDDC()
        {
            var ddcpath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "ddc");
            if (Directory.Exists(ddcpath))
            {
                ddc_config.Items.Clear();
                foreach (var xml in Directory.EnumerateFiles(ddcpath, "*.cfg", SearchOption.AllDirectories))
                {
                    var name = Path.GetFileNameWithoutExtension(xml);
                    if (name.StartsWith("user_", StringComparison.Ordinal))
                        name = name.Remove(0, 5);
                    ddc_config.Items.Add(name);
                    ddc_config.SelectedItem = ConfigRepository.Instance()[ddc_config.Name];
                }
            }
        }

        private void ConfigurationChanged(object sender, EventArgs e)
        {
            if (loading)
                return;

            Control control = (Control)sender;
            var key = control.Name;
            var value = control.Text;

            if (control is ComboBox)
            {
                var combo = ((ComboBox)control);
                if (!String.IsNullOrEmpty(combo.ValueMember))
                    value = combo.SelectedValue.ToString();
                else
                    value = combo.SelectedItem.ToString();
            }
            else if (control is CheckBox)
            {
                value = ((CheckBox)control).Checked.ToString().ToLower();
            }
            else if (control is NumericUpDown)
            {
                value = ((NumericUpDown)control).Value.ToString(CultureInfo.InvariantCulture);
            }

            if (ConfigRepository.Instance().ValueChanged(key, value) && !String.IsNullOrEmpty(value))
                ConfigRepository.Instance()[key] = value;
        }

        private void btnCloseConfig_Click(object sender, EventArgs e)
        {
            ConfigRepository.Instance()["generalconfigversion"] = GetConfigVersion();
            ConfigRepository.Instance()["general_firstrun"] = "false";
            ((MainForm)ParentForm).ReloadControls();
        }

        private void btnRs1Path_Click(object sender, EventArgs e)
        {
            using (var fbd = new VistaFolderBrowserDialog())
            {
                fbd.SelectedPath = general_rs1path.Text;
                fbd.Description = "Select Rocksmith 2012 executable root installation folder.";

                if (fbd.ShowDialog() != DialogResult.OK)
                    return;

                var rs1Path = fbd.SelectedPath;
                general_rs1path.Text = rs1Path;
                ConfigRepository.Instance()["general_rs1path"] = rs1Path;
            }
        }

        private void btnRs2014Path_Click(object sender, EventArgs e)
        {
            using (var fbd = new VistaFolderBrowserDialog())
            {
                fbd.SelectedPath = general_rs2014path.Text;
                fbd.Description = "Select Rocksmith 2014 executable root installation folder.";

                if (fbd.ShowDialog() != DialogResult.OK)
                    return;

                var rs2014Path = fbd.SelectedPath;
                general_rs2014path.Text = rs2014Path;
                ConfigRepository.Instance()["general_rs2014path"] = rs2014Path;
            }
        }

        private void btnWwisePath_Click(object sender, EventArgs e)
        {
            using (var fbd = new VistaFolderBrowserDialog())
            {
                fbd.SelectedPath = general_wwisepath.Text;
                fbd.Description = "Select the 'WwiseCLI.exe' installation folder," + Environment.NewLine +
                    "or press 'X' to close and clear the Wwise Path.";

                if (fbd.ShowDialog() != DialogResult.OK)
                {
                    fbd.SelectedPath = ""; // allow user to clear the path
                    // return; // leaves the path as-is
                }

                var wwisePath = fbd.SelectedPath;
                general_wwisepath.Text = wwisePath;
                ConfigRepository.Instance()["general_wwisepath"] = wwisePath;
            }
        }

        private void btnProjectDir_Click(object sender, EventArgs e)
        {
            using (var fbd = new VistaFolderBrowserDialog())
            {
                fbd.SelectedPath = creator_defaultproject.Text;
                fbd.Description = "Select Default Project Folder for the CDLC Creator";
                if (fbd.ShowDialog() != DialogResult.OK)
                    return;

                var projectDir = fbd.SelectedPath;
                creator_defaultproject.Text = projectDir;
                ConfigRepository.Instance()["creator_defaultproject"] = projectDir;
            }
        }

        private void btnTonePath_Click(object sender, EventArgs e)
        {
            using (var ofd = new OpenFileDialog())
            {
                ofd.InitialDirectory = creator_defaulttone.Text;
                ofd.Title = "Select Default Tone for the CDLC Creator";
                ofd.Filter = CurrentOFDFilter;

                if (ofd.ShowDialog() != DialogResult.OK)
                    return;

                var tonePath = ofd.FileName;
                creator_defaulttone.Text = tonePath;
                ConfigRepository.Instance()["creator_defaulttone"] = tonePath;
            }
        }

        private string CurrentOFDFilter
        {
            get
            {
                switch (general_defaultgameversion.SelectedItem.ToString())
                {
                    case "RS2014":
                        return "Rocksmith 2014 Tone Template(*.tone2014.xml)|*.tone2014.xml|All XML Files (*.xml)|*.xml";
                    default:
                        return "Rocksmith Tone Template (*.tone.xml)|*.tone.xml|All XML Files (*.xml)|*.xml";
                }
            }
        }

    }
}

{'repo_name': 'rscustom/rocksmith-custom-song-toolkit', 'stars': '281', 'repo_language': 'C#', 'file_name': 'sngFileTable.xml', 'mime_type': 'text/xml', 'hash': -5755348962143661149, 'source_dataset': 'data'}


#.rst:
# FindGDALExtra.cmake
# -------------
#
# Find additional libraries required by GDAL.
# This is only relevant when static linking GDAL.
#
# find_package(GDALExtra ...)
#
# The following are set after the configuration is done:
#
# ::
#
#   GDALExtra_FOUND            - Set to TRUE if the libraries were found.
#   GDALExtra_INCLUDE_DIRS     - Include directories
#   GDALExtra_LIBRARIES        - Path to the libraries.
#   GDALExtra_LIBRARY_DIRS     - compile time link directories
#
#
# Sample usage:
#
# ::
#
#    find_package(GDALExtra)
#    if(GDALExtra_FOUND)
#      target_link_libraries(<YourTarget> ${GDALExtra_LIBRARIES})
#    endif()

if(PREFER_STATIC_LIBS)
  set(_CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES})
  set(CMAKE_FIND_LIBRARY_SUFFIXES .lib .a ${CMAKE_FIND_LIBRARY_SUFFIXES})
endif()

set(GDALExtra_LIBRARIES "")
function(find_static_lib name)
  find_library(${name}_LIBRARY
    NAMES ${ARGN}
    HINTS ENV LD_LIBRARY_PATH
    HINTS ENV DYLD_LIBRARY_PATH
    PATHS
    /usr/lib
    /usr/local/lib
    /usr/local/homebrew/lib
    /opt/local/lib)
endfunction()

if(PREFER_STATIC_LIBS)
  find_static_lib(EXPAT expat)
  find_static_lib(KMLDOM kmldom)
  find_static_lib(MINIZIP minizip)
  find_static_lib(KMLENGINE kmlengine)
  find_static_lib(KMLBASE kmlbase)
  find_static_lib(URIPARSER uriparser)
  find_static_lib(PROJ proj)
  set(GDALExtra_LIBRARIES ${KMLDOM_LIBRARY} ${EXPAT_LIBRARY} ${KMLENGINE_LIBRARY} ${KMLBASE_LIBRARY} ${MINIZIP_LIBRARY} ${URIPARSER_LIBRARY} ${PROJ_LIBRARY})
  if(APPLE)
    find_static_lib(ICONV iconv)
    list(APPEND GDALExtra_LIBRARIES ${ICONV_LIBRARY})
  endif()
endif()

if(PREFER_STATIC_LIBS)
  set(CMAKE_FIND_LIBRARY_SUFFIXES ${_CMAKE_FIND_LIBRARY_SUFFIXES})
endif()

include(FindPackageHandleStandardArgs)
if(PREFER_STATIC_LIBS)
  find_package_handle_standard_args(GDALExtra REQUIRED_VARS EXPAT_LIBRARY KMLDOM_LIBRARY MINIZIP_LIBRARY KMLENGINE_LIBRARY KMLBASE_LIBRARY URIPARSER_LIBRARY PROJ_LIBRARY)
endif()

{'repo_name': 'omnisci/omniscidb', 'stars': '2226', 'repo_language': 'C++', 'file_name': 'omnisci_web_server@.service.in', 'mime_type': 'text/plain', 'hash': -5218719766351009612, 'source_dataset': 'data'}


/*
 * Copyright (c) 2000 Apple Computer, Inc. All rights reserved.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. The rights granted to you under the License
 * may not be used to create, or enable the creation or redistribution of,
 * unlawful or unlicensed copies of an Apple operating system, or to
 * circumvent, violate, or enable the circumvention or violation of, any
 * terms of an Apple operating system software license agreement.
 *
 * Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
 */
/*
 * @OSF_COPYRIGHT@
 *
 */
/*
 *	File: mach/lock_set.defs
 *	Author: Joseph CaraDonna
 *
 *	Exported kernel calls
 *
 */

subsystem
#if	KERNEL_SERVER
	KernelServer
#endif	/* KERNEL_SERVER */
			lock_set 617000;

#include <mach/std_types.defs>
#include <mach/mach_types.defs>

/*
 * a lock_set_t is created and destroyed through the task object.
 *      lock_set_create(task,&lock_set_t,...);
 *      lock_set_destroy(task,lock_set_t);
 */

routine lock_acquire(
		lock_set	: lock_set_t;
		lock_id		: int);

routine lock_release(
		lock_set	: lock_set_t;
		lock_id		: int);

routine lock_try(
		lock_set	: lock_set_t;
		lock_id		: int);

routine lock_make_stable(
		lock_set	: lock_set_t;
		lock_id		: int);

routine lock_handoff(
		lock_set	: lock_set_t;
		lock_id		: int);

routine lock_handoff_accept(
		lock_set	: lock_set_t;
		lock_id		: int);

/* vim: set ft=c : */

{'repo_name': 'waneck/linux-ios-toolchain', 'stars': '152', 'repo_language': 'C', 'file_name': 'pngmem.c', 'mime_type': 'text/x-c', 'hash': 3420541764148462146, 'source_dataset': 'data'}


// Copyright 2013 the V8 project authors. All rights reserved.
// Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1.  Redistributions of source code must retain the above copyright
//     notice, this list of conditions and the following disclaimer.
// 2.  Redistributions in binary form must reproduce the above copyright
//     notice, this list of conditions and the following disclaimer in the
//     documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

description("Test to ensure correct behaviour of Object.defineProperties");

shouldThrow("Object.create()");
shouldThrow("Object.create('a string')");
shouldThrow("Object.create({}, 'a string')");
shouldThrow("Object.create(null, 'a string')");
shouldBe("JSON.stringify(Object.create(null,{property:{value:'foo', enumerable:true}, property2:{value:'foo', enumerable:true}}))", '\'{"property":"foo","property2":"foo"}\'');
shouldBe("JSON.stringify(Object.create({},{property:{value:'foo', enumerable:true}, property2:{value:'foo', enumerable:true}}))", '\'{"property":"foo","property2":"foo"}\'');
shouldBe("JSON.stringify(Object.create({},{property:{value:'foo'}, property2:{value:'foo', enumerable:true}}))", '\'{"property2":"foo"}\'');
shouldBe("JSON.stringify(Object.create(null,{property:{value:'foo'}, property2:{value:'foo', enumerable:true}}))", '\'{"property2":"foo"}\'');
shouldBe("Object.getPrototypeOf(Object.create(Array.prototype))", "Array.prototype");
shouldBe("Object.getPrototypeOf(Object.create(null))", "null");
function valueGet() { return true; }
var DescriptorWithValueGetter = { foo: Object.create(null, { value: { get: valueGet }})};
var DescriptorWithEnumerableGetter = { foo: Object.create(null, { value: {value: true}, enumerable: { get: valueGet }})};
var DescriptorWithConfigurableGetter = { foo: Object.create(null, { value: {value: true}, configurable: { get: valueGet }})};
var DescriptorWithWritableGetter = { foo: Object.create(null, { value: {value: true}, writable: { get: valueGet }})};
var DescriptorWithGetGetter = { foo: Object.create(null, { get: { get: function() { return valueGet } }})};
var DescriptorWithSetGetter = { foo: Object.create(null, { get: { value: valueGet}, set: { get: function(){ return valueGet; } }})};
shouldBeTrue("Object.create(null, DescriptorWithValueGetter).foo");
shouldBeTrue("Object.create(null, DescriptorWithEnumerableGetter).foo");
shouldBeTrue("Object.create(null, DescriptorWithConfigurableGetter).foo");
shouldBeTrue("Object.create(null, DescriptorWithWritableGetter).foo");
shouldBeTrue("Object.create(null, DescriptorWithGetGetter).foo");
shouldBeTrue("Object.create(null, DescriptorWithSetGetter).foo");

{'repo_name': 'h0x91b/redis-v8', 'stars': '133', 'repo_language': 'C++', 'file_name': 'ConnectionFactory.php', 'mime_type': 'text/x-php', 'hash': -1070894500595056042, 'source_dataset': 'data'}


<map id="PxActor" name="PxActor">
<area shape="rect" id="node2" href="$classPxBase.html" title="Base class for objects that can be members of a PxCollection. " alt="" coords="48,109,116,136"/>
<area shape="rect" id="node3" href="$classPxFlags.html" title="PxFlags\< PxBaseFlag\l::Enum, PxU16 \>" alt="" coords="5,5,159,47"/>
</map>

{'repo_name': 'NVIDIAGameWorks/PhysX', 'stars': '1496', 'repo_language': 'C++', 'file_name': 'targa.h', 'mime_type': 'text/x-c', 'hash': 463580415811365478, 'source_dataset': 'data'}


/*
* Copyright 2004 ThoughtWorks, Inc
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/

function TestLoop(commandFactory) {
    this.commandFactory = commandFactory;
}

TestLoop.prototype = {

    start : function() {
        selenium.reset();
        LOG.debug("currentTest.start()");
        this.continueTest();
    },

    continueTest : function() {
        /**
         * Select the next command and continue the test.
         */
        LOG.debug("currentTest.continueTest() - acquire the next command");
        if (! this.aborted) {
            this.currentCommand = this.nextCommand();
        }
        if (! this.requiresCallBack) {
            this.continueTestAtCurrentCommand();
        } // otherwise, just finish and let the callback invoke continueTestAtCurrentCommand()
    },

    continueTestAtCurrentCommand : function() {
        LOG.debug("currentTest.continueTestAtCurrentCommand()");
        if (this.currentCommand) {
            // TODO: rename commandStarted to commandSelected, OR roll it into nextCommand
            this.commandStarted(this.currentCommand);
            this._resumeAfterDelay();
        } else {
            this._testComplete();
        }
    },

    _resumeAfterDelay : function() {
        /**
         * Pause, then execute the current command.
         */

        // Get the command delay. If a pauseInterval is set, use it once
        // and reset it.  Otherwise, use the defined command-interval.
        var delay = this.pauseInterval || this.getCommandInterval();
        this.pauseInterval = undefined;

        if (this.currentCommand.isBreakpoint || delay < 0) {
            // Pause: enable the "next/continue" button
            this.pause();
        } else {
            window.setTimeout(fnBind(this.resume, this), delay);
        }
    },

    resume: function() {
        /**
         * Select the next command and continue the test.
         */
        LOG.debug("currentTest.resume() - actually execute");
        try {
            selenium.browserbot.runScheduledPollers();
            this._executeCurrentCommand();
            this.continueTestWhenConditionIsTrue();
        } catch (e) {
            if (!this._handleCommandError(e)) {
                this.testComplete();
            } else {
                this.continueTest();
            }
        }
    },

    _testComplete : function() {
        selenium.ensureNoUnhandledPopups();
        this.testComplete();
    },

    _executeCurrentCommand : function() {
        /**
         * Execute the current command.
         *
         * @return a function which will be used to determine when
         * execution can continue, or null if we can continue immediately
         */
        var command = this.currentCommand;
        LOG.info("Executing: |" + command.command + " | " + command.target + " | " + command.value + " |");

        var handler = this.commandFactory.getCommandHandler(command.command);
        if (handler == null) {
            throw new SeleniumError("Unknown command: '" + command.command + "'");
        }

        command.target = selenium.preprocessParameter(command.target);
        command.value = selenium.preprocessParameter(command.value);
        LOG.debug("Command found, going to execute " + command.command);
        this.result = handler.execute(selenium, command);

        this.waitForCondition = this.result.terminationCondition;

    },

    _handleCommandError : function(e) {
        if (!e.isSeleniumError) {
            LOG.exception(e);
            var msg = "Command execution failure. Please search the forum at http://clearspace.openqa.org for error details from the log window.";
            msg += "  The error message is: " + extractExceptionMessage(e);
            return this.commandError(msg);
        } else {
            LOG.error(e.message);
            return this.commandError(e.message);
        }
    },

    continueTestWhenConditionIsTrue: function () {
        /**
         * Busy wait for waitForCondition() to become true, and then carry
         * on with test.  Fail the current test if there's a timeout or an
         * exception.
         */
        //LOG.debug("currentTest.continueTestWhenConditionIsTrue()");
        selenium.browserbot.runScheduledPollers();
        try {
            if (this.waitForCondition == null) {
                LOG.debug("null condition; let's continueTest()");
                LOG.debug("Command complete");
                this.commandComplete(this.result);
                this.continueTest();
            } else if (this.waitForCondition()) {
                LOG.debug("condition satisfied; let's continueTest()");
                this.waitForCondition = null;
                LOG.debug("Command complete");
                this.commandComplete(this.result);
                this.continueTest();
            } else {
                //LOG.debug("waitForCondition was false; keep waiting!");
                window.setTimeout(fnBind(this.continueTestWhenConditionIsTrue, this), 10);
            }
        } catch (e) {
            this.result = {};
            this.result.failed = true;
            this.result.failureMessage = extractExceptionMessage(e);
            this.commandComplete(this.result);
            this.continueTest();
        }
    },

    pause : function() {},
    nextCommand : function() {},
    commandStarted : function() {},
    commandComplete : function() {},
    commandError : function() {},
    testComplete : function() {},

    getCommandInterval : function() {
        return 0;
    }

}

{'repo_name': 'wocommunity/wonder', 'stars': '205', 'repo_language': 'Java', 'file_name': 'org.eclipse.core.resources.prefs', 'mime_type': 'text/plain', 'hash': -60355416599952344, 'source_dataset': 'data'}


fileFormatVersion: 2
guid: ed262769151458e428319e338719c476
MonoImporter:
  externalObjects: {}
  serializedVersion: 2
  defaultReferences: []
  executionOrder: 0
  icon: {instanceID: 0}
  userData:
  assetBundleName:
  assetBundleVariant:

{'repo_name': 'lgsvl/simulator', 'stars': '1003', 'repo_language': 'C#', 'file_name': 'README.md', 'mime_type': 'text/plain', 'hash': -8708044587555372458, 'source_dataset': 'data'}


# Copyright (c) 2014-2020 Maltrail developers (https://github.com/stamparm/maltrail/)
# See the file 'LICENSE' for copying permission

# Reference: https://www.symantec.com/security_response/writeup.jsp?docid=2016-082614-4453-99&tabid=2

powertoolsforyou.com
templatesupdates.dlinkddns.com

{'repo_name': 'stamparm/maltrail', 'stars': '3644', 'repo_language': 'Python', 'file_name': 'strings.py', 'mime_type': 'text/x-python', 'hash': -3784292135415993773, 'source_dataset': 'data'}


require  meta-python-image-base.bb

SUMMARY = "meta-python ptest test image"

IMAGE_INSTALL += "packagegroup-meta-python3-ptest"

{'repo_name': 'openembedded/meta-openembedded', 'stars': '185', 'repo_language': 'BitBake', 'file_name': 'waf-samba.bbclass', 'mime_type': 'text/x-python', 'hash': -2012073420839265760, 'source_dataset': 'data'}