text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Security.Cryptography.X509Certificates;
using Android.Accounts;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Content.PM;
using Android.Util;
using Java.Security;
using Java.Util.Concurrent;
using Signature = Android.Content.PM.Signature;
using Microsoft.Identity.Client.Core;
using Microsoft.Identity.Client.Internal.Broker;
using Microsoft.Identity.Client.Utils;
using Microsoft.Identity.Json.Linq;
using System.Threading.Tasks;
using OperationCanceledException = Android.Accounts.OperationCanceledException;
using AndroidUri = Android.Net.Uri;
using Android.Database;
using Microsoft.Identity.Json.Utilities;
using System.Threading;
using Microsoft.Identity.Client.OAuth2;
using Microsoft.Identity.Client.Http;
using AndroidNative = Android;
using System.Linq;

namespace Microsoft.Identity.Client.Platforms.Android.Broker
{
#if MAUI
    [Preserve(AllMembers = true)]
#else
    [global::Android.Runtime.Preserve(AllMembers = true)]
#endif
    internal class AndroidBrokerHelper
    {
        private const string RedirectUriScheme = "msauth";
        private const string BrokerTag = BrokerConstants.Signature;

        private readonly Context _androidContext;

        // Important: this object MUST be accessed on a background thread. Android will check this and throw otherwise.
        public AccountManager AndroidAccountManager { get; }
        private readonly ILoggerAdapter _logger;

        public AndroidBrokerHelper(Context androidContext, ILoggerAdapter logger)
        {
            _androidContext = androidContext ?? throw new ArgumentNullException(nameof(androidContext));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));

            _logger.Verbose("[Android broker] Getting the Android context for broker request. ");
            AndroidAccountManager = AccountManager.Get(_androidContext);
        }

        public bool IsBrokerInstalledAndInvokable(AuthorityType authorityType)
        {
            using (_logger.LogMethodDuration())
            {
                bool canInvoke = CanSwitchToBroker();
                _logger.Verbose("[Android broker] Can invoke broker? " + canInvoke);

                return canInvoke;
            }
        }

        private bool CanSwitchToBroker()
        {
            string packageName = _androidContext.PackageName;

            // Rules are:
            // 1- broker app is installed
            // 2- signature of the broker is valid
            // 3- account exists

            //Force this to return true for broker test app
            var authenticator = GetInstalledAuthenticator();
            return authenticator!= null
                   && !packageName.Equals(BrokerConstants.PackageName, StringComparison.OrdinalIgnoreCase)
                   && !packageName
           .Equals(BrokerConstants.AzureAuthenticatorAppPackageName, StringComparison.OrdinalIgnoreCase);
        }

        public Bundle CreateHandShakeOperationBundle()
        {
            Bundle handshakeOperationBundle = new Bundle();
            handshakeOperationBundle.PutString(BrokerConstants.ClientAdvertisedMaximumBPVersionKey, BrokerConstants.BrokerProtocolVersionCode);
            handshakeOperationBundle.PutString(BrokerConstants.ClientConfiguredMinimumBPVersionKey, "2.0");
            handshakeOperationBundle.PutString(BrokerConstants.BrokerAccountManagerOperationKey, "HELLO");

            return handshakeOperationBundle;
        }

        public string GetSilentResultFromBundle(Bundle bundleResult)
        {
            string responseJson = bundleResult.GetString(BrokerConstants.BrokerResultV2);

            bool success = bundleResult.GetBoolean(BrokerConstants.BrokerRequestV2Success);
            _logger.Info($"[Android broker] Silent call result - success? {success}. ");

            if (!success)
            {
                _logger.Warning($"[Android broker] Silent call failed. " +
                    $"This usually means that the RT cannot be refreshed and interaction is required. " +
                    $"BundleResult: {bundleResult} Result string: {responseJson}");
            }

            // upstream logic knows how to extract potential errors from this result
            return responseJson;
        }

        public BrokerRequest UpdateBrokerRequestWithAccountData(string accountData, BrokerRequest brokerRequest)
        {
            if (string.IsNullOrEmpty(accountData))
            {
                _logger.Info("[Android broker] Android account manager didn't return any accounts. ");
                throw new MsalUiRequiredException(MsalError.NoAndroidBrokerAccountFound, MsalErrorMessage.NoAndroidBrokerAccountFound);
            }

            string username = brokerRequest.UserName;
            string homeAccountId = brokerRequest.HomeAccountId;
            string localAccountId = brokerRequest.LocalAccountId;

                dynamic AccountDataList = JArray.Parse(accountData);

                foreach (JObject account in AccountDataList)
                {
                    var accountInfo = account[BrokerResponseConst.Account];
                    var accountInfoHomeAccountID = accountInfo[BrokerResponseConst.HomeAccountId]?.ToString();
                    var accountInfoLocalAccountID = accountInfo[BrokerResponseConst.LocalAccountId]?.ToString();

                    if (string.Equals(accountInfo[BrokerResponseConst.UserName].ToString(), username, StringComparison.OrdinalIgnoreCase))
                    {
                        // TODO: broker request should be immutable!
                        brokerRequest.HomeAccountId = accountInfoHomeAccountID;
                        brokerRequest.LocalAccountId = accountInfoLocalAccountID;
                        _logger.Info("[Android broker] Found broker account in Android account manager using the provided login hint. ");
                        return brokerRequest;
                    }

                    if (string.Equals(accountInfoHomeAccountID, homeAccountId, StringComparison.Ordinal) &&
                         string.Equals(accountInfoLocalAccountID, localAccountId, StringComparison.Ordinal))
                    {
                        _logger.Info("[Android broker] Found broker account in Android account manager using the provided account. ");
                        return brokerRequest;
                    }
                }

            _logger.Info("[Android broker] The requested account does not exist in the Android account manager. ");
            throw new MsalUiRequiredException(MsalError.NoAndroidBrokerAccountFound, MsalErrorMessage.NoAndroidBrokerAccountFound);
        }

        /// <summary>
        /// This method will acquire all of the accounts in the account manager that have an access token for the given client ID.
        /// </summary>
        public IReadOnlyList<IAccount> ExtractBrokerAccountsFromAccountData(string accountData)
        {
            List<IAccount> brokerAccounts = new List<IAccount>();

            if (!string.IsNullOrEmpty(accountData))
            {
                dynamic authResult = JArray.Parse(accountData);

                foreach (JObject account in authResult)
                {
                    if (account.ContainsKey(BrokerResponseConst.Account))
                    {
                        var accountInfo = account[BrokerResponseConst.Account];
                        IAccount iAccount = new Account(
                            accountInfo.Value<string>(BrokerResponseConst.HomeAccountId) ?? string.Empty,
                            accountInfo.Value<string>(BrokerResponseConst.UserName) ?? string.Empty,
                            accountInfo.Value<string>(BrokerResponseConst.Environment) ?? string.Empty);
                        brokerAccounts.Add(iAccount);
                    }
                }
            }

            _logger.Info("[Android broker] Found " + brokerAccounts.Count + " accounts in the account manager. ");

            return brokerAccounts;
        }

        public void ValidateBrokerRedirectUri(BrokerRequest brokerRequest)
        {
            using (_logger.LogMethodDuration())
            {
                string computedRedirectUri = GetRedirectUriForBroker();

                if (!string.Equals(computedRedirectUri, brokerRequest.RedirectUri.AbsoluteUri, StringComparison.OrdinalIgnoreCase))
                {
                    string msg = string.Format(CultureInfo.CurrentCulture, "[Android broker] The broker redirect URI is incorrect, it should be {0}. Please visit https://aka.ms/Brokered-Authentication-for-Android for more details. ", computedRedirectUri);
                    _logger.Info(msg);
                    throw new MsalClientException(MsalError.CannotInvokeBroker, msg);
                }
            }
        }

        private string GetRedirectUriForBroker()
        {
            string packageName = Application.Context.PackageName;

            // First available signature. Applications can be signed with multiple
            // signatures.
            string signatureDigest = GetCurrentSignatureForPackage(packageName);
            if (!string.IsNullOrEmpty(signatureDigest))
            {
                return string.Format(CultureInfo.InvariantCulture, "{0}://{1}/{2}", RedirectUriScheme,
                    packageName.ToLowerInvariant(), signatureDigest);
            }

            return string.Empty;
        }

        private string GetCurrentSignatureForPackage(string packageName)
        {
            try
            {
                PackageInfo info = Application.Context.PackageManager.GetPackageInfo(packageName,
                    PackageInfoFlags.Signatures);
#pragma warning disable CS0618 // Type or member is obsolete - https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/1854
                if (info != null && info.Signatures != null && info.Signatures.Count > 0)
                {
                    Signature signature = info.Signatures[0];
                    MessageDigest md = MessageDigest.GetInstance("SHA");
                    md.Update(signature.ToByteArray());
                    return Convert.ToBase64String(md.Digest(), Base64FormattingOptions.None);
                    // Server side needs to register all other tags. ADAL will
                    // send one of them.
                }
#pragma warning restore CS0618 // Type or member is obsolete

            }
            catch (PackageManager.NameNotFoundException)
            {
                _logger.Info("[Android broker] Calling App's package does not exist in PackageManager. ");
            }
            catch (NoSuchAlgorithmException)
            {
                _logger.Info("[Android broker] Digest SHA algorithm does not exists. ");
            }

            return null;
        }

        public Bundle CreateSilentBrokerBundle(BrokerRequest brokerRequest)
        {
            ValidateBrokerRedirectUri(brokerRequest);
            Bundle bundle = new Bundle();
            string brokerRequestJson = JsonHelper.SerializeToJson(brokerRequest);
            _logger.InfoPii("[Android broker] CreateSilentBrokerBundle: " + brokerRequestJson, "Enable PII to see the silent broker request. ");
            bundle.PutString(BrokerConstants.BrokerRequestV2, brokerRequestJson);
            bundle.PutInt(BrokerConstants.CallerInfoUID, Binder.CallingUid);

            return bundle;
        }

        public Bundle CreateBrokerAccountBundle(BrokerRequest brokerRequest)
        {
            _logger.InfoPii("[Android broker] CreateBrokerAccountBundle: " + JsonHelper.SerializeToJson(brokerRequest), "Enable PII to see the broker account bundle request. ");
            Bundle bundle = new Bundle();

            bundle.PutString(BrokerConstants.AccountClientIdKey, brokerRequest.ClientId);
            bundle.PutString(BrokerConstants.AccountRedirect, brokerRequest.UrlEncodedRedirectUri);
            bundle.PutInt(BrokerConstants.CallerInfoUID, Binder.CallingUid);

            return bundle;
        }

        public Bundle CreateRemoveBrokerAccountBundle(string clientId, IAccount account)
        {
            Bundle bundle = new Bundle();

            bundle.PutString(BrokerConstants.AccountClientIdKey, clientId);
            bundle.PutString(BrokerConstants.Environment, account.Environment);
            bundle.PutString(BrokerConstants.HomeAccountIDKey, account.HomeAccountId.Identifier);

            return bundle;
        }

        private bool VerifySignature(string brokerPackageName)
        {
            List<X509Certificate2> certs = ReadCertDataForBrokerApp(brokerPackageName);

            VerifySignatureHash(certs);
            if (certs.Count > 1)
            {
                // Verify the certificate chain is chained correctly.
                VerifyCertificateChain(certs);
            }

            return true;
        }

        private void VerifySignatureHash(List<X509Certificate2> certs)
        {
            bool validSignatureFound = false;

            foreach (var signerCert in certs)
            {
                MessageDigest messageDigest = MessageDigest.GetInstance("SHA");
                messageDigest.Update(signerCert.RawData);

                // Check the hash for signer cert is the same as what we hardcoded.
                string signatureHash = Base64.EncodeToString(messageDigest.Digest(), Base64Flags.NoWrap);
                if (BrokerTag.Equals(signatureHash, StringComparison.OrdinalIgnoreCase) ||
                    BrokerConstants.AzureAuthenticatorAppSignature.Equals(signatureHash, StringComparison.OrdinalIgnoreCase))
                {
                    validSignatureFound = true;
                }
            }

            if (!validSignatureFound)
            {
                throw new MsalClientException(MsalError.AndroidBrokerSignatureVerificationFailed, "No matching signature found");
            }
        }

        private void VerifyCertificateChain(List<X509Certificate2> certificates)
        {
            X509Certificate2Collection collection = new X509Certificate2Collection(certificates.ToArray());
            X509Chain chain = new X509Chain();
            chain.ChainPolicy = new X509ChainPolicy()
            {
#pragma warning disable IA5352 //Certificates are not published to a CRL when revoked for broker so this check cannot be made
                RevocationMode = X509RevocationMode.NoCheck
#pragma warning restore IA5352
            };

            chain.ChainPolicy.ExtraStore.AddRange(collection);
            foreach (X509Certificate2 certificate in certificates)
            {
                var chainBuilt = chain.Build(certificate);

                if (!chainBuilt)
                {
                    foreach (X509ChainStatus chainStatus in chain.ChainStatus)
                    {
                        if (chainStatus.Status != X509ChainStatusFlags.UntrustedRoot)
                        {
                            throw new MsalClientException(MsalError.AndroidBrokerSignatureVerificationFailed,
                                string.Format(CultureInfo.InvariantCulture, "app certificate validation failed with {0}", chainStatus.Status));
                        }
                    }
                }
            }
        }

        private List<X509Certificate2> ReadCertDataForBrokerApp(string brokerPackageName)
        {
            PackageInfo packageInfo = _androidContext.PackageManager.GetPackageInfo(brokerPackageName,
                PackageInfoFlags.Signatures);
            if (packageInfo == null)
            {
                throw new MsalClientException(MsalError.AndroidBrokerSignatureVerificationFailed, "No broker package found");
            }
#pragma warning disable CS0618 // Type or member is obsolete https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/1854

            if (packageInfo.Signatures == null || packageInfo.Signatures.Count == 0)
            {
                throw new MsalClientException(MsalError.AndroidBrokerSignatureVerificationFailed, "No signature associated with the broker package.");
            }

            List<X509Certificate2> certificates = new List<X509Certificate2>(packageInfo.Signatures.Count);
            foreach (Signature signature in packageInfo.Signatures)
            {
                byte[] rawCert = signature.ToByteArray();
                X509Certificate2 x509Certificate = null;
                x509Certificate = new X509Certificate2(rawCert);
                certificates.Add(x509Certificate);
            }
#pragma warning restore CS0618 // Type or member is obsolete

            return certificates;
        }

        private AuthenticatorDescription GetInstalledAuthenticator()
        {
            using (_logger.LogMethodDuration())
            {
                foreach (AuthenticatorDescription authenticator in AndroidAccountManager.GetAuthenticatorTypes())
                {
                    if (authenticator.Type.Equals(BrokerConstants.BrokerAccountType, StringComparison.OrdinalIgnoreCase)
                        && VerifySignature(authenticator.PackageName))
                    {
                        _logger.Verbose("[Android broker] Found the Authenticator on the device. ");
                        return authenticator;
                    }
                }

                _logger.Warning("[Android broker] No Authenticator found on the device. ");
                return null;
            }
        }

        // There may be multiple authenticators from same package
        // , but there is only one entry for an authenticator type in
        // AccountManager.
        // If another app tries to install same authenticator type, it will
        // queue up and will be active after first one is uninstalled.
        public AuthenticatorDescription Authenticator
        {
            get
            {
                return GetInstalledAuthenticator();
            }
        }

        public void LaunchInteractiveActivity(Activity activity, Intent interactiveIntent)
        {
            // onActivityResult will receive the response for this activity.
            // Launching this activity will switch to the broker app.
            try
            {
                _logger.Info(
                    "[Android broker] Calling activity pid:" + Process.MyPid()
                    + " tid:" + Process.MyTid() + "uid:"
                    + Process.MyUid());

                activity.StartActivityForResult(interactiveIntent, 1001);
            }
            catch (ActivityNotFoundException e)
            {
                _logger.ErrorPiiWithPrefix(e, "[Android broker] Unable to get Android activity during interactive broker request. ");
                throw;
            }
        }

        public MsalTokenResponse HandleSilentAuthenticationResult(string silentResult, string correlationId)
        {
            if (!string.IsNullOrEmpty(silentResult))
            {
                return MsalTokenResponse.CreateFromAndroidBrokerResponse(silentResult, correlationId);
            }

            return new MsalTokenResponse
            {
                Error = MsalError.BrokerResponseReturnedError,
                ErrorDescription = "[Android broker] Unknown broker error. Failed to acquire token silently from the broker. " + MsalErrorMessage.AndroidBrokerCannotBeInvoked,
            };
        }

        public void HandleBrokerOperationError(Exception ex)
        {
            _logger.Error(ex.Message);
            if (ex is MsalException)
                throw ex;
            else
                throw new MsalClientException(MsalError.AndroidBrokerOperationFailed, ex.Message, ex);
        }

        public void HandleInstallUrl(string appLink, Activity activity)
        {
            _logger.Info("[Android broker] Starting ActionView activity to " + appLink);
            activity.StartActivity(new Intent(Intent.ActionView, AndroidNative.Net.Uri.Parse(appLink)));

            throw new MsalClientException(
                MsalError.BrokerApplicationRequired,
                MsalErrorMessage.BrokerApplicationRequired);
        }
    }
}


text:
<!DOCTYPE html>

<meta content="text/html;charset=utf-8" http-equiv="content-type"/>

<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>pymel.core.general.validComponentIndexType — PyMEL 1.0.7 documentation</title>
<link href="../../../_static/nature.css" rel="stylesheet" type="text/css"/>
<link href="../../../_static/pygments.css" rel="stylesheet" type="text/css"/>

<link href="../../../index-2.html" rel="top" title="PyMEL 1.0.7 documentation"/>
<link href="../../pymel.core.general.html" rel="up" title="pymel.core.general"/>
<link href="pymel.core.general.vnn.html" rel="next" title="pymel.core.general.vnn"/>
<link href="pymel.core.general.upAxis.html" rel="prev" title="pymel.core.general.upAxis"/>
<link href="../../../../style/adsk.cpm.css" rel="stylesheet" type="text/css"/><meta content="expert" name="experiencelevel"/><meta content="programmer" name="audience"/><meta content="enable" name="user-comments"/><meta content="ENU" name="language"/><meta content="MAYAUL" name="product"/><meta content="2016" name="release"/><meta content="Customization" name="book"/><meta content="Maya-Tech-Docs" name="component"/><meta content="/view/MAYAUL/2016/ENU/" name="helpsystempath"/><meta content="04/03/2015" name="created"/><meta content="04/03/2015" name="modified"/><meta content="Navigation

 index

 modules |

 next |

 previous |
 PyMEL 1.0.7 documentation »
 pymel.core.general »

 pymel.core.general.validComponentIndexType ¶

 validComponentIndexType ( argObj , allowDicts=True , componentIndexTypes=None ) ¶
 True if argObj is of a suitable type for specifying a component's index.
False otherwise.
 Dicts allow for components whose 'mel name' may vary - ie, a single
isoparm component may have, u, v, or..." name="description"/><meta content="__PyMel_generated_functions_pymel_core_general_pymel_core_general_validComponentIndexType_html" name="topicid"/>

Navigation

index

modules |

next |

previous |

PyMEL 1.0.7 documentation »

pymel.core.general »

pymel.core.general.validComponentIndexType¶

<tt class="descname">validComponentIndexType</tt><big>(</big>argObj, allowDicts=True, componentIndexTypes=None<big>)</big>¶

True if argObj is of a suitable type for specifying a component's index.
False otherwise.

Dicts allow for components whose 'mel name' may vary - ie, a single
isoparm component may have, u, v, or uv elements; or, a single pivot
component may have scalePivot and rotatePivot elements.  The key of the
dict would indicate the 'mel component name', and the value the actual
indices.

Thus:

{'u':3, 'v':(4,5), 'uv':ComponentIndex((1,4)) }

would represent single component that contained:

.u[3]
.v[4]
.v[5]
.uv[1][4]

Derived classes should implement:
_dimLength

Previous topic

pymel.core.general.upAxis

Next topic

pymel.core.general.vnn

Core Modules

<tt class="xref">animation</tt>

<tt class="xref">effects</tt>

<tt class="xref">general</tt>

<tt class="xref">language</tt>

<tt class="xref">modeling</tt>

<tt class="xref">rendering</tt>

<tt class="xref">system</tt>

<tt class="xref">windows</tt>

Type Modules

<tt class="xref">datatypes</tt>

<tt class="xref">nodetypes</tt>

<tt class="xref">uitypes</tt>

Other Modules

<tt class="xref">plugins</tt>

<tt class="xref">mayautils</tt>

<tt class="xref">util</tt>

<tt class="xref">versions</tt>

<tt class="xref">tools</tt>

This Page

Show Source

Quick search

<form action="http://help.autodesk.com/cloudhelp/2016/ENU/Maya-Tech-Docs/PyMel/search.html" class="search" method="get"></form>
<input name="q" type="text"/>
<input type="submit" value="Go"/>
<input name="check_keywords" type="hidden" value="yes"/>
<input name="area" type="hidden" value="default"/>

    Enter search terms or a module, class or function name.

Navigation

index

modules |

next |

previous |

PyMEL 1.0.7 documentation »

pymel.core.general »

        © Copyright 2009, Chad Dombrova.
      Created using Sphinx 1.2.3.

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace litepubl\core;

interface ResponsiveInterface
{
    public function request(Context $context);
}


text:
package org.kaaproject.kaa.common.dto.event;

public enum EventClassType {
  EVENT, OBJECT;
}


text:
package execcmd

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/aws/amazon-ecs-agent/agent/config"
	dockercontainer "github.com/docker/docker/api/types/container"
)

const (
	folderPerm = 0755
)

var (
	ecsAgentExecDepsDir = config.AmazonECSProgramFiles + "\\managed-agents\\execute-command"

	// ecsAgentDepsBinDir is the directory where ECS Agent will read versions of SSM agent
	ecsAgentDepsBinDir = ecsAgentExecDepsDir + "\\bin"

	ContainerDepsFolder = config.AmazonProgramFiles + "\\SSM"

	SSMAgentBinName       = "amazon-ssm-agent.exe"
	SSMAgentWorkerBinName = "ssm-agent-worker.exe"
	SessionWorkerBinName  = "ssm-session-worker.exe"

	HostLogDir      = config.AmazonECSProgramData + "\\exec"
	ContainerLogDir = config.AmazonProgramData + "\\SSM"

	SSMPluginDir = config.AmazonProgramFiles + "\\SSM\\Plugins"
	// since ecs agent windows is not running in a container, the agent and host log dirs are the same
	ECSAgentExecLogDir = config.AmazonECSProgramData + "\\exec"

	// ECSAgentExecConfigDir is the directory where ECS Agent will write the ExecAgent config files to
	ECSAgentExecConfigDir = ecsAgentExecDepsDir + "\\" + ContainerConfigDirName
	// HostExecConfigDir is the dir where ExecAgents Config files will live
	HostExecConfigDir = hostExecDepsDir + "\\" + ContainerConfigDirName

	configFiles = []string{
		"amazon-ssm-agent.json",
		"seelog.xml",
	}

	execAgentLogConfigTemplate = `<!--amazon-ssm-agent uses seelog logging -->
<!--Seelog has github wiki pages, which contain detailed how-tos references: https://github.com/cihub/seelog/wiki -->
<!--Seelog examples can be found here: https://github.com/cihub/seelog-examples -->
<seelog type="adaptive" mininterval="2000000" maxinterval="100000000" critmsgcount="500" minlevel="info">
    <exceptions>
        <exception filepattern="test*" minlevel="error"/>
    </exceptions>
    <outputs formatid="fmtinfo">
        <console formatid="fmtinfo"/>
        <rollingfile type="size" filename="C:\ProgramData\Amazon\SSM\Logs\amazon-ssm-agent.log" maxsize="30000000" maxrolls="5"/>
        <filter levels="error,critical" formatid="fmterror">
            <rollingfile type="size" filename="C:\ProgramData\Amazon\SSM\Logs\errors.log" maxsize="10000000" maxrolls="5"/>
        </filter>
    </outputs>
    <formats>
        <format id="fmterror" format="%Date %Time %LEVEL [%FuncShort @ %File.%Line] %Msg%n"/>
        <format id="fmtdebug" format="%Date %Time %LEVEL [%FuncShort @ %File.%Line] %Msg%n"/>
        <format id="fmtinfo" format="%Date %Time %LEVEL %Msg%n"/>
    </formats>
</seelog>`
)

var GetExecAgentConfigDir = getAgentConfigDir

// Retrieves cached config dir, creates new one if needed
func getAgentConfigDir(sessionLimit int) (string, error) {
	agentConfig := fmt.Sprintf(execAgentConfigTemplate, sessionLimit)
	hash := getExecAgentConfigHash(agentConfig + execAgentLogConfigTemplate)
	// check if cached config dir exists already
	configDirPath := filepath.Join(ECSAgentExecConfigDir, hash)
	if isDir(configDirPath) && validConfigDirExists(configDirPath, hash) {
		return hash, nil
	}
	// check if config dir is a file; if true, remove it
	if fileExists(configDirPath) {
		if err := removeAll(configDirPath); err != nil {
			return "", err
		}
	}
	// create new config dir
	if err := createNewExecAgentConfigDir(agentConfig, configDirPath); err != nil {
		return "", err
	}
	return hash, nil
}

var createNewExecAgentConfigDir = createNewConfigDir

var mkdirAll = os.MkdirAll

func createNewConfigDir(agentConfig, configDirPath string) error {
	// make top level config directory
	err := mkdirAll(configDirPath, folderPerm)
	if err != nil {
		return err
	}

	// make individual config files
	agentConfigFilePath := filepath.Join(configDirPath, containerConfigFileName)
	err = createNewExecAgentConfigFile(agentConfig, agentConfigFilePath)
	if err != nil {
		return err
	}

	logConfigFilePath := filepath.Join(configDirPath, ExecAgentLogConfigFileName)
	err = createNewExecAgentConfigFile(execAgentLogConfigTemplate, logConfigFilePath)
	if err != nil {
		return err
	}

	return nil
}

func validConfigDirExists(configDirPath, expectedHash string) bool {
	// check that each config file exists and create a hash of their summed contents
	contentSum := ""
	for _, file := range configFiles {
		if isDir(filepath.Join(configDirPath, file)) {
			return false
		}
		config, err := getFileContent(filepath.Join(configDirPath, file))
		if err != nil {
			return false
		}
		contentSum += string(config)
	}

	hash := getExecAgentConfigHash(contentSum)
	return strings.Compare(expectedHash, hash) == 0
}

// This function creates any necessary config directories/files and ensures that
// the ssm-agent binaries, configs, logs, and plugin is bind mounted
func addRequiredBindMounts(taskId, cn, latestBinVersionDir, uuid string, sessionWorkersLimit int, hostConfig *dockercontainer.HostConfig) error {
	// In windows host mounts are not created automatically, so need to create
	rErr := os.MkdirAll(filepath.Join(HostLogDir, taskId, cn), folderPerm)
	if rErr != nil {
		return rErr
	}

	configDirHash, rErr := GetExecAgentConfigDir(sessionWorkersLimit)
	if rErr != nil {
		rErr = fmt.Errorf("could not generate ExecAgent Config dir: %v", rErr)
		return rErr
	}

	// Add ssm binary mount
	hostConfig.Binds = append(hostConfig.Binds, getReadOnlyBindMountMapping(
		latestBinVersionDir,
		ContainerDepsFolder))

	// Add ssm configuration dir mount
	hostConfig.Binds = append(hostConfig.Binds, getReadOnlyBindMountMapping(
		filepath.Join(ECSAgentExecConfigDir, configDirHash),
		filepath.Join(ContainerDepsFolder, "configuration")))

	// Add ssm log bind mount
	hostConfig.Binds = append(hostConfig.Binds, getBindMountMapping(
		filepath.Join(HostLogDir, taskId, cn),
		ContainerLogDir))

	// add ssm plugin bind mount (needed for execcmd windows)
	hostConfig.Binds = append(hostConfig.Binds, getReadOnlyBindMountMapping(
		SSMPluginDir,
		SSMPluginDir))

	return nil
}


text:
FROM fsharp/fsharp:latest
MAINTAINER Sheik Uduman Ali M

EXPOSE 8083

WORKDIR /app

CMD ["mono", "CatalogAPI.exe"]


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _5.Fox
{
    class Program
    {
        static void Main(string[] args)
        {
            var n = int.Parse(Console.ReadLine());

            var width = 2 * n + 3;

            for (int row = 1; row <= n; row++)
            {
                var leadingStars = new string('*', row);
                var middleDashes = new string('-', width - row * 2 - 2);
                Console.WriteLine("{0}\\{1}/{0}", leadingStars, middleDashes);
            }

            for (int row = 1; row <= n/3; row++)
            {
                var startFinalStars = new string('*', n/2 + row - 1);
                var middleStars = new string('*', n - row * 2 + 2);
                Console.WriteLine("|{0}\\{1}/{0}|", startFinalStars, middleStars);
            }

            for (int row = 1; row <= n; row++)
            {
                var startFinalDashes = new string('-', row);
                var middleStars = new string('*', width - row * 2 - 2);
                Console.WriteLine("{0}\\{1}/{0}", startFinalDashes, middleStars);
            }
        }
    }
}


text:
/* @flow */
import Router from 'models/router'
import bodyMiddleware from 'viewModels/middlewares/body'
import messageMiddleware from './middlewares/message'

import list from './list'
import read from './read'
import save from './save'
import del from './delete'

import clear from './clear'

const router = new Router

router.get('/', list)
router.get('/:message', messageMiddleware, read)

router.use(bodyMiddleware)

router.put(['/', '/save'], save)
router.post(['/', '/save'], save)

router.del('/:message', messageMiddleware, del)
router.post('/:message/delete', messageMiddleware, del)

router.post('/clear', clear)

export default router


text:
<?php

	/**
	 * Symphony Language Class
	 *
	 * Provides an interface for translations and transliterations
	 */

	// Translations
	function __($string, array $tokens=NULL){
		if(!class_exists('Lang') || !(Lang::Dictionary() instanceof Dictionary)) return vsprintf($string, $tokens);
		return Lang::Dictionary()->translate($string, $tokens);
	}

	// Transliterations
	function _t($str){

		$patterns = array_keys(Lang::Transliterations());
		$values = array_values(Lang::Transliterations());

		$str = preg_replace($patterns, $values, $str);

		return $str;
	}

	/**
	 * Dictionary Class
	 *
	 * Contains the dictionary for the current language and provides the translate function
	 */
	Class Dictionary {

		private $_strings;

		public function __construct(array $strings) {
			$this->_strings = $strings;
		}

		public function translate($string, array $tokens=NULL) {
			$translated = $this->find($string);

			if($translated === false) $translated = $string;

			if(!is_null($tokens) && is_array($tokens) && !empty($tokens)) {
				$translated = vsprintf($translated, $tokens);
			}

			return $translated;

		}

		public function find($string) {
			if(isset($this->_strings[$string])) {
				return $this->_strings[$string];
			}

			return false;
		}

		public function add($from, $to) {
			$this->_strings[$from] = $to;
		}

		public function merge($strings) {
			if(is_array($strings)) $this->_strings = array_merge($this->_strings, $strings);
		}

		public function remove($string) {
			unset($this->_strings[$string]);
		}

	}

	/**
	 * Lanuage Class
	 *
	 * Loads and manages languages
	 */
	Class Lang {

		private static $_dictionary;
		private static $_transliterations;
		private static $_instance;

		/**
		 * Load specified language file
		 */
		public static function load($path, $lang, $clear=false) {

			if((bool)$clear === true || !(self::$_dictionary instanceof Dictionary)) {
				Lang::clear();
			}

			$include = sprintf($path, $lang);

			if(file_exists($include)){
				require($include);
			}

			if(isset($dictionary) && is_array($dictionary)) self::$_dictionary->merge($dictionary);
			if(isset($transliterations) && is_array($transliterations)) self::$_transliterations = array_merge(self::$_transliterations, $transliterations);

			if(empty(self::$_transliterations)) {
				include(TOOLKIT . '/include.transliterations.php');
				self::$_transliterations = $transliterations;
			}
		}

		/**
		 * Clear the current dictionary and transliteration arrays
		 */
		public static function clear() {
			self::$_dictionary = new Dictionary(array());
			self::$_transliterations = array();
		}

		/**
		 * Load all language files (core and extensions)
		 *
		 * It may be possible that there are only translations for an extension,
		 * so don't stop if there is no core translation as Symphony will always display the English strings.
		 */
		public static function loadAll($ExtensionManager) {
			// Load localisation file for the Symphony core
			$file = Lang::findLanguagePath(Symphony::lang(), $ExtensionManager) . '/lang.%s.php';
			$path = sprintf($file, Symphony::lang());
			if(file_exists($path)) {
				Lang::load($file, Symphony::lang(), true);
			}

			// Load localisation files for extensions
			foreach($ExtensionManager->listAll() as $handle => $e){
				$path = $ExtensionManager->__getClassPath($handle) . '/lang/lang.%s.php';
				if($e['status'] == EXTENSION_ENABLED && file_exists(sprintf($path, Symphony::lang()))){
					Lang::add($path, Symphony::lang());
				}
			}
		}

		/**
		 * Find the correct path to the core translations based on the language code
		 *
		 * The default English language strings are stored in /symphony/lib/lang whereas
		 * the localisation files for other languages are stored in the extension folder.
		 */
		public static function findLanguagePath($lang, $ExtensionManager) {
			$file = sprintf('/lang.%s.php', $lang);
			if(!file_exists(LANG . $file)) {
				foreach($ExtensionManager->listAll() as $extension => $about) {
					// Explicitly match localisation extensions
					if(strpos($about['handle'], 'lang_') === false) continue;
					$path = EXTENSIONS . '/' . $about['handle'] . '/lang';
					if(file_exists($path . $file)) {
						return $path;
					}
				}
			}
			else {
				return LANG;
			}
		}

		public static function add($path, $lang) {
			self::load($path, $lang);
		}

		public static function Transliterations() {
			return self::$_transliterations;
		}

		public static function Dictionary() {
			return self::$_dictionary;
		}

		/**
		 * Create handle
		 *
		 * Given a string, this will clean it for use as a Symphony handle. Preserves multi-byte characters
		 * @param string $string
		 * @param int $max_length the maximum number of characters in the handle
		 * @param string $delim all non-valid characters will be replaced with this
		 * @param boolean $uriencode force the resultant string to be uri encoded making it safe for URL's
		 * @param boolean $apply_transliteration if true, this will run the string through an array of substitution characters
		 * @return string resultant handle
		 */
		public static function createHandle($string, $max_length=255, $delim='-', $uriencode=false, $apply_transliteration=true, $additional_rule_set=NULL) {

			// Use the transliteration table if provided
			if($apply_transliteration == true) $string = _t($string);

			$max_length = intval($max_length);

			// Strip out any tag
			$string = strip_tags($string);

			// Remove punctuation
			$string = preg_replace('/[\\.\'"]+/', NULL, $string);

			// Trim it
			if($max_length != NULL && is_numeric($max_length)) $string = General::limitWords($string, $max_length);

			// Replace spaces (tab, newline etc) with the delimiter
			$string = preg_replace('/[\s]+/', $delim, $string);

			// Find all legal characters
			preg_match_all('/[^<>?@:!-\/\[-`ëí;'']+/u', $string, $matches);

			// Join only legal character with the $delim
			$string = implode($delim, $matches[0]);

			// Allow for custom rules
			if(is_array($additional_rule_set) && !empty($additional_rule_set)){
				foreach($additional_rule_set as $rule => $replacement) $string = preg_replace($rule, $replacement, $string);
			}

			// Remove leading or trailing delim characters
			$string = trim($string, $delim);

			// Encode it for URI use
			if($uriencode) $string = urlencode($string);

			// Make it lowercase
			$string = strtolower($string);

			return $string;

		}

		/**
		 * Create filename
		 *
		 * Given a string, this will clean it for use as a filename.
		 * Preserves multi-byte characters.
		 * @param string $string string to clean
		 * @param string $delim replacement for invalid characters
		 * @param boolean $apply_transliteration if true, umlauts and special characters will be substituted
		 * @return string created filename
		 */
		public static function createFilename($string, $delim='-', $apply_transliteration=true) {

			// Use the transliteration table if provided
			if($apply_transliteration == true) $string = _t($string);

			// Strip out any tag
			$string = strip_tags($string);

			// Find all legal characters
			$count = preg_match_all('/[\p{L}\w:;.,+=~]+/u', $string, $matches);
			if($count <= 0 || $count == false){
				preg_match_all('/[\w:;.,+=~]+/', $string, $matches);
			}

			// Join only legal character with the $delim
			$string = implode($delim, $matches[0]);

			// Remove leading or trailing delim characters
			$string = trim($string, $delim);

			// Make it lowercase
			$string = strtolower($string);

			return $string;

		}

		/**
		 * Get browser languages
		 *
		 * Return languages accepted by browser as an array sorted by priority
		 * @return array language codes, e. g. 'en'
		 */
		public static function getBrowserLanguages() {
			static $languages;
			if(is_array($languages)) return $languages;

			$languages = array();

			if(strlen(trim($_SERVER['HTTP_ACCEPT_LANGUAGE'])) < 1) return $languages;
			if(!preg_match_all('/(\w+(?:-\w+)?,?)+(?:;q=(?:\d+\.\d+))?/', preg_replace('/\s+/', '', $_SERVER['HTTP_ACCEPT_LANGUAGE']), $matches)) return $languages;

			$priority = 1.0;
			$languages = array();
			foreach($matches[0] as $def){
				list($list, $q) = explode(';q=', $def);
				if(!empty($q)) $priority=floatval($q);
				$list = explode(',', $list);
				foreach($list as $lang){
					$languages[$lang] = $priority;
					$priority -= 0.000000001;
				}
			}
			arsort($languages);
			$languages = array_keys($languages);
			// return list sorted by descending priority, e.g., array('en-gb','en');
			return $languages;
		}

		/**
         * Get codes of available languages
         *
		 * Return all available languages (core and extensions)
		 * @return array language codes, e. g. 'en'
		 */
		public static function getAvailableLanguages($ExtensionManager=false) {
			$languages = array();
			// Get core translation files
			$languages = self::getLanguageCodes(LIBRARY . '/lang', $languages);
			// Get extension translation files
			if($ExtensionManager) {
				foreach ($ExtensionManager->listAll() as $extension => $about) {
					$path = EXTENSIONS . '/' . $about['handle'] . '/lang';
					if(file_exists($path)) $languages = self::getLanguageCodes($path, $languages);
				}
			}
			// Return languages codes
			return $languages;
		}

		/**
		 * Get languages
		 *
		 * Extract language codes and files
		 * @return array language codes and files
		 */
		public static function getLanguageCodes($path, $languages) {
			$iterator = new DirectoryIterator($path);
			foreach($iterator as $file) {
				if(!$file->isDot() && preg_match('/^lang\.(\w+(-\w+)?)\.php$/', $file->getFilename(), $matches)) {
					if(!isset($languages[$matches[1]])) {
						include($file->getPathname());
						$languages[$matches[1]] = $about['name'];
					}
				}
			}
			return $languages;
		}

	}


text:
package team1;

import battlecode.common.RobotController;

public class Commander extends Mobile {

	public Commander(RobotController rc) {
		super(rc);
		location_channel_x  = defence_location_channel_x;
		location_channel_y  = defence_location_channel_y;
		basic_turn_loop();
	}

}


text:
@class AddUserViewController;

@protocol AddUserViewControllerDelegate <NSObject>
- (void)addUserViewControllerDidCancel:(AddUserViewController *)controller;
- (void)addUserViewController:(AddUserViewController *)controller didAddUser:(NSMutableDictionary *)user;
@end

@interface AddUserViewController : UITableViewController

@property (strong, nonatomic) IBOutlet UITextField *userIDText;
@property (strong, nonatomic) IBOutlet UITextField *nameText;
@property (strong, nonatomic) IBOutlet UITextField *passwordText;
@property (weak) id <AddUserViewControllerDelegate> delegate;

- (IBAction)cancel:(id)sender;
- (IBAction)done:(id)sender;

@end


text:
//Problem 2. Print Company Information

//A company has name, address, phone number, fax number, web site and manager. The manager has first name, last name, age and a phone number.
//Write a program that reads the information about a company and its manager and prints it back on the console.

using System;

class PrintCompanyInformationDetails
{
    static void Main()
    {
        Console.Write("Please enter company name: ");
        string companyName = (Console.ReadLine());
        Console.Write("Please enter company address: ");
        string companyAddress = (Console.ReadLine());
        Console.Write("Please enter company phone number: ");
        string companyPhoneNumber = (Console.ReadLine());
        Console.Write("Please enter company fax number: ");
        string faxNumber = (Console.ReadLine());
        Console.Write("Please enter company web site: ");
        string webSite = (Console.ReadLine());
        Console.Write("Please enter youre first name: ");
        string firstName = (Console.ReadLine());
        Console.Write("Please enter youre last name: ");
        string lastName = (Console.ReadLine());
        object fullName = firstName + " " +  lastName;
        Console.Write("Please enter youre age: ");
        sbyte managerAge = sbyte.Parse(Console.ReadLine());
        Console.Write("Please enter youre phone number: ");
        string managerPhoneNumber=(Console.ReadLine());
        Console.WriteLine(companyName);
        Console.WriteLine("Adress: " + companyAddress);
        Console.WriteLine("Tel. " + companyPhoneNumber);
        Console.WriteLine("Fax: " + faxNumber);
        Console.WriteLine("Web Site: " + webSite);
        Console.WriteLine("Manager: {0} (age: {1}, tel. {2})",fullName, managerAge, managerPhoneNumber);
        Console.WriteLine();
    }
}


text:
* [Design Principles](design_principles.md)
* [DPLA MAP and PCDM](dpla_map_and_pcdm.md)


text:
package com.bddinaction.chapter5.cucumber.steps;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import cucumber.api.PendingException;
import org.junit.Assert;

import java.util.Date;

import static org.hamcrest.CoreMatchers.is;

public class EarningPointsFromFlights {
    @Given("^the (flying|travelling) distance between (.*) and (.*) is (\\d+) km$")
    public void define_flying_distance(String flightMode,
                                       String departure,
                                       String destination,
                                       int distance) {
    }

    @When("^I fly from (.*) to (.*) on (.*)$")
    public void I_fly_from(String departure, String destination, Date date) throws Throwable {
    }

    @Then("^I should earn (\\d+) points$")
    public void I_should_earn_points(int points) throws Throwable {
    }

    @Then("^I should earn a status bonus of <bonus>$")
    public void I_should_earn_a_status_bonus_of_bonus() throws Throwable {
    }

    @When("^I fly on a flight that is worth <base> base points$")
    public void I_fly_on_a_flight_that_is_worth_base_base_points() throws Throwable {
    }

    @When("^I fly on a flight that is worth (\\d+) base points$")
    public void I_fly_on_a_flight_that_is_worth_base_points(int arg1) throws Throwable {
        // Express the Regexp above with the code you wish you had
    }

    @Then("^I should earn a status bonus of (\\d+)$")
    public void I_should_earn_a_status_bonus_of(int arg1) throws Throwable {
        // Express the Regexp above with the code you wish you had
    }

    @Then("^I should have guaranteed minimum earned points per trip of (\\d+)$")
    public void I_should_have_guaranteed_minimum_earned_points_per_trip_of(int arg1) throws Throwable {
        // Express the Regexp above with the code you wish you had
    }

    @Then("^I should earn (\\d+) points in all$")
    public void I_should_earn_points_in_all(int arg1) throws Throwable {
        // Express the Regexp above with the code you wish you had
    }

}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>404</title>
    <link rel="stylesheet" href="<?=\Framework\Helpers\Helpers::url()?>Css/404.css" type="text/css">
    <link rel="stylesheet" href="<?=\Framework\Helpers\Helpers::url()?>Css/bootstrap.min.css" type="text/css">

Whoops!

You got yourself in a situation!

The page you are looking for was moved, removed,

                        renamed or might have never existed.


text:
layout: post
date: '2016-02-07'
title: "Bonny Bridal Bonny Unforgettable 1317 Plus Size Wedding Dress"
category: Bonny Bridal
tags: [Bonny Bridal]
---
### Bonny Bridal Bonny Unforgettable 1317 Plus Size Wedding Dress
Just **$324.99**
###

Not Available In-Store For Try On. Special Order Only.

Timeless elegance, this full A-line organza gown features a lace covered scoop neckline bodice with tip of the shoulder cap sleeves wrapping over the shoulders to the illusion buttoned back. A cinched waist is covered with pleated organza and adorned with floral organza blooms. The train is adorned with a folded drape scattered with sparkling lace.

Sizes Available: 16W- 32W

Buy it: [https://www.eudances.com/en/bonny-bridal/283-bonny-unforgettable-1317-plus-size-wedding-dress.html](https://www.eudances.com/en/bonny-bridal/283-bonny-unforgettable-1317-plus-size-wedding-dress.html)


text:
package cmd

import (
	"fmt"
	"log"

	"github.com/spf13/cobra"
)

var downloadLogfileNow bool

// logfilegetCmd represents the logfiles get command
var logfilegetCmd = &cobra.Command{
	Use:   "get [deployment id]  logfile id/name]",
	Short: "Show Logfile details for deployment",
	Long:  `Show the Logfile details for a deployment's Logfile`,
	Run: func(cmd *cobra.Command, args []string) {
		c := getComposeAPI()
		if len(args) != 2 {
			log.Fatal("Need a deployment id/name and a logfile id")
		}
		depid, err := resolveDepID(c, args[0])
		if err != nil {
			log.Fatal(err)
		}
		logfileid := args[1]
		if outputRaw {
			text, errs := c.GetLogfileDetailsForDeploymentJSON(depid, logfileid)
			bailOnErrs(errs)
			fmt.Println(text)
		} else {
			logfile, errs := c.GetLogfileDetailsForDeployment(depid, logfileid)
			bailOnErrs(errs)

			if !outputJSON {
				fmt.Printf("%15s: %s\n", "Logfile ID", logfile.ID)
				fmt.Printf("%15s: %s\n", "Deployment ID", logfile.Deploymentid)
				fmt.Printf("%15s: %s\n", "Capsule ID", logfile.Capsuleid)
				fmt.Printf("%15s: %s\n", "Logfile Name", logfile.Name)
				fmt.Printf("%15s: %s\n", "Status", logfile.Status)
				fmt.Printf("%15s: %s\n", "Download Link", logfile.DownloadLink)

				if downloadLogfileNow {
					err := DownloadFile(logfile.Name, logfile.DownloadLink)
					if err != nil {
						fmt.Printf("Error downloading: %s\n", err)
					} else {
						fmt.Printf("Downloaded: %s\n", logfile.Name)
					}
				}
			} else {
				printAsJSON(logfile)
			}
		}
	},
}

func init() {
	logfilesCmd.AddCommand(logfilegetCmd)
	logfilegetCmd.Flags().BoolVarP(&downloadLogfileNow, "download", "d", false, "Download the selected logfile")
}


text:
package health

import (
	"context"
	"crypto/tls"
	"log"
	"net"
	"net/http"
	"net/url"
	"sync"
	"time"

	"github.com/influxdata/telegraf"
	"github.com/influxdata/telegraf/internal"
	tlsint "github.com/influxdata/telegraf/internal/tls"
	"github.com/influxdata/telegraf/plugins/outputs"
)

const (
	defaultServiceAddress = "tcp://:8080"
	defaultReadTimeout    = 5 * time.Second
	defaultWriteTimeout   = 5 * time.Second
)

var sampleConfig = `
  ## Address and port to listen on.
  ##   ex: service_address = "tcp://localhost:8080"
  ##       service_address = "unix:///var/run/telegraf-health.sock"
  # service_address = "tcp://:8080"

  ## The maximum duration for reading the entire request.
  # read_timeout = "5s"
  ## The maximum duration for writing the entire response.
  # write_timeout = "5s"

  ## Username and password to accept for HTTP basic authentication.
  # basic_username = "user1"
  # basic_password = "secret"

  ## Allowed CA certificates for client certificates.
  # tls_allowed_cacerts = ["/etc/telegraf/clientca.pem"]

  ## TLS server certificate and private key.
  # tls_cert = "/etc/telegraf/cert.pem"
  # tls_key = "/etc/telegraf/key.pem"

  ## One or more check sub-tables should be defined, it is also recommended to
  ## use metric filtering to limit the metrics that flow into this output.
  ##
  ## When using the default buffer sizes, this example will fail when the
  ## metric buffer is half full.
  ##
  ## namepass = ["internal_write"]
  ## tagpass = { output = ["influxdb"] }
  ##
  ## [[outputs.health.compares]]
  ##   field = "buffer_size"
  ##   lt = 5000.0
  ##
  ## [[outputs.health.contains]]
  ##   field = "buffer_size"
`

type Checker interface {
	// Check returns true if the metrics meet its criteria.
	Check(metrics []telegraf.Metric) bool
}

type Health struct {
	ServiceAddress string            `toml:"service_address"`
	ReadTimeout    internal.Duration `toml:"read_timeout"`
	WriteTimeout   internal.Duration `toml:"write_timeout"`
	BasicUsername  string            `toml:"basic_username"`
	BasicPassword  string            `toml:"basic_password"`
	tlsint.ServerConfig

	Compares []*Compares `toml:"compares"`
	Contains []*Contains `toml:"contains"`
	checkers []Checker

	wg     sync.WaitGroup
	server *http.Server
	origin string

	mu      sync.Mutex
	healthy bool
}

func (h *Health) SampleConfig() string {
	return sampleConfig
}

func (h *Health) Description() string {
	return "Configurable HTTP health check resource based on metrics"
}

// Connect starts the HTTP server.
func (h *Health) Connect() error {
	h.checkers = make([]Checker, 0)
	for i := range h.Compares {
		h.checkers = append(h.checkers, h.Compares[i])
	}
	for i := range h.Contains {
		h.checkers = append(h.checkers, h.Contains[i])
	}

	tlsConf, err := h.ServerConfig.TLSConfig()
	if err != nil {
		return err
	}

	authHandler := internal.AuthHandler(h.BasicUsername, h.BasicPassword, onAuthError)

	h.server = &http.Server{
		Addr:         h.ServiceAddress,
		Handler:      authHandler(h),
		ReadTimeout:  h.ReadTimeout.Duration,
		WriteTimeout: h.WriteTimeout.Duration,
		TLSConfig:    tlsConf,
	}

	listener, err := h.listen(tlsConf)
	if err != nil {
		return err
	}

	h.origin = h.getOrigin(listener, tlsConf)

	log.Printf("I! [outputs.health] Listening on %s", h.origin)

	h.wg.Add(1)
	go func() {
		defer h.wg.Done()
		err := h.server.Serve(listener)
		if err != http.ErrServerClosed {
			log.Printf("E! [outputs.health] Serve error on %s: %v", h.origin, err)
		}
		h.origin = ""
	}()

	return nil
}

func onAuthError(rw http.ResponseWriter, code int) {
	http.Error(rw, http.StatusText(code), code)
}

func (h *Health) listen(tlsConf *tls.Config) (net.Listener, error) {
	u, err := url.Parse(h.ServiceAddress)
	if err != nil {
		return nil, err
	}

	network := "tcp"
	address := u.Host
	if u.Host == "" {
		network = "unix"
		address = u.Path
	}

	if tlsConf != nil {
		return tls.Listen(network, address, tlsConf)
	} else {
		return net.Listen(network, address)
	}

}

func (h *Health) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	var code = http.StatusOK
	if !h.isHealthy() {
		code = http.StatusServiceUnavailable
	}

	rw.Header().Set("Server", internal.ProductToken())
	http.Error(rw, http.StatusText(code), code)
}

// Write runs all checks over the metric batch and adjust health state.
func (h *Health) Write(metrics []telegraf.Metric) error {
	healthy := true
	for _, checker := range h.checkers {
		success := checker.Check(metrics)
		if !success {
			healthy = false
		}
	}

	h.setHealthy(healthy)
	return nil
}

// Close shuts down the HTTP server.
func (h *Health) Close() error {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	h.server.Shutdown(ctx)
	h.wg.Wait()
	return nil
}

// Origin returns the URL of the HTTP server.
func (h *Health) Origin() string {
	return h.origin
}

func (h *Health) getOrigin(listener net.Listener, tlsConf *tls.Config) string {
	switch listener.Addr().Network() {
	case "tcp":
		scheme := "http"
		if tlsConf != nil {
			scheme = "https"
		}
		origin := &url.URL{
			Scheme: scheme,
			Host:   listener.Addr().String(),
		}
		return origin.String()
	case "unix":
		return listener.Addr().String()
	default:
		return ""
	}
}

func (h *Health) setHealthy(healthy bool) {
	h.mu.Lock()
	defer h.mu.Unlock()
	h.healthy = healthy
}

func (h *Health) isHealthy() bool {
	h.mu.Lock()
	defer h.mu.Unlock()
	return h.healthy
}

func NewHealth() *Health {
	return &Health{
		ServiceAddress: defaultServiceAddress,
		ReadTimeout:    internal.Duration{Duration: defaultReadTimeout},
		WriteTimeout:   internal.Duration{Duration: defaultWriteTimeout},
		healthy:        true,
	}
}

func init() {
	outputs.Add("health", func() telegraf.Output {
		return NewHealth()
	})
}


text:
package com.asakusafw.compiler.flow;

import java.lang.annotation.Annotation;
import java.util.Map;

import com.asakusafw.compiler.common.NameGenerator;
import com.asakusafw.compiler.common.Precondition;
import com.asakusafw.compiler.common.TargetOperator;
import com.asakusafw.utils.java.model.syntax.Expression;
import com.asakusafw.utils.java.model.util.ImportBuilder;
import com.asakusafw.vocabulary.flow.graph.FlowElementAttributeProvider;
import com.asakusafw.vocabulary.flow.graph.FlowResourceDescription;
import com.asakusafw.vocabulary.flow.graph.OperatorDescription;
import com.asakusafw.vocabulary.operator.Identity;

/**
 * Processes an operator which is part of line.
 */
public abstract class LinePartProcessor extends LineProcessor {

    @Override
    public final Kind getKind() {
        return Kind.LINE_PART;
    }

    /**
     * Performs this processor for the context.
     * @param context the current context
     * @throws IllegalArgumentException if the parameter is {@code null}
     */
    public abstract void emitLinePart(Context context);

    /**
     * The context object for {@link LinePartProcessor}.
     */
    public static class Context extends LineProcessorContext {

        private final Expression input;

        private Expression resultValue;

        /**
         * Creates a new instance.
         * @param environment the current context
         * @param element the target element
         * @param importer the import declaration builder
         * @param names the unique name generator
         * @param desc the target operator description
         * @param input an expression of the input value for the operator
         * @param resources the mapping between external resources and their Java expressions
         * @throws IllegalArgumentException if the parameters are {@code null}
         */
        public Context(
                FlowCompilingEnvironment environment,
                FlowElementAttributeProvider element,
                ImportBuilder importer,
                NameGenerator names,
                OperatorDescription desc,
                Expression input,
                Map<FlowResourceDescription, Expression> resources) {
            super(environment, element, importer, names, desc, resources);
            Precondition.checkMustNotBeNull(input, "input"); //$NON-NLS-1$
            this.input = input;
            this.resultValue = null;
        }

        /**
         * Returns an expression of the input value.
         * @return the expression of the input value
         */
        public Expression getInput() {
            return input;
        }

        /**
         * Sets an expression of the output value.
         * @param expresion the expression of the output value
         * @throws IllegalStateException if the expression has been already set
         * @throws IllegalArgumentException if the parameter is {@code null}
         */
        public void setOutput(Expression expresion) {
            Precondition.checkMustNotBeNull(expresion, "expresion"); //$NON-NLS-1$
            if (this.resultValue != null) {
                throw new IllegalStateException();
            }
            this.resultValue = expresion;
        }

        /**
         * Returns the expression of the output value.
         * @return the expression of the output value
         * @throws IllegalStateException if the expression has not been set
         * @see #setOutput(Expression)
         */
        public Expression getOutput() {
            if (resultValue == null) {
                throw new IllegalStateException();
            }
            return resultValue;
        }
    }

    /**
     * An implementation of {@link LinePartProcessor} that does nothing.
     */
    @TargetOperator(Identity.class)
    public static class Nop extends LinePartProcessor {
        @Override
        protected Class<? extends Annotation> loadTargetAnnotationType() {
            return Identity.class;
        }
        @Override
        public void emitLinePart(Context context) {
            context.setOutput(context.getInput());
        }
    }
}


text:
\documentclass{article}

\usepackage{graphicx}

\title{AI Homework 4}
\author{Connor Taffe}

\begin{document}
  \maketitle

  The best $k$ value was $k=7$, with an accuracy probability of $0.73743$.

  {\centering\includegraphics[width=\textwidth]{image}}

  \section{Compiling and Executing}

  I suppose open {\tt main.cc} in Visual Studio. Click the run button.

  \section{Description}

  The tradeoffs between the value of $k$ and the accuracy has to do with the number of samples and the size of the dataset. Since I calculated the distance between every node and the testing node before taking the first $k$ nodes and averaging means that because of my hugely inefficient approach, there is no further penalty in performance of averaging more $k$ (there is, but it is an add-loop, which is extremely minimal). What one wants to do is take the maximum $k$ nodes in a locality, which depends highly upon the size of the dataset, and would benefit from wieghting the data. One could hypothesize that a $k$ equal to the size of the dataset and weighted properly would produce the best results, but since the weighting would make some nodes (far away) have a very small effect, the best approach would be to have a variable $k$ which lops off such insignificant weighted nodes.

  The static $k$ really only works well with a very dense homogenized dataset. Sets with different sparsenesses would work poorly.

\end{document}


text:
package com.aspose.cells.examples.articles;

import com.aspose.cells.AbstractCalculationEngine;
import com.aspose.cells.CalculationData;
import com.aspose.cells.*;

public class CustomEngine extends AbstractCalculationEngine
{
	public void calculate(CalculationData data)
        {
		if(data.getFunctionName().toUpperCase().equals("SUM")==true)
                {
                    double val = (double)data.getCalculatedValue();
                    val = val + 30;

                    data.setCalculatedValue(val);
                }
        }
}