text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
using Newtonsoft.Json.Linq;

namespace Microsoft.Azure.Management.Automation
{
    /// <summary>
    /// Service operation for node reports.  (see
    /// http://aka.ms/azureautomationsdk/dscnodereportoperations for more
    /// information)
    /// </summary>
    internal partial class DscNodeReportsOperations : IServiceOperations<AutomationManagementClient>, IDscNodeReportsOperations
    {
        /// <summary>
        /// Initializes a new instance of the DscNodeReportsOperations class.
        /// </summary>
        /// <param name='client'>
        /// Reference to the service client.
        /// </param>
        internal DscNodeReportsOperations(AutomationManagementClient client)
        {
            this._client = client;
        }

        private AutomationManagementClient _client;

        /// <summary>
        /// Gets a reference to the
        /// Microsoft.Azure.Management.Automation.AutomationManagementClient.
        /// </summary>
        public AutomationManagementClient Client
        {
            get { return this._client; }
        }

        /// <summary>
        /// Retrieve the Dsc node report data by node id and report id.  (see
        /// http://aka.ms/azureautomationsdk/dscnodereportoperations for more
        /// information)
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group
        /// </param>
        /// <param name='automationAccount'>
        /// Required. The automation account name.
        /// </param>
        /// <param name='nodeId'>
        /// Required. The Dsc node id.
        /// </param>
        /// <param name='reportId'>
        /// Required. The report id.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response model for the get dsc node report operation.
        /// </returns>
        public async Task<DscNodeReportGetResponse> GetAsync(string resourceGroupName, string automationAccount, Guid nodeId, Guid reportId, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (automationAccount == null)
            {
                throw new ArgumentNullException("automationAccount");
            }

            // Tracing
            bool shouldTrace = TracingAdapter.IsEnabled;
            string invocationId = null;
            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("automationAccount", automationAccount);
                tracingParameters.Add("nodeId", nodeId);
                tracingParameters.Add("reportId", reportId);
                TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
            }

            // Construct URL
            string url = "";
            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(resourceGroupName);
            url = url + "/providers/";
            if (this.Client.ResourceNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
            }
            url = url + "/automationAccounts/";
            url = url + Uri.EscapeDataString(automationAccount);
            url = url + "/nodes/";
            url = url + Uri.EscapeDataString(nodeId.ToString());
            url = url + "/reports/";
            url = url + Uri.EscapeDataString(reportId.ToString());
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2015-01-01-preview");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;
            try
            {
                httpRequest = new HttpRequestMessage();
                httpRequest.Method = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json");
                httpRequest.Headers.Add("x-ms-version", "2014-06-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    DscNodeReportGetResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                        result = new DscNodeReportGetResponse();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            DscNodeReport nodeReportInstance = new DscNodeReport();
                            result.NodeReport = nodeReportInstance;

                            JToken endTimeValue = responseDoc["endTime"];
                            if (endTimeValue != null && endTimeValue.Type != JTokenType.Null)
                            {
                                DateTimeOffset endTimeInstance = ((DateTimeOffset)endTimeValue);
                                nodeReportInstance.EndTime = endTimeInstance;
                            }

                            JToken lastModifiedTimeValue = responseDoc["lastModifiedTime"];
                            if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
                            {
                                DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
                                nodeReportInstance.LastModifiedTime = lastModifiedTimeInstance;
                            }

                            JToken startTimeValue = responseDoc["startTime"];
                            if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
                            {
                                DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue);
                                nodeReportInstance.StartTime = startTimeInstance;
                            }

                            JToken typeValue = responseDoc["type"];
                            if (typeValue != null && typeValue.Type != JTokenType.Null)
                            {
                                string typeInstance = ((string)typeValue);
                                nodeReportInstance.Type = typeInstance;
                            }

                            JToken idValue = responseDoc["id"];
                            if (idValue != null && idValue.Type != JTokenType.Null)
                            {
                                string idInstance = ((string)idValue);
                                nodeReportInstance.Id = idInstance;
                            }

                            JToken idValue2 = responseDoc["id"];
                            if (idValue2 != null && idValue2.Type != JTokenType.Null)
                            {
                                string idInstance2 = ((string)idValue2);
                                nodeReportInstance.Id = idInstance2;
                            }

                            JToken nameValue = responseDoc["name"];
                            if (nameValue != null && nameValue.Type != JTokenType.Null)
                            {
                                string nameInstance = ((string)nameValue);
                                nodeReportInstance.Name = nameInstance;
                            }

                            JToken locationValue = responseDoc["location"];
                            if (locationValue != null && locationValue.Type != JTokenType.Null)
                            {
                                string locationInstance = ((string)locationValue);
                                nodeReportInstance.Location = locationInstance;
                            }

                            JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
                            if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
                            {
                                foreach (JProperty property in tagsSequenceElement)
                                {
                                    string tagsKey = ((string)property.Name);
                                    string tagsValue = ((string)property.Value);
                                    nodeReportInstance.Tags.Add(tagsKey, tagsValue);
                                }
                            }

                            JToken etagValue = responseDoc["etag"];
                            if (etagValue != null && etagValue.Type != JTokenType.Null)
                            {
                                string etagInstance = ((string)etagValue);
                                nodeReportInstance.Etag = etagInstance;
                            }
                        }

                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return result;
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }

        /// <summary>
        /// Retrieve the Dsc node reports by node id and report id.  (see
        /// http://aka.ms/azureautomationsdk/dscnodereportoperations for more
        /// information)
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group
        /// </param>
        /// <param name='automationAccount'>
        /// Required. The automation account name.
        /// </param>
        /// <param name='nodeId'>
        /// Required. The Dsc node id.
        /// </param>
        /// <param name='reportId'>
        /// Required. The report id.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response model for the get node report content operation.
        /// </returns>
        public async Task<DscNodeReportGetContentResponse> GetContentAsync(string resourceGroupName, string automationAccount, Guid nodeId, Guid reportId, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (automationAccount == null)
            {
                throw new ArgumentNullException("automationAccount");
            }

            // Tracing
            bool shouldTrace = TracingAdapter.IsEnabled;
            string invocationId = null;
            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("automationAccount", automationAccount);
                tracingParameters.Add("nodeId", nodeId);
                tracingParameters.Add("reportId", reportId);
                TracingAdapter.Enter(invocationId, this, "GetContentAsync", tracingParameters);
            }

            // Construct URL
            string url = "";
            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(resourceGroupName);
            url = url + "/providers/";
            if (this.Client.ResourceNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
            }
            url = url + "/automationAccounts/";
            url = url + Uri.EscapeDataString(automationAccount);
            url = url + "/nodes/";
            url = url + Uri.EscapeDataString(nodeId.ToString());
            url = url + "/reports/";
            url = url + Uri.EscapeDataString(reportId.ToString());
            url = url + "/content";
            List<string> queryParameters = new List<string>();
            queryParameters.Add("api-version=2015-01-01-preview");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;
            try
            {
                httpRequest = new HttpRequestMessage();
                httpRequest.Method = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json");
                httpRequest.Headers.Add("x-ms-version", "2014-06-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    DscNodeReportGetContentResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                        result = new DscNodeReportGetContentResponse();
                        result.Content = responseContent;

                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return result;
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }

        /// <summary>
        /// Retrieve the Dsc node report list by node id and report id.  (see
        /// http://aka.ms/azureautomationsdk/dscnodereportoperations for more
        /// information)
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the resource group
        /// </param>
        /// <param name='automationAccount'>
        /// Required. The automation account name.
        /// </param>
        /// <param name='parameters'>
        /// Optional. The parameters supplied to the list operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response model for the list dsc nodes operation.
        /// </returns>
        public async Task<DscNodeReportListResponse> ListAsync(string resourceGroupName, string automationAccount, DscNodeReportListParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (automationAccount == null)
            {
                throw new ArgumentNullException("automationAccount");
            }

            // Tracing
            bool shouldTrace = TracingAdapter.IsEnabled;
            string invocationId = null;
            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("resourceGroupName", resourceGroupName);
                tracingParameters.Add("automationAccount", automationAccount);
                tracingParameters.Add("parameters", parameters);
                TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
            }

            // Construct URL
            string url = "";
            url = url + "/subscriptions/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/resourceGroups/";
            url = url + Uri.EscapeDataString(resourceGroupName);
            url = url + "/providers/";
            if (this.Client.ResourceNamespace != null)
            {
                url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
            }
            url = url + "/automationAccounts/";
            url = url + Uri.EscapeDataString(automationAccount);
            url = url + "/nodes/";
            if (parameters != null && parameters.NodeId != null)
            {
                url = url + Uri.EscapeDataString(parameters.NodeId.ToString());
            }
            url = url + "/reports";
            List<string> queryParameters = new List<string>();
            List<string> odataFilter = new List<string>();
            if (parameters != null && parameters.StartTime != null)
            {
                odataFilter.Add("startTime ge " + Uri.EscapeDataString(parameters.StartTime));
            }
            if (parameters != null && parameters.EndTime != null)
            {
                odataFilter.Add("endTime le " + Uri.EscapeDataString(parameters.EndTime));
            }
            if (parameters != null && parameters.Type != null)
            {
                odataFilter.Add("type eq '" + Uri.EscapeDataString(parameters.Type) + "'");
            }
            if (odataFilter.Count > 0)
            {
                queryParameters.Add("$filter=" + string.Join(" and ", odataFilter));
            }
            queryParameters.Add("api-version=2015-01-01-preview");
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;
            try
            {
                httpRequest = new HttpRequestMessage();
                httpRequest.Method = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json");
                httpRequest.Headers.Add("ocp-referer", url);
                httpRequest.Headers.Add("x-ms-version", "2014-06-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    DscNodeReportListResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                        result = new DscNodeReportListResponse();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken valueArray = responseDoc["value"];
                            if (valueArray != null && valueArray.Type != JTokenType.Null)
                            {
                                foreach (JToken valueValue in ((JArray)valueArray))
                                {
                                    DscNodeReport dscNodeReportInstance = new DscNodeReport();
                                    result.NodeReports.Add(dscNodeReportInstance);

                                    JToken endTimeValue = valueValue["endTime"];
                                    if (endTimeValue != null && endTimeValue.Type != JTokenType.Null)
                                    {
                                        DateTimeOffset endTimeInstance = ((DateTimeOffset)endTimeValue);
                                        dscNodeReportInstance.EndTime = endTimeInstance;
                                    }

                                    JToken lastModifiedTimeValue = valueValue["lastModifiedTime"];
                                    if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
                                    {
                                        DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
                                        dscNodeReportInstance.LastModifiedTime = lastModifiedTimeInstance;
                                    }

                                    JToken startTimeValue = valueValue["startTime"];
                                    if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
                                    {
                                        DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue);
                                        dscNodeReportInstance.StartTime = startTimeInstance;
                                    }

                                    JToken typeValue = valueValue["type"];
                                    if (typeValue != null && typeValue.Type != JTokenType.Null)
                                    {
                                        string typeInstance = ((string)typeValue);
                                        dscNodeReportInstance.Type = typeInstance;
                                    }

                                    JToken idValue = valueValue["id"];
                                    if (idValue != null && idValue.Type != JTokenType.Null)
                                    {
                                        string idInstance = ((string)idValue);
                                        dscNodeReportInstance.Id = idInstance;
                                    }

                                    JToken idValue2 = valueValue["id"];
                                    if (idValue2 != null && idValue2.Type != JTokenType.Null)
                                    {
                                        string idInstance2 = ((string)idValue2);
                                        dscNodeReportInstance.Id = idInstance2;
                                    }

                                    JToken nameValue = valueValue["name"];
                                    if (nameValue != null && nameValue.Type != JTokenType.Null)
                                    {
                                        string nameInstance = ((string)nameValue);
                                        dscNodeReportInstance.Name = nameInstance;
                                    }

                                    JToken locationValue = valueValue["location"];
                                    if (locationValue != null && locationValue.Type != JTokenType.Null)
                                    {
                                        string locationInstance = ((string)locationValue);
                                        dscNodeReportInstance.Location = locationInstance;
                                    }

                                    JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
                                    if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
                                    {
                                        foreach (JProperty property in tagsSequenceElement)
                                        {
                                            string tagsKey = ((string)property.Name);
                                            string tagsValue = ((string)property.Value);
                                            dscNodeReportInstance.Tags.Add(tagsKey, tagsValue);
                                        }
                                    }

                                    JToken etagValue = valueValue["etag"];
                                    if (etagValue != null && etagValue.Type != JTokenType.Null)
                                    {
                                        string etagInstance = ((string)etagValue);
                                        dscNodeReportInstance.Etag = etagInstance;
                                    }
                                }
                            }

                            JToken odatanextLinkValue = responseDoc["odata.nextLink"];
                            if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
                            {
                                string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value;
                                result.SkipToken = odatanextLinkInstance;
                            }

                            JToken nextLinkValue = responseDoc["nextLink"];
                            if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
                            {
                                string nextLinkInstance = ((string)nextLinkValue);
                                result.NextLink = nextLinkInstance;
                            }
                        }

                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return result;
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }

        /// <summary>
        /// Retrieve the Dsc node report list by node id and report id.  (see
        /// http://aka.ms/azureautomationsdk/dscnodereportoperations for more
        /// information)
        /// </summary>
        /// <param name='nextLink'>
        /// Required. The link to retrieve next set of items.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response model for the list dsc nodes operation.
        /// </returns>
        public async Task<DscNodeReportListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
        {
            // Validate
            if (nextLink == null)
            {
                throw new ArgumentNullException("nextLink");
            }

            // Tracing
            bool shouldTrace = TracingAdapter.IsEnabled;
            string invocationId = null;
            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("nextLink", nextLink);
                TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
            }

            // Construct URL
            string url = "";
            url = url + nextLink;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;
            try
            {
                httpRequest = new HttpRequestMessage();
                httpRequest.Method = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json");
                httpRequest.Headers.Add("ocp-referer", url);
                httpRequest.Headers.Add("x-ms-version", "2014-06-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    DscNodeReportListResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                        result = new DscNodeReportListResponse();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken valueArray = responseDoc["value"];
                            if (valueArray != null && valueArray.Type != JTokenType.Null)
                            {
                                foreach (JToken valueValue in ((JArray)valueArray))
                                {
                                    DscNodeReport dscNodeReportInstance = new DscNodeReport();
                                    result.NodeReports.Add(dscNodeReportInstance);

                                    JToken endTimeValue = valueValue["endTime"];
                                    if (endTimeValue != null && endTimeValue.Type != JTokenType.Null)
                                    {
                                        DateTimeOffset endTimeInstance = ((DateTimeOffset)endTimeValue);
                                        dscNodeReportInstance.EndTime = endTimeInstance;
                                    }

                                    JToken lastModifiedTimeValue = valueValue["lastModifiedTime"];
                                    if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
                                    {
                                        DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
                                        dscNodeReportInstance.LastModifiedTime = lastModifiedTimeInstance;
                                    }

                                    JToken startTimeValue = valueValue["startTime"];
                                    if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
                                    {
                                        DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue);
                                        dscNodeReportInstance.StartTime = startTimeInstance;
                                    }

                                    JToken typeValue = valueValue["type"];
                                    if (typeValue != null && typeValue.Type != JTokenType.Null)
                                    {
                                        string typeInstance = ((string)typeValue);
                                        dscNodeReportInstance.Type = typeInstance;
                                    }

                                    JToken idValue = valueValue["id"];
                                    if (idValue != null && idValue.Type != JTokenType.Null)
                                    {
                                        string idInstance = ((string)idValue);
                                        dscNodeReportInstance.Id = idInstance;
                                    }

                                    JToken idValue2 = valueValue["id"];
                                    if (idValue2 != null && idValue2.Type != JTokenType.Null)
                                    {
                                        string idInstance2 = ((string)idValue2);
                                        dscNodeReportInstance.Id = idInstance2;
                                    }

                                    JToken nameValue = valueValue["name"];
                                    if (nameValue != null && nameValue.Type != JTokenType.Null)
                                    {
                                        string nameInstance = ((string)nameValue);
                                        dscNodeReportInstance.Name = nameInstance;
                                    }

                                    JToken locationValue = valueValue["location"];
                                    if (locationValue != null && locationValue.Type != JTokenType.Null)
                                    {
                                        string locationInstance = ((string)locationValue);
                                        dscNodeReportInstance.Location = locationInstance;
                                    }

                                    JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
                                    if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
                                    {
                                        foreach (JProperty property in tagsSequenceElement)
                                        {
                                            string tagsKey = ((string)property.Name);
                                            string tagsValue = ((string)property.Value);
                                            dscNodeReportInstance.Tags.Add(tagsKey, tagsValue);
                                        }
                                    }

                                    JToken etagValue = valueValue["etag"];
                                    if (etagValue != null && etagValue.Type != JTokenType.Null)
                                    {
                                        string etagInstance = ((string)etagValue);
                                        dscNodeReportInstance.Etag = etagInstance;
                                    }
                                }
                            }

                            JToken odatanextLinkValue = responseDoc["odata.nextLink"];
                            if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
                            {
                                string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value;
                                result.SkipToken = odatanextLinkInstance;
                            }

                            JToken nextLinkValue = responseDoc["nextLink"];
                            if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
                            {
                                string nextLinkInstance = ((string)nextLinkValue);
                                result.NextLink = nextLinkInstance;
                            }
                        }

                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return result;
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
    }
}


text:
package routines.system.api;

/**
 * A JOB interface for Jobs that are using tMDMTrigger Components
 */
public interface TalendMDMJob extends TalendJob {

	/**
	 * @return
	 */
	public org.dom4j.Document getMDMOutputMessage();

	/**
	 * @param message
	 */
	public void setMDMInputMessage(org.dom4j.Document message);

	/**
	 * @param message
	 * @throws DocumentException
	 */
	public void setMDMInputMessage(String message) throws org.dom4j.DocumentException;

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Paybox\Epayment\Controller\Payment;

use \Magento\Framework\Validator\Exception;

class Success extends \Paybox\Epayment\Controller\Payment
{
    public function execute()
    {
        try {
            $session = $this->getSession();
            $paybox = $this->getPaybox();

            // Retrieves params
            $params = $paybox->getParams(false, false);
            if ($params === false) {
                return $this->_404();
            }

            // Load order
            $order = $this->_getOrderFromParams($params);
            if (is_null($order) || is_null($order->getId())) {
                return $this->_404();
            }

            // Payment method
            $order->getPayment()->getMethodInstance()->onPaymentSuccess($order, $params);

            // Cleanup
            $session->unsCurrentPbxepOrderId();

            $message = sprintf('Order %s: Customer is back from Verifone e-commerce payment page. Payment success.', $order->getIncrementId());
            $this->logDebug($message);

            // Redirect to success page
            $this->_redirectResponse($order, true /* is success ? */, true /* notification url warn in TEST mode */);
            return;
        } catch (\Exception $e) {
            $this->logDebug(sprintf('successAction: %s', $e->getMessage()));
        }

        $this->_redirect('checkout/cart');
    }
}


text:
package com.intellij.codeInsight.daemon.impl.analysis;

import com.intellij.codeInsight.daemon.JavaErrorBundle;
import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.codeInsight.daemon.impl.HighlightInfoType;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.NlsContexts;
import com.intellij.psi.*;
import com.intellij.psi.util.MethodSignature;
import com.intellij.psi.util.PsiTypesUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.TypeConversionUtil;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public final class LambdaHighlightingUtil {
  private static final Logger LOG = Logger.getInstance(LambdaHighlightingUtil.class);

  public static @NlsContexts.DetailedDescription String checkInterfaceFunctional(@NotNull PsiClass psiClass) {
    return checkInterfaceFunctional(psiClass, JavaErrorBundle.message("target.type.of.a.lambda.conversion.must.be.an.interface"));
  }

  static @NlsContexts.DetailedDescription String checkInterfaceFunctional(@NotNull PsiClass psiClass, @NotNull @Nls String interfaceNonFunctionalMessage) {
    if (psiClass instanceof PsiTypeParameter) return null; //should be logged as cyclic inference
    List<HierarchicalMethodSignature> signatures = LambdaUtil.findFunctionCandidates(psiClass);
    if (signatures == null) return interfaceNonFunctionalMessage;
    if (signatures.isEmpty()) return JavaErrorBundle.message("no.target.method.found");
    if (signatures.size() == 1) {
      return null;
    }
    return JavaErrorBundle.message("multiple.non.overriding.abstract.methods.found.in.interface.0", HighlightUtil.formatClass(psiClass));
  }

  static HighlightInfo checkParametersCompatible(@NotNull PsiLambdaExpression expression,
                                                 PsiParameter @NotNull [] methodParameters,
                                                 @NotNull PsiSubstitutor substitutor) {
    PsiParameter[] lambdaParameters = expression.getParameterList().getParameters();
    if (lambdaParameters.length != methodParameters.length) {
      return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR)
        .range(expression.getParameterList())
        .descriptionAndTooltip(JavaErrorBundle.message("incompatible.parameter.types.in.lambda.wrong.number.of.parameters", methodParameters.length, lambdaParameters.length))
        .create();
    }
    boolean hasFormalParameterTypes = expression.hasFormalParameterTypes();
    for (int i = 0; i < lambdaParameters.length; i++) {
      PsiParameter lambdaParameter = lambdaParameters[i];
      PsiType lambdaParameterType = lambdaParameter.getType();
      PsiType substitutedParamType = substitutor.substitute(methodParameters[i].getType());
      if (hasFormalParameterTypes &&!PsiTypesUtil.compareTypes(lambdaParameterType, substitutedParamType, true) ||
          !TypeConversionUtil.isAssignable(substitutedParamType, lambdaParameterType)) {
        String expectedType = substitutedParamType != null ? substitutedParamType.getPresentableText() : null;
        String actualType = lambdaParameterType.getPresentableText();
        return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR)
          .range(expression.getParameterList())
          .descriptionAndTooltip(
            JavaErrorBundle.message("incompatible.parameter.types.in.lambda", expectedType, actualType))
          .create();
      }
    }
    return null;
  }

  public static boolean insertSemicolonAfter(@NotNull PsiLambdaExpression lambdaExpression) {
    return lambdaExpression.getBody() instanceof PsiCodeBlock || insertSemicolon(lambdaExpression.getParent());
  }

  public static boolean insertSemicolon(PsiElement parent) {
    return !(parent instanceof PsiExpressionList) && !(parent instanceof PsiExpression);
  }

  public static @NlsContexts.DetailedDescription String checkInterfaceFunctional(@NotNull PsiType functionalInterfaceType) {
    if (functionalInterfaceType instanceof PsiIntersectionType) {
      Set<MethodSignature> signatures = new HashSet<>();
      for (PsiType type : ((PsiIntersectionType)functionalInterfaceType).getConjuncts()) {
        if (checkInterfaceFunctional(type) == null) {
          MethodSignature signature = LambdaUtil.getFunction(PsiUtil.resolveClassInType(type));
          LOG.assertTrue(signature != null, type.getCanonicalText());
          signatures.add(signature);
        }
      }

      if (signatures.size() > 1) {
        return JavaErrorBundle.message("multiple.non.overriding.abstract.methods.found.in.0", functionalInterfaceType.getPresentableText());
      }
      return null;
    }
    PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(functionalInterfaceType);
    PsiClass aClass = resolveResult.getElement();
    if (aClass != null) {
      if (aClass instanceof PsiTypeParameter) return null; //should be logged as cyclic inference
      MethodSignature functionalMethod = LambdaUtil.getFunction(aClass);
      if (functionalMethod != null && functionalMethod.getTypeParameters().length > 0) return JavaErrorBundle
        .message("target.method.is.generic");
      return checkInterfaceFunctional(aClass);
    }
    return JavaErrorBundle.message("not.a.functional.interface",functionalInterfaceType.getPresentableText());
  }

  static HighlightInfo checkConsistentParameterDeclaration(@NotNull PsiLambdaExpression expression) {
    PsiParameter[] parameters = expression.getParameterList().getParameters();
    if (parameters.length < 2) return null;
    boolean hasExplicitParameterTypes = hasExplicitType(parameters[0]);
    for (int i = 1; i < parameters.length; i++) {
      if (hasExplicitParameterTypes != hasExplicitType(parameters[i])) {
        return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR)
                            .descriptionAndTooltip(JavaErrorBundle.message("lambda.parameters.consistency.message"))
                            .range(expression.getParameterList())
                            .create();
      }
    }

    return null;
  }

  private static boolean hasExplicitType(@NotNull PsiParameter parameter) {
    PsiTypeElement typeElement = parameter.getTypeElement();
    return typeElement != null && !typeElement.isInferredType();
  }
}


text:
Answers

				Posted on

				by

    	No Answers yet, why don't you create one?


text:
namespace celestial {
Snapshot::Snapshot() {
    filepath_ = Configure::instance().get_snapshot_dir() + "/" + Configure::instance().get_snapshot_name();
    snapshot_max_block_size_ = Configure::instance().get_snapshot_max_block_size();
}

void Snapshot::serializeSnapshot(std::shared_ptr<StateMachine> state_machine) {
    std::string filepath = filepath_ + "_" + std::tostring(last_index_) + "_" + std::tostring(last_term_);
    std::string tmp_filepath = filepath + ".tmp"
    std::fstream fs(tmp_filepath, std::fstream::out | std::fstream::binary | std::fstream::trunc);
    state_machine->writeToStream(fs);
    fs.close();
    boost::filesystem::rename(tmp_filepath, filepath);
}
std::shared_ptr<StateMachine> Snapshot::deserializeSnapshot() {
    std::string filepath = filepath_ + "_" + std::tostring(last_index_) + "_" + std::tostring(last_term_);
    std::fstream fs(filepath, std::fstream::in | std::fstream::binary);
    std::shared_ptr<StateMachine> state_machine = make_shared<StateMachine>();
    state_machine->readFromStream(fs);
    fs.close();
    return state_machine;
}
int64_t Snapshot::getLastIncludedIndex() {
    return last_index_;
}
void Snapshot::setLastIncludedIndex(int64_t last_index) {
    last_index_ = last_index;
}
int64_t Snapshot::getLastIncludedTerm() {
    return last_term_;
}
void Snapshot::setLastIncludedTerm(int64_t last_term) {
    last_term_ = last_term;
}
std::string Snapshot::readDataFromOffset(int64_t offset) {
    std::string filepath = filepath_ + "_" + std::tostring(last_index_) + "_" + std::tostring(last_term_);
    std::fstream fs(filepath, std::fstream::in | std::fstream::binary);
    fs.seekg(offset, std::ios::beg);
    char* tmp = new char[snapshot_max_block_size_];
    fs.read(tmp, snapshot_max_block_size_);
    uint32_t size = fs.gcount();
    string res(tmp, size);
    delete tmp;
    return res;
}
void Snapshot::writeDataFromOffset(const std::string& data, int64_t offset) {
    std::string filepath = filepath_ + "_" + std::tostring(last_index_) + "_" + std::tostring(last_term_);
    if (boost::filesystem::exists(filepath)) {
        try {
            boost::filesystem::resize_file(filepath, offset);
        } catch (std::exception &e) {
            throw SnapshotException(string("truncate fail, error:") + e.what());
        }
    }
    std::fstream fs(filepath, std::fstream::out | std::fstream::binary);
    fs.seekp(offset, std::ios::beg);
    fs.write(data.c_str(), data.size());
}
uint32_t Snapshot::getFileSize() {
    return boost::filesystem::file_size(filepath_);
}
}


text:
package config

import (
	"context"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"strings"

	"github.com/GoogleCloudPlatform/osconfig/clog"
	"github.com/GoogleCloudPlatform/osconfig/util"

	agentendpointpb "google.golang.org/genproto/googleapis/cloud/osconfig/agentendpoint/v1"
)

const maxExecOutputSize = 100 * 1024

var runner = util.CommandRunner(&util.DefaultRunner{})

type execResource struct {
	*agentendpointpb.OSPolicy_Resource_ExecResource

	validatePath, enforcePath, tempDir string
	enforceOutput                      []byte
}

// TODO: use a persistent cache for downloaded files so we dont need to redownload them each time
func (e *execResource) download(ctx context.Context, execR *agentendpointpb.OSPolicy_Resource_ExecResource_Exec) (string, error) {
	tmpDir, err := ioutil.TempDir(e.tempDir, "")
	if err != nil {
		return "", fmt.Errorf("failed to create temp dir: %s", err)
	}

	// File extensions are important on Windows.
	var name string
	perms := os.FileMode(0644)
	switch execR.GetSource().(type) {
	case *agentendpointpb.OSPolicy_Resource_ExecResource_Exec_Script:
		switch execR.GetInterpreter() {
		case agentendpointpb.OSPolicy_Resource_ExecResource_Exec_NONE:
			if goos == "windows" {
				name = "script.cmd"
			} else {
				name = "script"
			}
			perms = os.FileMode(0755)
		case agentendpointpb.OSPolicy_Resource_ExecResource_Exec_SHELL:
			if goos == "windows" {
				name = "script.cmd"
			} else {
				name = "script.sh"
			}
		case agentendpointpb.OSPolicy_Resource_ExecResource_Exec_POWERSHELL:
			name = "script.ps1"
		default:
			return "", fmt.Errorf("unsupported interpreter %q", execR.GetInterpreter())
		}
		name = filepath.Join(tmpDir, name)
		if _, err := util.AtomicWriteFileStream(strings.NewReader(execR.GetScript()), "", name, perms); err != nil {
			return "", err
		}

	case *agentendpointpb.OSPolicy_Resource_ExecResource_Exec_File:
		if execR.GetFile().GetLocalPath() != "" {
			return execR.GetFile().GetLocalPath(), nil
		}
		switch {
		case execR.GetFile().GetGcs().GetObject() != "":
			name = path.Base(execR.GetFile().GetGcs().GetObject())
		case execR.GetFile().GetRemote().GetUri() != "":
			name = path.Base(execR.GetFile().GetRemote().GetUri())
		default:
			return "", fmt.Errorf("unsupported File %v", execR.GetFile())
		}
		if execR.GetInterpreter() == agentendpointpb.OSPolicy_Resource_ExecResource_Exec_NONE {
			perms = os.FileMode(0755)
		}
		name = filepath.Join(tmpDir, name)
		if _, err := downloadFile(ctx, name, perms, execR.GetFile()); err != nil {
			return "", err
		}
	default:
		return "", fmt.Errorf("unrecognized Source type for ExecResource: %q", execR.GetSource())
	}

	return name, nil
}

func (e *execResource) validate(ctx context.Context) (*ManagedResources, error) {
	tmpDir, err := ioutil.TempDir("", "osconfig_exec_resource_")
	if err != nil {
		return nil, fmt.Errorf("failed to create temp dir: %s", err)
	}
	e.tempDir = tmpDir

	e.validatePath, err = e.download(ctx, e.GetValidate())
	if err != nil {
		return nil, err
	}

	// Assume lack of Enforce means policy is in VALIDATE mode.
	if e.GetEnforce() != nil {
		e.enforcePath, err = e.download(ctx, e.GetEnforce())
		if err != nil {
			return nil, err
		}
	}

	return nil, nil
}

func (e *execResource) run(ctx context.Context, name string, execR *agentendpointpb.OSPolicy_Resource_ExecResource_Exec) ([]byte, []byte, int, error) {
	if execR == nil {
		return nil, nil, 0, fmt.Errorf("ExecResource Exec cannot be nil")
	}

	var cmd string
	var args []string
	switch execR.GetInterpreter() {
	case agentendpointpb.OSPolicy_Resource_ExecResource_Exec_NONE:
		cmd = name
	case agentendpointpb.OSPolicy_Resource_ExecResource_Exec_SHELL:
		if goos == "windows" {
			cmd = name
		} else {
			args = append([]string{name})
			cmd = "/bin/sh"
		}
	case agentendpointpb.OSPolicy_Resource_ExecResource_Exec_POWERSHELL:
		if goos != "windows" {
			return nil, nil, 0, fmt.Errorf("interpreter %q can only be used on Windows systems", execR.GetInterpreter())
		}
		args = append([]string{"-File", name})
		cmd = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\PowerShell.exe"
	default:
		return nil, nil, 0, fmt.Errorf("unsupported interpreter %q", execR.GetInterpreter())
	}
	args = append(args, execR.GetArgs()...)

	stdout, stderr, err := runner.Run(ctx, exec.CommandContext(ctx, cmd, args...))
	code := 0
	if err != nil {
		code = -1
		if v, ok := err.(*exec.ExitError); ok {
			code = v.ExitCode()
		}
	}
	return stdout, stderr, code, err
}

func (e *execResource) checkState(ctx context.Context) (inDesiredState bool, err error) {
	// For validate we expect an exit code of 100 for "correct state" and 101 for "incorrect state".
	// 100 was chosen over 0 (and 101 vs 1) because we want an explicit indicator of
	// "correct" vs "incorrect" state and errors. Also Powershell will always exit 0 unless "exit"
	// is explicitly called.
	// A code of -1 indicates some other error, so we just return err.
	stdout, stderr, code, err := e.run(ctx, e.validatePath, e.GetValidate())
	switch code {
	case -1:
		return false, err
	case 100:
		return true, nil
	case 101:
		return false, nil
	default:
		return false, fmt.Errorf("unexpected return code from validate: %d, stdout: %s, stderr: %s", code, stdout, stderr)
	}
}

func (e *execResource) enforceState(ctx context.Context) (inDesiredState bool, err error) {
	clog.Infof(ctx, `Running "Enforce" for ExecResource.`)
	// For enforce we expect an exit code of 100 for "success" and anything positive code is a failure".
	// 100 was chosen over 0 because we want an explicit indicator of "sucess" vs errors.
	// Also Powershell will always exit 0 unless "exit" is explicitly called.
	// A code of -1 indicates some other error, so we just return err.
	stdout, stderr, code, err := e.run(ctx, e.enforcePath, e.GetEnforce())
	switch code {
	case -1:
		return false, err
	case 100:
		out, err := execOutput(ctx, e.GetEnforce().GetOutputFilePath())
		e.enforceOutput = out
		return true, err
	default:
		return false, fmt.Errorf("unexpected return code from enforce: %d, stdout: %s, stderr: %s", code, stdout, stderr)
	}
}

func execOutput(ctx context.Context, outputFilePath string) ([]byte, error) {
	if outputFilePath == "" {
		return nil, nil
	}

	clog.Debugf(ctx, "Reading %q for ExecResource output", outputFilePath)

	f, err := os.Open(outputFilePath)
	if err != nil {
		return nil, fmt.Errorf("error opening OutputFilePath: %v", err)
	}
	defer f.Close()

	// Make a byte slice with a capacity of 1 over maxSize (for checking maxExecOutputSize).
	output := make([]byte, 0, maxExecOutputSize+1)
	// Read up to capactity.
	n, err := f.Read(output[:cap(output)])
	output = output[:len(output)+n]
	if err != nil && err != io.EOF {
		return output, fmt.Errorf("error reading from OutputFilePath: %v", err)
	}
	// Return the output up to this point and an error if total size is greater than maxExecOutputSize.
	if n > maxExecOutputSize {
		return output[:maxExecOutputSize], fmt.Errorf("contents of OutputFilePath greater than %dK", maxExecOutputSize/1024)
	}
	return output, nil
}

func (e *execResource) populateOutput(rCompliance *agentendpointpb.OSPolicyResourceCompliance) {
	if e.enforceOutput != nil {
		rCompliance.Output = &agentendpointpb.OSPolicyResourceCompliance_ExecResourceOutput_{
			ExecResourceOutput: &agentendpointpb.OSPolicyResourceCompliance_ExecResourceOutput{
				EnforcementOutput: e.enforceOutput,
			},
		}
	}
}

func (e *execResource) cleanup(ctx context.Context) error {
	if e.tempDir != "" {
		return os.RemoveAll(e.tempDir)
	}
	return nil
}


text:
"""Builds all assets under samples/rawassets/, writing the results to assets/.

Finds the flatbuffer compiler then uses it to convert the JSON files to
flatbuffer binary files.  If you would like to clean all generated files, you
can call this script with the argument 'clean'.
"""

import argparse
import distutils.spawn
import glob
import os
import platform
import shutil
import subprocess
import sys

# The project root directory, which is one level up from this script's
# directory.
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__),
                                            os.path.pardir))

# Directories that may contains the FlatBuffers compiler.
FLATBUFFERS_PATHS = [
    os.path.join(PROJECT_ROOT, 'bin'),
    os.path.join(PROJECT_ROOT, 'bin', 'Release'),
    os.path.join(PROJECT_ROOT, 'bin', 'Debug')
    ]

# Directory to place processed assets.
ASSETS_PATH = os.path.join(PROJECT_ROOT, 'assets')

# Directory where unprocessed assets can be found.
RAW_ASSETS_PATH = os.path.join(PROJECT_ROOT, 'samples', 'rawassets')

# Directory where unprocessed sound flatbuffer data can be found.
RAW_SOUND_PATH = os.path.join(RAW_ASSETS_PATH, 'sounds')

# Directory where unprocessed sound flatbuffer data can be found.
RAW_SOUND_BANK_PATH = os.path.join(RAW_ASSETS_PATH, 'sound_banks')

# Directory where unprocessed assets can be found.
SCHEMA_PATHS = [ os.path.join(PROJECT_ROOT, 'schemas') ]

# Windows uses the .exe extension on executables.
EXECUTABLE_EXTENSION = '.exe' if platform.system() == 'Windows' else ''

# Name of the flatbuffer executable.
FLATC_EXECUTABLE_NAME = 'flatc' + EXECUTABLE_EXTENSION

class FlatbuffersConversionData(object):
  """Holds data needed to convert a set of json files to flatbuffer binaries.

  Attributes:
    schema: The path to the flatbuffer schema file.
    input_files: A list of input files to convert.
  """

  def __init__(self, schema, input_files):
    """Initializes this object's schema and input_files."""
    self.schema = schema
    self.input_files = input_files

def find_in_paths(name, paths):
  """Searches for a file with named `name` in the given paths and returns it."""
  for path in paths:
    full_path = os.path.join(path, name)
    if os.path.isfile(full_path):
      return full_path
  # If not found, just assume it's in the PATH.
  return name

# A list of json files and their schemas that will be converted to binary files
# by the flatbuffer compiler.
FLATBUFFERS_CONVERSION_DATA = [
    FlatbuffersConversionData(
        schema=find_in_paths('audio_config.fbs', SCHEMA_PATHS),
        input_files=[os.path.join(RAW_ASSETS_PATH, 'audio_config.json')]),
    FlatbuffersConversionData(
        schema=find_in_paths('buses.fbs', SCHEMA_PATHS),
        input_files=[os.path.join(RAW_ASSETS_PATH, 'buses.json')]),
    FlatbuffersConversionData(
        schema=find_in_paths('sound_bank_def.fbs', SCHEMA_PATHS),
        input_files=glob.glob(os.path.join(RAW_SOUND_BANK_PATH, '*.json'))),
    FlatbuffersConversionData(
        schema=find_in_paths('sound_collection_def.fbs', SCHEMA_PATHS),
        input_files=glob.glob(os.path.join(RAW_SOUND_PATH, '*.json')))
    ]

# Location of FlatBuffers compiler.
FLATC = find_in_paths(FLATC_EXECUTABLE_NAME, FLATBUFFERS_PATHS)

class BuildError(Exception):
  """Error indicating there was a problem building assets."""

  def __init__(self, argv, error_code, message=None):
    Exception.__init__(self)
    self.argv = argv
    self.error_code = error_code
    self.message = message if message else ''

def run_subprocess(argv):
  try:
    process = subprocess.Popen(argv)
  except OSError as e:
    raise BuildError(argv, 1, message=str(e))
  process.wait()
  if process.returncode:
    raise BuildError(argv, process.returncode)

def convert_json_to_flatbuffer_binary(flatc, json, schema, out_dir):
  """Run the flatbuffer compiler on the given json file and schema.

  Args:
    flatc: Path to the flatc binary.
    json: The path to the json file to convert to a flatbuffer binary.
    schema: The path to the schema to use in the conversion process.
    out_dir: The directory to write the flatbuffer binary.

  Raises:
    BuildError: Process return code was nonzero.
  """
  command = [flatc, '-o', out_dir]
  for path in SCHEMA_PATHS:
    command.extend(['-I', path])
  command.extend(['-b', schema, json])
  run_subprocess(command)

def needs_rebuild(source, target):
  """Checks if the source file needs to be rebuilt.

  Args:
    source: The source file to be compared.
    target: The target file which we may need to rebuild.

  Returns:
    True if the source file is newer than the target, or if the target file
    does not exist.
  """
  return not os.path.isfile(target) or (
      os.path.getmtime(source) > os.path.getmtime(target))

def processed_json_path(path, target_directory):
  """Take the path to a raw json asset and convert it to target bin path.

  Args:
    target_directory: Path to the target assets directory.
  """
  return path.replace(RAW_ASSETS_PATH, target_directory).replace(
      '.json', '.bin')

def generate_flatbuffer_binaries(flatc, target_directory):
  """Run the flatbuffer compiler on the all of the flatbuffer json files.

  Args:
    flatc: Path to the flatc binary.
    target_directory: Path to the target assets directory.
  """
  for element in FLATBUFFERS_CONVERSION_DATA:
    schema = element.schema
    for json in element.input_files:
      target = processed_json_path(json, target_directory)
      target_file_dir = os.path.dirname(target)
      if not os.path.exists(target_file_dir):
        os.makedirs(target_file_dir)
      if needs_rebuild(json, target) or needs_rebuild(schema, target):
        convert_json_to_flatbuffer_binary(flatc, json, schema, target_file_dir)

def copy_assets(target_directory):
  """Copy modified assets to the target assets directory.

  All files are copied from ASSETS_PATH to the specified target_directory if
  they're newer than the destination files.

  Args:
    target_directory: Directory to copy assets to.
  """
  assets_dir = target_directory
  source_dir = os.path.realpath(ASSETS_PATH)
  if source_dir != os.path.realpath(assets_dir):
    for dirpath, _, files in os.walk(source_dir):
      for name in files:
        source_filename = os.path.join(dirpath, name)
        relative_source_dir = os.path.relpath(source_filename, source_dir)
        target_dir = os.path.dirname(os.path.join(assets_dir,
                                                  relative_source_dir))
        target_filename = os.path.join(target_dir, name)
        if not os.path.exists(target_dir):
          os.makedirs(target_dir)
        if (not os.path.exists(target_filename) or
            (os.path.getmtime(target_filename) <
             os.path.getmtime(source_filename))):
              shutil.copy2(source_filename, target_filename)

def clean_flatbuffer_binaries(target_directory):
  """Delete all the processed flatbuffer binaries.

  Args:
    target_directory: Path to the target assets directory.
  """
  for element in FLATBUFFERS_CONVERSION_DATA:
    for json in element.input_files:
      path = processed_json_path(json, target_directory)
      if os.path.isfile(path):
        os.remove(path)

def clean():
  """Delete all the processed files."""
  clean_flatbuffer_binaries()

def handle_build_error(error):
  """Prints an error message to stderr for BuildErrors."""
  sys.stderr.write('Error running command `%s`. Returned %s.\n%s\n' % (
      ' '.join(error.argv), str(error.error_code), str(error.message)))

def main(argv):
  """Builds or cleans the assets needed for the game.

  This script will build all the assets in samples/rawassets.  To clean all
  converted files, call it with 'clean'.

  Returns:
    Returns 0 on success.
  """
  parser = argparse.ArgumentParser()
  parser.add_argument('--flatc', default=FLATC,
                      help='Location of the flatbuffers compiler.')
  parser.add_argument('--output', default=ASSETS_PATH,
                      help='Assets output directory.')
  parser.add_argument('args', nargs=argparse.REMAINDER)
  args = parser.parse_args()
  target = args.args[1] if len(args.args) >= 2 else 'all'
  if target != 'clean':
    copy_assets(args.output)
    try:
      generate_flatbuffer_binaries(args.flatc, args.output)
    except BuildError as error:
      handle_build_error(error)
      return 1
  else:
    try:
      clean()
    except OSError as error:
      sys.stderr.write('Error cleaning: %s' % str(error))
      return 1
  return 0

if __name__ == '__main__':
  sys.exit(main(sys.argv))


text:
/**
 *
 */
package com.impetus.client.crud.compositeType.association;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import org.apache.cassandra.thrift.CfDef;
import org.apache.cassandra.thrift.ColumnDef;
import org.apache.cassandra.thrift.IndexType;
import org.apache.cassandra.thrift.InvalidRequestException;
import org.apache.cassandra.thrift.KsDef;
import org.apache.cassandra.thrift.NotFoundException;
import org.apache.cassandra.thrift.SchemaDisagreementException;
import org.apache.thrift.TException;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import com.impetus.kundera.client.cassandra.persistence.CassandraCli;

/**
 * @author impadmin
 *
 */
public class CassandraUserOTMTest
{

    private static final String _KEYSPACE = "KunderaExamples";

    private EntityManagerFactory emf;

    private EntityManager em;

    /**
     * @throws java.lang.Exception
     */
    @Before
    public void setUp() throws Exception
    {
        CassandraCli.cassandraSetUp();
        CassandraCli.createKeySpace(_KEYSPACE);
        loadData();
        // HashMap propertyMap = new HashMap();
        // propertyMap.put(CassandraConstants.CQL_VERSION,
        // CassandraConstants.CQL_VERSION_3_0);
        // propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE,
        // "create");
        emf = Persistence.createEntityManagerFactory("secIdxCassandraTest");
    }

    /**
     * @throws java.lang.Exception
     */
    @After
    public void tearDown() throws Exception
    {
        CassandraCli.dropKeySpace(_KEYSPACE);
        emf.close();
    }

    @Test
    public void test()
    {
        em = emf.createEntityManager();

        Set<CassandraAddressUniOTM> addresses = new HashSet<CassandraAddressUniOTM>();

        CassandraAddressUniOTM address1 = new CassandraAddressUniOTM();
        address1.setAddressId("a");
        address1.setStreet("my street");
        CassandraAddressUniOTM address2 = new CassandraAddressUniOTM();
        address2.setAddressId("b");
        address2.setStreet("my new street");

        addresses.add(address1);
        addresses.add(address2);

        CassandraUserUniOTM userUniOTM = new CassandraUserUniOTM();
        userUniOTM.setPersonId("1");
        userUniOTM.setPersonName("kuldeep");
        userUniOTM.setAddresses(addresses);

        em.persist(userUniOTM);

        em.clear();

        CassandraUserUniOTM foundObject = em.find(CassandraUserUniOTM.class, "1");
        Assert.assertNotNull(foundObject);
        Assert.assertEquals(2, foundObject.getAddresses().size());

        Query q = em.createQuery("Select u from CassandraUserUniOTM u");
        List<CassandraUserUniOTM> users = q.getResultList();
        Assert.assertNotNull(users);
        Assert.assertEquals(1, users.size());
        Assert.assertNotNull(users.get(0));
        Assert.assertEquals("kuldeep", users.get(0).getPersonName());
        Assert.assertEquals("1", users.get(0).getPersonId());
        Assert.assertNotNull(users.get(0).getAddresses());
        Assert.assertEquals(2, users.get(0).getAddresses().size());

        em.remove(foundObject);

        foundObject = em.find(CassandraUserUniOTM.class, "1");
        Assert.assertNull(foundObject);
    }

    /**
     * Loads data.
     *
     * @throws InvalidRequestException
     * @throws SchemaDisagreementException
     * @throws TException
     */
    private void loadData() throws InvalidRequestException, SchemaDisagreementException, TException
    {
        List<CfDef> cfDefs = new ArrayList<CfDef>();

        CfDef user = new CfDef(_KEYSPACE, "CassandraUserUniOTM");
        user.setKey_validation_class("UTF8Type");
        user.setDefault_validation_class("UTF8Type");
        user.setComparator_type("UTF8Type");
        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap("PERSON_NAME".getBytes()), "UTF8Type");
        columnDef.index_type = IndexType.KEYS;
        user.addToColumn_metadata(columnDef);

        CfDef address = new CfDef(_KEYSPACE, "CassandraAddressUniOTM");
        address.setKey_validation_class("UTF8Type");
        address.setDefault_validation_class("UTF8Type");
        address.setComparator_type("UTF8Type");
        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap("PERSON_ID".getBytes()), "UTF8Type");
        columnDef1.index_type = IndexType.KEYS;
        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap("STREET".getBytes()), "UTF8Type");
        columnDef2.index_type = IndexType.KEYS;

        address.addToColumn_metadata(columnDef1);
        address.addToColumn_metadata(columnDef2);

        cfDefs.add(user);
        cfDefs.add(address);
        KsDef ksDef = null;
        try
        {
            CassandraCli.initClient();
            ksDef = CassandraCli.client.describe_keyspace(_KEYSPACE);
            CassandraCli.client.set_keyspace(_KEYSPACE);

            List<CfDef> cfDefn = ksDef.getCf_defs();

            for (CfDef cfDef1 : cfDefn)
            {
                if (cfDef1.getName().equals("CassandraUserUniOTM"))
                {
                    CassandraCli.client.system_drop_column_family("CassandraUserUniOTM");
                }
                if (cfDef1.getName().equals("CassandraAddressUniOTM"))
                {
                    CassandraCli.client.system_drop_column_family("CassandraAddressUniOTM");
                }
            }
            CassandraCli.client.system_add_column_family(user);
            CassandraCli.client.system_add_column_family(address);
        }
        catch (NotFoundException e)
        {

            ksDef = new org.apache.cassandra.thrift.KsDef(_KEYSPACE, "org.apache.cassandra.locator.SimpleStrategy",
                    cfDefs);

            if (ksDef.strategy_options == null)
            {
                ksDef.strategy_options = new LinkedHashMap<String, String>();
            }
            ksDef.strategy_options.put("replication_factor", "1");
            CassandraCli.client.system_add_keyspace(ksDef);

            CassandraCli.client.set_keyspace(_KEYSPACE);
        }
        catch (TException e)
        {

        }
    }
}


text:
package org.xtreemfs.pbrpc.generatedinterfaces;

import com.google.protobuf.Message;

public class DIRServiceConstants {

    public static final int INTERFACE_ID = 10001;
    public static final int PROC_ID_XTREEMFS_ADDRESS_MAPPINGS_GET = 1;
    public static final int PROC_ID_XTREEMFS_ADDRESS_MAPPINGS_REMOVE = 2;
    public static final int PROC_ID_XTREEMFS_ADDRESS_MAPPINGS_SET = 3;
    public static final int PROC_ID_XTREEMFS_DISCOVER_DIR = 4;
    public static final int PROC_ID_XTREEMFS_GLOBAL_TIME_S_GET = 5;
    public static final int PROC_ID_XTREEMFS_SERVICE_DEREGISTER = 6;
    public static final int PROC_ID_XTREEMFS_SERVICE_GET_BY_NAME = 7;
    public static final int PROC_ID_XTREEMFS_SERVICE_GET_BY_TYPE = 8;
    public static final int PROC_ID_XTREEMFS_SERVICE_GET_BY_UUID = 9;
    public static final int PROC_ID_XTREEMFS_SERVICE_OFFLINE = 10;
    public static final int PROC_ID_XTREEMFS_SERVICE_REGISTER = 11;
    public static final int PROC_ID_XTREEMFS_CHECKPOINT = 20;
    public static final int PROC_ID_XTREEMFS_SHUTDOWN = 21;
    public static final int PROC_ID_XTREEMFS_CONFIGURATION_GET = 22;
    public static final int PROC_ID_XTREEMFS_CONFIGURATION_SET = 23;
    public static final int PROC_ID_XTREEMFS_VIVALDI_CLIENT_UPDATE = 24;

    public static Message getRequestMessage(int procId) {
        switch (procId) {
           case 1: return DIR.addressMappingGetRequest.getDefaultInstance();
           case 2: return DIR.addressMappingGetRequest.getDefaultInstance();
           case 3: return DIR.AddressMappingSet.getDefaultInstance();
           case 4: return null;
           case 5: return null;
           case 6: return DIR.serviceDeregisterRequest.getDefaultInstance();
           case 7: return DIR.serviceGetByNameRequest.getDefaultInstance();
           case 8: return DIR.serviceGetByTypeRequest.getDefaultInstance();
           case 9: return DIR.serviceGetByUUIDRequest.getDefaultInstance();
           case 10: return DIR.serviceGetByUUIDRequest.getDefaultInstance();
           case 11: return DIR.serviceRegisterRequest.getDefaultInstance();
           case 20: return null;
           case 21: return null;
           case 22: return DIR.configurationGetRequest.getDefaultInstance();
           case 23: return DIR.Configuration.getDefaultInstance();
           case 24: return GlobalTypes.VivaldiCoordinates.getDefaultInstance();
           default: throw new RuntimeException("unknown procedure id");
        }
    }

    public static Message getResponseMessage(int procId) {
        switch (procId) {
           case 1: return DIR.AddressMappingSet.getDefaultInstance();
           case 2: return null;
           case 3: return DIR.addressMappingSetResponse.getDefaultInstance();
           case 4: return DIR.DirService.getDefaultInstance();
           case 5: return DIR.globalTimeSGetResponse.getDefaultInstance();
           case 6: return null;
           case 7: return DIR.ServiceSet.getDefaultInstance();
           case 8: return DIR.ServiceSet.getDefaultInstance();
           case 9: return DIR.ServiceSet.getDefaultInstance();
           case 10: return null;
           case 11: return DIR.serviceRegisterResponse.getDefaultInstance();
           case 20: return null;
           case 21: return null;
           case 22: return DIR.Configuration.getDefaultInstance();
           case 23: return DIR.configurationSetResponse.getDefaultInstance();
           case 24: return null;
           default: throw new RuntimeException("unknown procedure id");
        }
    }

}


text:
import os
import warnings

warnings.simplefilter('always')

PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(PROJECT_ROOT, 'db.sqlite'),
    }
}

SITE_ID = 1

# Set in order to catch timezone aware vs unaware comparisons
USE_TZ = True

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
USE_L10N = True

# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = '/media/'

# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/admin/'

# Make this unique, and don't share it with anybody.
SECRET_KEY = '0'

ROOT_URLCONF = 'django_mobile_tests.urls'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    ('django_mobile.loader.CachedLoader', (
        'django_mobile.loader.Loader',
        'django.template.loaders.filesystem.Loader',
        'django.template.loaders.app_directories.Loader',
    )),
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django_mobile.middleware.MobileDetectionMiddleware',
    'django_mobile.middleware.SetFlavourMiddleware',
)

TEMPLATE_DIRS = (
    os.path.join(PROJECT_ROOT, 'templates'),
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.admin',

    'django_mobile',
    'django_mobile_tests',
)

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django_mobile.context_processors.flavour",
    "django_mobile.context_processors.is_mobile",
)

import django
if django.VERSION < (1, 6):
    TEST_RUNNER = 'discover_runner.DiscoverRunner'
else:
    TEST_RUNNER = 'django.test.runner.DiscoverRunner'