text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

namespace Networks.Tests
{
    using System;
    using System.Collections.Generic;
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    using Microsoft.Azure.Management.Network;
    using Microsoft.Azure.Management.Network.Models;
    using Microsoft.Azure.Management.Resources;
    using Microsoft.Azure.Management.Resources.Models;
    using Microsoft.Azure.Test;
    using Networks.Tests.Helpers;
    using ResourceGroups.Tests;
    using Xunit;

    using Microsoft.Azure.Test.HttpRecorder;
    using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
    using SubResource = Microsoft.Azure.Management.Network.Models.SubResource;

    public class ApplicationGatewayTests
    {
        private static string GetChildAppGwResourceId(string subscriptionId,
                                                        string resourceGroupName,
                                                        string appGwname,
                                                        string childResourceType,
                                                        string childResourceName)
        {
            return string.Format(
                    "/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/applicationGateways/{2}/{3}/{4}",
                    subscriptionId,
                    resourceGroupName,
                    appGwname,
                    childResourceType,
                    childResourceName);
        }

        public ApplicationGatewayTests()
        {
            HttpMockServer.RecordsDirectory = "SessionRecords";
        }

        private List<ApplicationGatewaySslCertificate> CreateSslCertificate(string sslCertName, string password)
        {
            string certPath = System.IO.Path.Combine("Tests", "Data", "rsa2048.pfx");
            var cert = new X509Certificate2(certPath, password, X509KeyStorageFlags.Exportable);

            var sslCertList = new List<ApplicationGatewaySslCertificate>{
                new ApplicationGatewaySslCertificate()
                {
                    Name = sslCertName,
                    Data = Convert.ToBase64String(cert.Export(X509ContentType.Pfx, password)),
                    Password = password
                }
            };
            return sslCertList;
        }

        private List<ApplicationGatewayAuthenticationCertificate> CreateAuthCertificate(string authCertName)
        {
            string certPath = System.IO.Path.Combine("Tests", "Data", "ApplicationGatewayAuthCert.cer");
            var cert = new X509Certificate2(certPath);

            var authCertList = new List<ApplicationGatewayAuthenticationCertificate>()
            {
                new ApplicationGatewayAuthenticationCertificate()
                {
                    Name = authCertName,
                    Data  = Convert.ToBase64String(cert.Export(X509ContentType.Cert))
                }
            };
            return authCertList;
        }

        private ApplicationGateway CreateApplicationGateway(string location, Subnet subnet, string resourceGroupName, string appGwName, string subscriptionId)
        {
            var gatewayIPConfigName = TestUtilities.GenerateName();
            var frontendIPConfigName = TestUtilities.GenerateName();
            var frontendPort1Name = TestUtilities.GenerateName();
            var frontendPort2Name = TestUtilities.GenerateName();
            var frontendPort3Name = TestUtilities.GenerateName();
            var frontendPort4Name = TestUtilities.GenerateName();
            var backendAddressPoolName = TestUtilities.GenerateName();
            var nicBackendAddressPoolName = TestUtilities.GenerateName();
            var backendHttpSettings1Name = TestUtilities.GenerateName();
            var backendHttpSettings2Name = TestUtilities.GenerateName();
            var requestRoutingRule1Name = TestUtilities.GenerateName();
            var requestRoutingRule2Name = TestUtilities.GenerateName();
            var requestRoutingRule3Name = TestUtilities.GenerateName();
            var requestRoutingRule4Name = TestUtilities.GenerateName();
            var httpListener1Name = TestUtilities.GenerateName();
            var httpListener2Name = TestUtilities.GenerateName();
            var httpListener3Name = TestUtilities.GenerateName();
            var httpListener4Name = TestUtilities.GenerateName();
            var probeName = TestUtilities.GenerateName();
            var sslCertName = TestUtilities.GenerateName();
            var authCertName = TestUtilities.GenerateName();
            var redirectConfiguration1Name = TestUtilities.GenerateName();
            var redirectConfiguration2Name = TestUtilities.GenerateName();
            var urlPathMapName = TestUtilities.GenerateName();
            var pathRuleName = TestUtilities.GenerateName();

            var appGw = new ApplicationGateway()
            {
                Location = location,
                Sku = new ApplicationGatewaySku()
                {
                    Name = ApplicationGatewaySkuName.WAFMedium,
                    Tier = ApplicationGatewayTier.WAF,
                    Capacity = 2
                },
                GatewayIPConfigurations = new List<ApplicationGatewayIPConfiguration>()
                    {
                        new ApplicationGatewayIPConfiguration()
                        {
                            Name = gatewayIPConfigName,
                            Subnet = new SubResource()
                            {
                                Id = subnet.Id
                            }
                        }
                    },
                FrontendIPConfigurations = new List<ApplicationGatewayFrontendIPConfiguration>()
                    {
                        new ApplicationGatewayFrontendIPConfiguration()
                        {
                            Name = frontendIPConfigName,
                            PrivateIPAllocationMethod = IPAllocationMethod.Dynamic,
                            Subnet = new SubResource()
                            {
                                Id = subnet.Id
                            }
                        }
                    },
                FrontendPorts = new List<ApplicationGatewayFrontendPort>
                    {
                        new ApplicationGatewayFrontendPort()
                        {
                            Name = frontendPort1Name,
                            Port = 80
                        },
                        new ApplicationGatewayFrontendPort()
                        {
                            Name = frontendPort2Name,
                            Port = 443
                        },
                        new ApplicationGatewayFrontendPort()
                        {
                            Name = frontendPort3Name,
                            Port = 8080
                        },
                        new ApplicationGatewayFrontendPort()
                        {
                            Name = frontendPort4Name,
                            Port = 8081
                        }
                    },
                Probes = new List<ApplicationGatewayProbe>
                    {
                        new ApplicationGatewayProbe()
                        {
                            Name = probeName,
                            Protocol = ApplicationGatewayProtocol.Http,
                            Path = "/path/path.htm",
                            Interval = 17,
                            Timeout = 17,
                            UnhealthyThreshold = 5,
                            PickHostNameFromBackendHttpSettings = true,
                            Match = new ApplicationGatewayProbeHealthResponseMatch
                            {
                                Body = "helloworld",
                                StatusCodes = new List<string> {"200-300","403"}
                            }
                        }
                    },
                BackendAddressPools = new List<ApplicationGatewayBackendAddressPool>
                    {
                        new ApplicationGatewayBackendAddressPool()
                        {
                            Name = backendAddressPoolName,
                            BackendAddresses = new List<ApplicationGatewayBackendAddress>()
                            {
                                new ApplicationGatewayBackendAddress()
                                {
                                    IpAddress = "hello1.azurewebsites.net"
                                },
                                new ApplicationGatewayBackendAddress()
                                {
                                    IpAddress = "hello2.azurewebsites.net"
                                }
                            }
                        },
                        new ApplicationGatewayBackendAddressPool()
                        {
                            Name = nicBackendAddressPoolName
                        }
                    },
                BackendHttpSettingsCollection = new List<ApplicationGatewayBackendHttpSettings>
                    {
                        new ApplicationGatewayBackendHttpSettings()
                        {
                            Name = backendHttpSettings1Name,
                            Port = 80,
                            Protocol = ApplicationGatewayProtocol.Http,
                            CookieBasedAffinity = ApplicationGatewayCookieBasedAffinity.Disabled,
                            RequestTimeout = 69,
                            Probe = new SubResource()
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                    resourceGroupName, appGwName, "probes", probeName)
                            },
                            ConnectionDraining = new ApplicationGatewayConnectionDraining()
                            {
                                Enabled = true,
                                DrainTimeoutInSec = 42
                            },
                            ProbeEnabled = true,
                            PickHostNameFromBackendAddress = true
                        },
                        new ApplicationGatewayBackendHttpSettings()
                        {
                            Name = backendHttpSettings2Name,
                            Port = 443,
                            Protocol = ApplicationGatewayProtocol.Https,
                            CookieBasedAffinity = ApplicationGatewayCookieBasedAffinity.Enabled,
                            AuthenticationCertificates =  new List<SubResource>()
                            {
                                new SubResource()
                                {
                                    Id = GetChildAppGwResourceId(subscriptionId,
                                    resourceGroupName, appGwName, "authenticationCertificates", authCertName)
                                }
                            }
                        }
                    },
                HttpListeners = new List<ApplicationGatewayHttpListener>
                    {
                        new ApplicationGatewayHttpListener()
                        {
                            Name = httpListener1Name,
                            FrontendPort = new SubResource()
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                    resourceGroupName, appGwName, "frontendPorts", frontendPort1Name)
                            },
                            FrontendIPConfiguration = new SubResource()
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                    resourceGroupName, appGwName, "frontendIPConfigurations", frontendIPConfigName)
                            },
                            SslCertificate = null,
                            Protocol = ApplicationGatewayProtocol.Http
                        },
                        new ApplicationGatewayHttpListener()
                        {
                            Name = httpListener2Name,
                            FrontendPort = new SubResource()
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                    resourceGroupName, appGwName, "frontendPorts", frontendPort2Name)
                            },
                            FrontendIPConfiguration = new SubResource()
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                    resourceGroupName, appGwName, "frontendIPConfigurations", frontendIPConfigName)
                            },
                            SslCertificate = new SubResource()
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                    resourceGroupName, appGwName, "sslCertificates", sslCertName)
                            },
                            Protocol = ApplicationGatewayProtocol.Https
                        },
                        new ApplicationGatewayHttpListener()
                        {
                            Name = httpListener3Name,
                            FrontendPort = new SubResource()
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                    resourceGroupName, appGwName, "frontendPorts", frontendPort3Name)
                            },
                            FrontendIPConfiguration = new SubResource()
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                    resourceGroupName, appGwName, "frontendIPConfigurations", frontendIPConfigName)
                            },
                            SslCertificate = new SubResource()
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                    resourceGroupName, appGwName, "sslCertificates", sslCertName)
                            },
                            Protocol = ApplicationGatewayProtocol.Https
                        },
                        new ApplicationGatewayHttpListener()
                        {
                            Name = httpListener4Name,
                            FrontendPort = new SubResource()
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                    resourceGroupName, appGwName, "frontendPorts", frontendPort4Name)
                            },
                            FrontendIPConfiguration = new SubResource()
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                    resourceGroupName, appGwName, "frontendIPConfigurations", frontendIPConfigName)
                            },
                            SslCertificate = new SubResource()
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                    resourceGroupName, appGwName, "sslCertificates", sslCertName)
                            },
                            Protocol = ApplicationGatewayProtocol.Https
                        }
                    },
                UrlPathMaps = new List<ApplicationGatewayUrlPathMap>()
                    {
                        new ApplicationGatewayUrlPathMap{
                            Name = urlPathMapName,
                            DefaultRedirectConfiguration = new SubResource
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                resourceGroupName, appGwName, "redirectConfigurations", redirectConfiguration2Name)
                            },
                            PathRules = new List<ApplicationGatewayPathRule>
                            {
                                new ApplicationGatewayPathRule{
                                    Name = pathRuleName,
                                    Paths = new List<string>{"/paa"},
                                    BackendAddressPool = new SubResource()
                                    {
                                        Id = GetChildAppGwResourceId(subscriptionId,
                                            resourceGroupName, appGwName, "backendAddressPools", backendAddressPoolName)
                                    },
                                    BackendHttpSettings = new SubResource()
                                    {
                                        Id = GetChildAppGwResourceId(subscriptionId,
                                            resourceGroupName, appGwName, "backendHttpSettingsCollection", backendHttpSettings1Name)
                                    }
                                }
                            }

                        }
                    },
                RequestRoutingRules = new List<ApplicationGatewayRequestRoutingRule>()
                    {
                        new ApplicationGatewayRequestRoutingRule()
                        {
                            Name = requestRoutingRule1Name,
                            RuleType = ApplicationGatewayRequestRoutingRuleType.Basic,
                            HttpListener = new SubResource()
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                    resourceGroupName, appGwName, "httpListeners", httpListener1Name)
                            },
                            BackendAddressPool = new SubResource()
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                    resourceGroupName, appGwName, "backendAddressPools", backendAddressPoolName)
                            },
                            BackendHttpSettings = new SubResource()
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                    resourceGroupName, appGwName, "backendHttpSettingsCollection", backendHttpSettings1Name)
                            }
                        },
                        new ApplicationGatewayRequestRoutingRule()
                        {
                            Name = requestRoutingRule2Name,
                            RuleType = ApplicationGatewayRequestRoutingRuleType.Basic,
                            HttpListener = new SubResource()
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                    resourceGroupName, appGwName, "httpListeners", httpListener2Name)
                            },
                            RedirectConfiguration = new SubResource()
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                    resourceGroupName, appGwName, "redirectConfigurations", redirectConfiguration1Name)
                            }
                        },
                        new ApplicationGatewayRequestRoutingRule()
                        {
                            Name = requestRoutingRule3Name,
                            RuleType = ApplicationGatewayRequestRoutingRuleType.PathBasedRouting,
                            HttpListener = new SubResource()
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                    resourceGroupName, appGwName, "httpListeners", httpListener3Name)
                            },
                            UrlPathMap = new SubResource()
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                    resourceGroupName, appGwName, "urlPathMaps", urlPathMapName)
                            }
                        },
                        new ApplicationGatewayRequestRoutingRule()
                        {
                            Name = requestRoutingRule4Name,
                            RuleType = ApplicationGatewayRequestRoutingRuleType.Basic,
                            HttpListener = new SubResource()
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                    resourceGroupName, appGwName, "httpListeners", httpListener4Name)
                            },
                            BackendAddressPool = new SubResource()
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                    resourceGroupName, appGwName, "backendAddressPools", nicBackendAddressPoolName)
                            },
                            BackendHttpSettings = new SubResource()
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                    resourceGroupName, appGwName, "backendHttpSettingsCollection", backendHttpSettings2Name)
                            }
                        },
                    },
                AuthenticationCertificates = CreateAuthCertificate(authCertName),
                WebApplicationFirewallConfiguration = new ApplicationGatewayWebApplicationFirewallConfiguration()
                {
                    Enabled = true,
                    FirewallMode = ApplicationGatewayFirewallMode.Prevention,
                    RuleSetType = "OWASP",
                    RuleSetVersion = "2.2.9",
                    DisabledRuleGroups = new List<ApplicationGatewayFirewallDisabledRuleGroup>()
                        {
                            new ApplicationGatewayFirewallDisabledRuleGroup(
                                "crs_41_sql_injection_attacks",
                                new List<int>() { 981318, 981320 }),
                            new ApplicationGatewayFirewallDisabledRuleGroup("crs_35_bad_robots")
                        }
                },
                SslPolicy = new ApplicationGatewaySslPolicy()
                {
                    PolicyType = "Predefined",
                    PolicyName = "AppGwSslPolicy20170401"
                },
                RedirectConfigurations = new List<ApplicationGatewayRedirectConfiguration>
                    {
                        new ApplicationGatewayRedirectConfiguration
                        {
                            Name = redirectConfiguration1Name,
                            RedirectType = ApplicationGatewayRedirectType.Permanent,
                            TargetListener = new SubResource()
                            {
                                Id = GetChildAppGwResourceId(subscriptionId,
                                    resourceGroupName, appGwName, "httpListeners", httpListener1Name)
                            },
                        },
                        new ApplicationGatewayRedirectConfiguration
                        {
                            Name = redirectConfiguration2Name,
                            RedirectType = ApplicationGatewayRedirectType.Permanent,
                            TargetUrl = "http://www.bing.com"
                        }
                    },
                //SslCertificates = CreateSslCertificate(sslCertName, "abc")
            };
            return appGw;
        }

        private void CompareApplicationGateway(ApplicationGateway gw1, ApplicationGateway gw2)
        {
            // compare count of child resources
            Assert.Equal(gw1.GatewayIPConfigurations.Count, gw2.GatewayIPConfigurations.Count);
            Assert.Equal(gw1.FrontendIPConfigurations.Count, gw2.FrontendIPConfigurations.Count);
            Assert.Equal(gw1.FrontendPorts.Count, gw2.FrontendPorts.Count);
            Assert.Equal(gw1.Probes.Count, gw2.Probes.Count);
            Assert.Equal(gw1.BackendAddressPools.Count, gw2.BackendAddressPools.Count);
            Assert.Equal(gw1.BackendHttpSettingsCollection.Count, gw2.BackendHttpSettingsCollection.Count);
            Assert.Equal(gw1.HttpListeners.Count, gw2.HttpListeners.Count);
            Assert.Equal(gw1.RequestRoutingRules.Count, gw2.RequestRoutingRules.Count);
            Assert.Equal(gw1.RedirectConfigurations.Count, gw2.RedirectConfigurations.Count);
            Assert.Equal(gw1.AuthenticationCertificates.Count, gw2.AuthenticationCertificates.Count);

            // compare sku
            Assert.Equal(gw1.Sku.Name, gw2.Sku.Name);
            Assert.Equal(gw1.Sku.Tier, gw2.Sku.Tier);
            Assert.Equal(gw1.Sku.Capacity, gw2.Sku.Capacity);

            // compare connectionDraining
            for (int i = 0; i < gw1.BackendHttpSettingsCollection.Count; i++)
            {
                if (gw1.BackendHttpSettingsCollection[i].ConnectionDraining != null)
                {
                    Assert.NotNull(gw2.BackendHttpSettingsCollection[i].ConnectionDraining);
                    Assert.Equal(gw1.BackendHttpSettingsCollection[i].ConnectionDraining.Enabled, gw2.BackendHttpSettingsCollection[i].ConnectionDraining.Enabled);
                    Assert.Equal(gw1.BackendHttpSettingsCollection[i].ConnectionDraining.DrainTimeoutInSec, gw2.BackendHttpSettingsCollection[i].ConnectionDraining.DrainTimeoutInSec);
                }
                else
                {
                    Assert.Null(gw2.BackendHttpSettingsCollection[i].ConnectionDraining);
                }
            }

            //compare WAF
            Assert.Equal(gw1.WebApplicationFirewallConfiguration.Enabled, gw2.WebApplicationFirewallConfiguration.Enabled);
            Assert.Equal(gw1.WebApplicationFirewallConfiguration.FirewallMode, gw2.WebApplicationFirewallConfiguration.FirewallMode);
            Assert.Equal(gw1.WebApplicationFirewallConfiguration.RuleSetType, gw2.WebApplicationFirewallConfiguration.RuleSetType);
            Assert.Equal(gw1.WebApplicationFirewallConfiguration.RuleSetVersion, gw2.WebApplicationFirewallConfiguration.RuleSetVersion);
            if (gw1.WebApplicationFirewallConfiguration.DisabledRuleGroups != null)
            {
                Assert.NotNull(gw2.WebApplicationFirewallConfiguration.DisabledRuleGroups);
                Assert.Equal(gw1.WebApplicationFirewallConfiguration.DisabledRuleGroups.Count, gw2.WebApplicationFirewallConfiguration.DisabledRuleGroups.Count);
                for (int i = 0; i < gw1.WebApplicationFirewallConfiguration.DisabledRuleGroups.Count; i++)
                {
                    Assert.Equal(gw1.WebApplicationFirewallConfiguration.DisabledRuleGroups[i].RuleGroupName, gw2.WebApplicationFirewallConfiguration.DisabledRuleGroups[i].RuleGroupName);
                    Assert.Equal(gw1.WebApplicationFirewallConfiguration.DisabledRuleGroups[i].Rules, gw2.WebApplicationFirewallConfiguration.DisabledRuleGroups[i].Rules);
                }
            }
            else
            {
                Assert.Empty(gw2.WebApplicationFirewallConfiguration.DisabledRuleGroups);
            }

            // ssl policy
            Assert.Equal(gw1.SslPolicy.PolicyType, gw2.SslPolicy.PolicyType);
            Assert.Equal(gw1.SslPolicy.PolicyName, gw2.SslPolicy.PolicyName);
            Assert.Equal(gw1.SslPolicy.MinProtocolVersion, gw2.SslPolicy.MinProtocolVersion);
        }

        [Fact]
        public void ApplicationGatewayApiTest()
        {
            var handler1 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
            var handler2 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };

            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {

                var resourcesClient = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(context, handler1);
                var networkManagementClient = NetworkManagementTestUtilities.GetNetworkManagementClientWithHandler(context, handler2);

                var location = "West US";

                var a = HttpMockServer.Mode;

                string resourceGroupName = TestUtilities.GenerateName("csmrg");
                resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
                    new ResourceGroup
                    {
                        Location = location
                    });

                var vnetName = TestUtilities.GenerateName();
                var gwSubnetName = TestUtilities.GenerateName();
                var subnet2Name = TestUtilities.GenerateName();
                var appGwName = TestUtilities.GenerateName();

                var vnet = new VirtualNetwork()
                {
                    Location = location,

                    AddressSpace = new AddressSpace()
                    {
                        AddressPrefixes = new List<string>()
                    {
                        "10.0.0.0/16",
                    }
                    },
                    DhcpOptions = new DhcpOptions()
                    {
                        DnsServers = new List<string>()
                    {
                        "10.1.1.1",
                        "10.1.2.4"
                    }
                    },
                    Subnets = new List<Subnet>()
                    {
                        new Subnet()
                        {
                            Name = gwSubnetName,
                            AddressPrefix = "10.0.0.0/24",
                        },
                        new Subnet()
                        {
                            Name = subnet2Name,
                            AddressPrefix = "10.0.1.0/24",
                        }
                    }
                };

                var putVnetResponse = networkManagementClient.VirtualNetworks.CreateOrUpdate(resourceGroupName, vnetName, vnet);
                var getVnetResponse = networkManagementClient.VirtualNetworks.Get(resourceGroupName, vnetName);
                var getSubnetResponse = networkManagementClient.Subnets.Get(resourceGroupName, vnetName, gwSubnetName);
                Console.WriteLine("Virtual Network GatewaySubnet Id: {0}", getSubnetResponse.Id);
                var gwSubnet = getSubnetResponse;

                var appGw = CreateApplicationGateway(location, gwSubnet, resourceGroupName, appGwName, networkManagementClient.SubscriptionId);

                // Put AppGw
                var putAppGwResponse = networkManagementClient.ApplicationGateways.CreateOrUpdate(resourceGroupName, appGwName, appGw);
                Assert.Equal("Succeeded", putAppGwResponse.ProvisioningState);

                // Get AppGw
                var getGateway = networkManagementClient.ApplicationGateways.Get(resourceGroupName, appGwName);
                Assert.Equal(appGwName, getGateway.Name);
                CompareApplicationGateway(appGw, getGateway);

                // Get available WAF rule sets (validate first result set/group)
                var availableWAFRuleSets = networkManagementClient.ApplicationGateways.ListAvailableWafRuleSets();
                Assert.NotNull(availableWAFRuleSets);
                Assert.NotEmpty(availableWAFRuleSets.Value);
                Assert.NotNull(availableWAFRuleSets.Value[0].Name);
                Assert.NotNull(availableWAFRuleSets.Value[0].RuleSetType);
                Assert.NotNull(availableWAFRuleSets.Value[0].RuleSetVersion);
                Assert.NotEmpty(availableWAFRuleSets.Value[0].RuleGroups);
                Assert.NotNull(availableWAFRuleSets.Value[0].RuleGroups[0].RuleGroupName);
                Assert.NotEmpty(availableWAFRuleSets.Value[0].RuleGroups[0].Rules);
                Assert.NotNull(availableWAFRuleSets.Value[0].RuleGroups[0].Rules[0].RuleId);

                // Get availalbe SSL options
                var sslOptions = networkManagementClient.ApplicationGateways.ListAvailableSslOptions();
                Assert.NotNull(sslOptions.DefaultPolicy);
                Assert.NotNull(sslOptions.AvailableCipherSuites);
                Assert.NotNull(sslOptions.AvailableCipherSuites[20]);

                var policies = networkManagementClient.ApplicationGateways.ListAvailableSslPredefinedPolicies();
                var enumerator = policies.GetEnumerator();
                Assert.True(enumerator.MoveNext());
                Assert.NotNull(enumerator.Current.Name);

                var policy = networkManagementClient.ApplicationGateways.GetSslPredefinedPolicy(ApplicationGatewaySslPolicyName.AppGwSslPolicy20150501);
                Assert.NotNull(policy.MinProtocolVersion);
                Assert.NotNull(policy.CipherSuites);
                Assert.NotNull(policy.CipherSuites[20]);

                // Create Nics
                string nic1name = TestUtilities.GenerateName();
                string nic2name = TestUtilities.GenerateName();

                var nic1 = TestHelper.CreateNetworkInterface(
                    nic1name,
                    resourceGroupName,
                    null,
                    getVnetResponse.Subnets[1].Id,
                    location,
                    "ipconfig",
                    networkManagementClient);

                var nic2 = TestHelper.CreateNetworkInterface(
                    nic2name,
                    resourceGroupName,
                    null,
                    getVnetResponse.Subnets[1].Id,
                    location,
                    "ipconfig",
                    networkManagementClient);

                // Add NIC to application gateway backend address pool.
                nic1.IpConfigurations[0].ApplicationGatewayBackendAddressPools = new List<ApplicationGatewayBackendAddressPool>
                                                                                {
                                                                                getGateway.BackendAddressPools[1]
                                                                                };
                nic2.IpConfigurations[0].ApplicationGatewayBackendAddressPools = new List<ApplicationGatewayBackendAddressPool>
                                                                                {
                                                                                getGateway.BackendAddressPools[1]
                                                                                };
                // Put Nics
                networkManagementClient.NetworkInterfaces.CreateOrUpdate(resourceGroupName, nic1name, nic1);
                networkManagementClient.NetworkInterfaces.CreateOrUpdate(resourceGroupName, nic2name, nic2);

                // Get AppGw backend health
                var backendHealth = networkManagementClient.ApplicationGateways.BackendHealth(resourceGroupName, appGwName, "true");
                Assert.Equal(2, backendHealth.BackendAddressPools.Count);
                Assert.Equal(1, backendHealth.BackendAddressPools[0].BackendHttpSettingsCollection.Count);
                Assert.Equal(1, backendHealth.BackendAddressPools[1].BackendHttpSettingsCollection.Count);
                Assert.True(backendHealth.BackendAddressPools[1].BackendAddressPool.BackendIPConfigurations.IsAny());

                //Start AppGw
                networkManagementClient.ApplicationGateways.Start(resourceGroupName, appGwName);

                // Get AppGw and make sure nics are added to backend
                getGateway = networkManagementClient.ApplicationGateways.Get(resourceGroupName, appGwName);
                Assert.Equal(2, getGateway.BackendAddressPools[1].BackendIPConfigurations.Count);

                //Stop AppGw
                networkManagementClient.ApplicationGateways.Stop(resourceGroupName, appGwName);

                // Delete AppGw
                networkManagementClient.ApplicationGateways.Delete(resourceGroupName, appGwName);
            }
        }
    }
}


text:
<?php require_once('Connections/MySQL.php'); ?>
<?php
//initialize the session
if (!isset($_SESSION)) {
  session_start();
}

if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysqli_real_escape_string") ? mysqli_real_escape_string(dbconnect(), $theValue) : mysqli_escape_string(dbconnect(), $theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}
?>

Fecha de firma actualizada con éxito

<?php
$query_Recordset1 = sprintf("select a.Apellido, a.DNI , m.Descripcion, am.FechaFirma, am.IdAlumnoMateria
                     from
                        terciario.materias m
                            inner join terciario.materias_plan mp on mp.IdMateria = m.IdMateria
                            inner join terciario.alumno_materias am on m.IdMateria = am.IdMateriaPlan
                            inner join terciario.alumnos a on a.IdAlumno = am.IdAlumno
                    where a.IdAlumno = %s", GetSQLValueString($_POST['id'], "int"));

$Recordset1 = mysqli_query(dbconnect(),$query_Recordset1) or die(mysqli_error());
$row_Recordset1 = mysqli_fetch_assoc($Recordset1);
?>

<?php
do {

    if(($_POST['idmesa'.(string)$row_Recordset1['IdAlumnoMateria']])==='1')
    {
        $par2 = $_POST['idAlumnoMateria'.(string)$row_Recordset1['IdAlumnoMateria']];
        $par2 = "'".$par2."'";
        $par1 = $row_Recordset1['IdAlumnoMateria'];

        mysqli_query(dbconnect(),"UPDATE terciario.alumno_materias SET FechaFirma = $par2 WHERE IdAlumnoMateria=  $par1 ");
    } else if (($_POST['idmesa'.(string)$row_Recordset1['IdAlumnoMateria']])==='2') {
        $par1 = $row_Recordset1['IdAlumnoMateria'];
        mysqli_query(dbconnect(),"UPDATE terciario.alumno_materias SET FechaFirma = NULL WHERE IdAlumnoMateria=  $par1 ");
    }
} while ($row_Recordset1 = mysqli_fetch_assoc($Recordset1));

 //header("Location: " . "Direcciones.php" );
?>

    <input type=button onClick="location.href='Direcciones.php'" value='Volver al menu principal'>

redpajama_set_name: RedPajamaGithub


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

namespace AimaTeam.Http
{
    /// <summary>
    /// This is a extension class for <see cref="MultipartFormData"/>
    /// </summary>
    public static partial class MultipartFormDataExtension
    {
        /// <summary>
        /// 将一个字典添加到 <see cref="MultipartFormData"/>对象中
        /// </summary>
        /// <param name="formData"></param>
        /// <param name="_params"></param>
        /// <returns></returns>
        public static MultipartFormData AddParameter(this MultipartFormData formData, IDictionary<string, object> _params)
        {
            foreach (var _p in _params.Keys)
            {
                formData.AddParameter(_p, _params[_p] == null ? "" : _params[_p].ToString());
            }
            return formData;
        }

        /// <summary>
        /// 将一个字典添加到 <see cref="MultipartFormData"/>对象中
        /// </summary>
        /// <param name="formData"></param>
        /// <param name="_params"></param>
        /// <returns></returns>
        public static MultipartFormData AddParameter(this MultipartFormData formData, IDictionary<string, string> _params)
        {
            foreach (var _p in _params.Keys)
            {
                formData.AddParameter(_p, _params[_p] == null ? "" : _params[_p]);
            }
            return formData;
        }
    }
}


text: Android client for LFGSS.com


text:
<?php

namespace Minsal\sifdaBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
//use Minsal\sifdaBundle\Entity\Catalogo;
//use Minsal\sifdaBundle\Form\CatalogoType;

/**
 * Catalogo controller.
 *
 * @Route("/sifda/administrador")
 */
class AdministradorController extends Controller
{

    /**
     * Lists all Catalogo entities.
     *
     * @Route("/", name="sifda_administrador")
     * @Method("GET")
     * @Template()
     */
    public function index3Action()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('MinsalsifdaBundle:SifdaSolicitudServicio')->findAll();

        $estado=1;

        $solicitudes = $em->getRepository('MinsalsifdaBundle:SifdaSolicitudServicio')->ContarSolicitudesIngresadas($estado);
//         $solicitudes2=  implode("",$solicitudes);
//         ladybug_dump($solicitudes);
         if(!$solicitudes)
             {
                throw $this->createNotFoundException('Unable to find SifdaSolicitudServicio entity.');
             }

       $valor=  array_shift($solicitudes);

        return array(
            'entities' => $entities,
            'dependencias'=>$valor
        );
        //return $this->render('MinsalsifdaBundle:Administrador:index.html.twig');

    }
    /**
     * Creates a new Catalogo entity.
     *
     * @Route("/", name="sifda_catalogo_create")
     * @Method("POST")
     * @Template("MinsalsifdaBundle:Catalogo:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new Catalogo();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('sifda_catalogo_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Creates a form to create a Catalogo entity.
     *
     * @param Catalogo $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Catalogo $entity)
    {
        $form = $this->createForm(new CatalogoType(), $entity, array(
            'action' => $this->generateUrl('sifda_catalogo_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new Catalogo entity.
     *
     * @Route("/new", name="sifda_catalogo_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Catalogo();
        $form   = $this->createCreateForm($entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a Catalogo entity.
     *
     * @Route("/{id}", name="sifda_catalogo_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('MinsalsifdaBundle:Catalogo')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Catalogo entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing Catalogo entity.
     *
     * @Route("/{id}/edit", name="sifda_catalogo_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('MinsalsifdaBundle:Catalogo')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Catalogo entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
    * Creates a form to edit a Catalogo entity.
    *
    * @param Catalogo $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Catalogo $entity)
    {
        $form = $this->createForm(new CatalogoType(), $entity, array(
            'action' => $this->generateUrl('sifda_catalogo_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing Catalogo entity.
     *
     * @Route("/{id}", name="sifda_catalogo_update")
     * @Method("PUT")
     * @Template("MinsalsifdaBundle:Catalogo:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('MinsalsifdaBundle:Catalogo')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Catalogo entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('sifda_catalogo_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a Catalogo entity.
     *
     * @Route("/{id}", name="sifda_catalogo_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('MinsalsifdaBundle:Catalogo')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Catalogo entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('sifda_catalogo'));
    }

    /**
     * Creates a form to delete a Catalogo entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('sifda_catalogo_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
}


text:
Rack Middleware that embeds the Konami Code in your app and lets you fade in and out a snippet of html.

## Requirements
It requires JQuery 1.4.0 or greater.

## Usage

```
$ gem install rack_konami
```

```ruby
require 'rack_konami'

use Rack::Konami, :html => "<img src='/images/rails.png'>"

app = lambda { |env| [200, { 'Content-Type' => 'text/html' }, '<html><body><p>Awesome Body</p></body></html>'] }
run app
```

## Usage in Rails 2.3.x

In config/environment.rb

	config.gem 'rack_clicky'
	config.middleware.use Rack::Konami, :html => '', :delay => '1500'
	Open your browser and type ↑ ↑ ↓ ↓  ← →  ← → B A  ↵

## Rails 3.x / Sinatra
In your Gemfile

	gem "rack_konami"

In your config.ru

``
use Rack::Konami, :html => '', :delay => '1500'
```

Open your browser and type `↑ ↑ ↓ ↓  ← →  ← → B A  ↵`

## TODO

* It probably wouldn't hurt to have more tests.
* Add support for embedding the asynchronous tracking code.

## Note on Patches/Pull Requests

* Fork the project.
* Make your feature addition or bug fix.
* Add tests for it. This is important so I don't break it in a
  future version unintentionally.
* Commit, do not mess with rakefile, version, or history.
  (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
* Send me a pull request. Bonus points for topic branches.

## Copyright

Copyright (c) 2010 Mark Turner. See LICENSE for details.


text:
import * as q from 'q';
import {Config, protractor} from '../..';
import {promise as wdpromise} from 'selenium-webdriver';
const env = require('../environment.js');

export let config: Config = {
  seleniumAddress: env.seleniumAddress,

  framework: 'jasmine',

  specs: [
    'plugin/plugin_spec.js'
  ],

  capabilities: env.capabilities,

  baseUrl: env.baseUrl + '/ng1/',

  SELENIUM_PROMISE_MANAGER: false,

  plugins: [{
    inline: {
      onPageLoad: function() {
        //TODO: remove cast when @types/selenium-webdriver understands disabling the control flow
        return (q.delay(100) as any as wdpromise.Promise<void>).then(function() {
          (protractor as any).ON_PAGE_LOAD = true;
        });
      }
    }
  }]
};


text:
package cats

final case class Cat(name: String, age: Int, color: String)
object Cat {
  import cats.syntax.show._
  import cats.std.int._
  import cats.std.string._

  implicit val catShow = Show.show[Cat] { cat =>
    val name = cat.name.show
    val age = cat.age.show
    val color = cat.color.show

    s"$name is a $age year-old $color cat."
  }
}

object CatShowDriver extends App {
  import Cat._

  val tabby = Cat("Tabby", 4, "reddish-brown")

  import cats.syntax.show._
  println(tabby.show)
}


text:
import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { sortedCatagIds, sort } from '../lib/nodes';
import homeStyles from '../styles/modules/HomePageNodes.scss';
import topicsStyles from '../styles/modules/TopicsPageNodes.scss';

class NodesPartial extends React.Component {

  static propTypes = {
    partialHeadContent: PropTypes.string.isRequired,
    page: PropTypes.string.isRequired,
    nodes: PropTypes.array.isRequired
  }

  render(){
    const { partialHeadContent, page, nodes } = this.props;
    const styles = page === 'home' ? homeStyles : topicsStyles;
    const store = sort(nodes);
    const keys = Object.keys(store);
    const sortKeys = [];
    if (keys.length > 0) {
      sortedCatagIds.forEach((id) => {
        if (keys.indexOf(id.toString()) >= 0) sortKeys.push(id);
      })
    }
    return (

{partialHeadContent}

          {sortKeys.map( key =>

                {store[key]['name']}

                {store[key]['items'].map( item =>
                  <Link to={`/topics/node${item.id}`}
                        key={item.id}
                        className={styles['node-item']}>
                    {item.name}
                  </Link>
                )}

          )}

    )
  }
}

export default NodesPartial;


text:
<?php

class Controller_SNI_Google extends Controller_SNI {
    protected $oauth;
    protected $developer_key;
    function setOAuth($oauth){
        $this->oauth = $oauth;
    }
    function setDeveloperKey($key){
        $this->developer_key = $key;
    }
    function setAuthToken($oauth){
        if (is_array($oauth)){
            $this->oauth_token = $oauth["oauth_token"];
            $this->oauth_token_secret = $oauth["oauth_token_secret"];
        } else if (is_object($oauth) && method_exists($oauth, "getAuthToken")){
            $this->setAuthToken($oauth->getAuthToken());
        }
    }
    function request($url, $params){

    }
}


text:
from oslo_config import cfg
from oslo_upgradecheck.upgradecheck import Code

from murano.cmd import status
from murano.tests.unit import base

class TestUpgradeChecks(base.MuranoTestCase):

    def setUp(self):
        super(TestUpgradeChecks, self).setUp()
        self.cmd = status.Checks()

    def test_checks(self):
        cfg.CONF(args=[], project='murano')
        for name, func in self.cmd._upgrade_checks:
            if isinstance(func, tuple):
                func_name, kwargs = func
                result = func_name(self, **kwargs)
            else:
                result = func(self)
            self.assertEqual(Code.SUCCESS, result.code)


text:
require 'spec_helper'

describe Clockworkd do
  it "should define rails" do
    ::Rails::VERSION::MAJOR.should be
  end

end


text:
package com.github.mkroli.cdns

import scala.collection.JavaConverters.asScalaBufferConverter

import com.datastax.driver.core.Cluster
import com.datastax.driver.core.querybuilder.QueryBuilder

import akka.actor.Actor
import akka.actor.Props
import akka.pattern.pipe

trait CassandraComponent {
  self: AkkaComponent =>

  val cassandraHosts: List[String]

  lazy val cassandraActor = system.actorOf(Props(new CassandraActor))

  case class CassandraQuery(question: String, `type`: String)
  case class CassandraResponse(answers: List[String], shuffle: Boolean)

  lazy val cluster = {
    val cluster = (Cluster.builder /: cassandraHosts)(_ addContactPoint _).build.connect

    cluster.execute("""CREATE KEYSPACE IF NOT EXISTS cdns WITH replication = {
      'class': 'SimpleStrategy',
      'replication_factor': 1
    }""")

    cluster.execute("""CREATE COLUMNFAMILY IF NOT EXISTS cdns.cdns (
      question text,
      type text,
      answers list<text>,
      shuffle boolean,
      PRIMARY KEY (question, type)
    )""")

    cluster
  }

  private lazy val query = cluster.prepare(QueryBuilder
    .select("answers", "shuffle")
    .from("cdns", "cdns")
    .where(QueryBuilder.eq("question", QueryBuilder.bindMarker))
    .and(QueryBuilder.eq("type", QueryBuilder.bindMarker)))

  private class CassandraActor extends Actor {
    import context.dispatcher

    override def receive = {
      case CassandraQuery(q, t) =>
        cluster.executeAsync(query.bind(q, t)).map(r => Option(r.one)).collect {
          case Some(row) =>
            val answers = row.getList("answers", classOf[String]).asScala.toList
            val shuffle = row.getBool("shuffle")
            CassandraResponse(answers, shuffle)
        }.pipeTo(sender)
    }
  }
}


text:
using BenchmarkDotNet.Jobs;
using System;
using System.Threading;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Loggers;
using BenchmarkDotNet.Running;
using BenchmarkDotNet.Tests.Loggers;
using Xunit;
using Xunit.Abstractions;

namespace BenchmarkDotNet.IntegrationTests
{
    public class GlobalSetupAttributeTest : BenchmarkTestExecutor
    {
        private const string GlobalSetupCalled = "// ### GlobalSetup called ###";
        private const string BenchmarkCalled = "// ### Benchmark called ###";

        public GlobalSetupAttributeTest(ITestOutputHelper output) : base(output) { }

        [Fact]
        public void GlobalSetupMethodRunsTest()
        {
            var logger = new OutputLogger(Output);
            var config = CreateSimpleConfig(logger);

            CanExecute<GlobalSetupAttributeBenchmarks>(config);

            string log = logger.GetLog();
            Assert.Contains(GlobalSetupCalled + Environment.NewLine, log);
            Assert.True(
                log.IndexOf(GlobalSetupCalled + Environment.NewLine) <
                log.IndexOf(BenchmarkCalled + Environment.NewLine));
        }

        public class GlobalSetupAttributeBenchmarks
        {
            [GlobalSetup]
            public void GlobalSetup()
            {
                Console.WriteLine(GlobalSetupCalled);
            }

            [Benchmark]
            public void Benchmark()
            {
                Console.WriteLine(BenchmarkCalled);
            }
        }
    }
}


text:
({
    onChange1 : function(cmp, evt, helper){
        var array = evt.getParam('value') || [];
        cmp.set("v.firstArrayLen", array.length);

        cmp._log || (cmp._log = []);
        cmp._log.push(evt.getParams());
    },
    onChange2 : function(cmp, evt, helper){
        cmp._log || (cmp._log = []);
        cmp._log.push(evt.getParams());

        var array = evt.getParam('value') || [];
        cmp.set("v.secondArrayLen", array.length);

        cmp._log || (cmp._log = []);
        cmp._log.push(evt.getParams());
    },
    onLengthChangeArrayFromModel : function(cmp, evt, helper) {
        cmp.set("v.arrayFromModelLen", evt.getParams('value'));
    }
})


text:
from pipeline.param.base_param import BaseParam

class SecureAddExampleParam(BaseParam):
    def __init__(self, seed=None, partition=1, data_num=1000):
        self.seed = seed
        self.partition = partition
        self.data_num = data_num

    def check(self):
        if self.seed is not None and type(self.seed).__name__ != "int":
            raise ValueError("random seed should be None or integers")

        if type(self.partition).__name__ != "int" or self.partition < 1:
            raise ValueError("partition should be an integer large than 0")

        if type(self.data_num).__name__ != "int" or self.data_num < 1:
            raise ValueError("data_num should be an integer large than 0")


text:
<resources>

    <!-- Declare custom theme attributes that allow changing which styles are
         used for button bars depending on the API level.
         ?android:attr/buttonBarStyle is new as of API 11 so this is
         necessary to support previous API levels. -->
    <declare-styleable name="ButtonBarContainerTheme">
        <attr name="metaButtonBarStyle" format="reference" />
        <attr name="metaButtonBarButtonStyle" format="reference" />
    </declare-styleable>

    <declare-styleable name="ReservationOptions">
        <attr name="textPadding" format="integer" />
        <attr name="showLineState" format="boolean" />
        <attr name="highLight" format="boolean" />
    </declare-styleable>

    <declare-styleable name="DataUnitOptions">
        <attr name="dataText" format="string" />
        <attr name="unitText" format="string" />
        <attr name="dataFontSize" format="float" />
        <attr name="unitFontSize" format="float" />
    </declare-styleable>

</resources>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;

namespace EgovaBLL
{
    public class LogHelper
    {
        private ILog logger;
        public LogHelper(Type type)
        {
            logger = LogManager.GetLogger(type);
        }
       public void Debug(object message)
        {
            logger.Debug(message);
        }
       public void Error(object message)
        {
            logger.Error(message);
        }
       public void Fatal(object message)
        {
            logger.Fatal(message);
        }
       public void Info(object message)
        {
            logger.Info(message);
        }
       public void Warn(object message)
        {
            logger.Warn(message);
        }

    }
}


text:
package com.google.security.zynamics.binnavi.ZyGraph.Menus.Actions;

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;

import com.google.common.base.Preconditions;
import com.google.security.zynamics.binnavi.Gui.GraphWindows.Implementations.CGraphSelecter;
import com.google.security.zynamics.binnavi.disassembly.INaviFunction;
import com.google.security.zynamics.binnavi.yfileswrap.zygraph.ZyGraph;

/**
 * Action class used to select all nodes of a graph which have the same parent function as a given
 * graph.
 */
public final class CActionSelectSameParentFunction extends AbstractAction {
  /**
   * Used for serialization.
   */
  private static final long serialVersionUID = 6300870557894835360L;

  /**
   * Graph in which the selection event happens.
   */
  private final ZyGraph m_graph;

  /**
   * Nodes with this parent function are selected.
   */
  private final INaviFunction m_function;

  /**
   * Creates a new action object.
   *
   * @param graph Graph in which the selection event happens.
   * @param function Nodes with this parent function are selected.
   */
  public CActionSelectSameParentFunction(final ZyGraph graph, final INaviFunction function) {
    super("Select nodes from the same function");

    m_graph = Preconditions.checkNotNull(graph, "IE00936: Graph argument can't be null");
    m_function = Preconditions.checkNotNull(function, "IE00937: Function argument can't be null");
  }

  @Override
  public void actionPerformed(final ActionEvent event) {
    CGraphSelecter.selectNodesWithParentFunction(m_graph, m_function);
  }
}


text:
require 'test_helper'
require 'employee'

class ActsAsTallyableTest < Minitest::Test
  def employee_stub(stub_response)
    stub_request(:post, "http://example.com:9002").
      with( body: File.read("lib/tallyable/employee_request.xml") ).
        to_return(stub_response)
  end

  def test_an_employee_tallyable_for_invalid_request
    employee_stub(status: 500, body: "Internal Server Error", headers: {})

    result = Employee.employee_request
    assert_equal result, []
  end

  def test_an_employee_tallyable_on_a_valid_request
    employee_stub(status: 200,
      body: File.read("test/fixtures/employee_response.xml"), headers: {})

    result = Employee.employee_request
    assert_equal result.count, 3
  end

  def test_an_employee_tallyable_response_on_a_valid_request
    employee_stub(status: 200,
      body: File.read("test/fixtures/employee_response.xml"), headers: {})

    result = Employee.employee_request
    assert_equal result.first[:name], "test_employee_1"
    assert_equal result.first[:email], "test_employee_1@example.com"
    assert_equal result.first[:date_of_birth], '20-July-1970'
    assert_equal result.first[:gender], "Male"
    assert_equal result.first[:address], "Bangalore"
    assert_equal result.first[:phone], "1234567890"
  end
end


text:
from django.db import models

# get_facebook_client lets us get the current Facebook object
# from outside of a view, which lets us have cleaner code
from facebook.djangofb import get_facebook_client

class UserManager(models.Manager):
    """Custom manager for a Facebook User."""

    def get_current(self):
        """Gets a User object for the logged-in Facebook user."""
        facebook = get_facebook_client()
        user, created = self.get_or_create(id=int(facebook.uid))
        if created:
            # we could do some custom actions for new users here...
            pass
        return user

class User(models.Model):
    """A simple User model for Facebook users."""

    # We use the user's UID as the primary key in our database.
    id = models.IntegerField(primary_key=True)

    # TODO: The data that you want to store for each user would go here.
    # For this sample, we let users let people know their favorite progamming
    # language, in the spirit of Extended Info.
    language = models.CharField(maxlength=64, default='Python')

    # Add the custom manager
    objects = UserManager()


text:
RSpec.describe Moya do
  describe '#show' do
    context 'when requesting hale json' do
      include_context 'shared drd hale context'

      it 'responds appropriately to a drd show call' do
        show_url = hale_url_for("self", drds.embedded["items"].sample)
        expect(get(show_url).status).to eq(200)
      end

      it 'returns the appropriate attributes for a drd show call' do
        show_url = hale_url_for("self", drds.embedded["items"].sample)
        drd = parse_hale(get(show_url).body)
        expect(drd.properties.keys).to match_array(drd_properties)
      end

      it 'returns an appropriate 404 response for an unkown drd' do
        show_url = hale_url_for("self", drds.embedded["items"].sample)
        # Trim off the uuid and .hale_json, add back another uuid and .hale_json
        bad_show_url = "#{show_url[0...-46]}#{SecureRandom.uuid}.hale_json"

        response = get bad_show_url
        expect(response.status).to eq(404)
        expect(parse_hale(response.body).properties.keys).to match_array(error_properties)
      end

    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Web;

namespace U4ieServer {
    class Program {
        static string DDNS_UPDATE { get { return "https://ieserver.net/cgi-bin/dip.cgi"; } }
        static string REMOTE_ADDR_CHK { get { return "https://ieserver.net/ipcheck.shtml"; } }

        static void Main(string[] args) {
            if (args.Length < 3) {
                Console.Error.WriteLine("U4ieServer account domain password ");
                Environment.Exit(1);
            }

            WebClient wc = new WebClient();
            try {
                String myip = wc.DownloadString(REMOTE_ADDR_CHK);
                if (myip.Trim().Length == 0)
                    Environment.Exit(3);
                byte[] bin = wc.DownloadData(DDNS_UPDATE + "?username=" + HttpUtility.UrlEncode(args[0]) + "&domain=" + HttpUtility.UrlEncode(args[1]) + "&password=" + HttpUtility.UrlEncode(args[2]) + "&updatehost=1");
                String html = Encoding.GetEncoding("euc-jp").GetString(bin);
                if (html.Contains(myip)) {
                    return;
                }
                Environment.Exit(4);
            }
            catch (WebException) {
                Environment.Exit(2);
            }
        }
    }
}


text:
package com.kosbuild.remoteemulator;

import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author sad
 */
public class ByteArrayParserFormatter {

    private ByteArrayInputStream inputStream;
    private ByteArrayFormatter formatter;

    public ByteArrayParserFormatter(byte[] array) {
        inputStream = new ByteArrayInputStream(array);
        formatter=new ByteArrayFormatter(100);
    }

    public byte[] receive(int count) throws IOException {
        byte[] buffer = new byte[count];
        for (int i = 0; i < count; i++) {
            buffer[i] = (byte) inputStream.read();
        }
        return buffer;
    }

    public boolean receiveBoolean() throws IOException {
        return receiveInt() == 1;
    }

    public int receiveInt() throws IOException {
        return fromByteArray(receive(4));
    }

    public long receiveLong() throws IOException {
        return fromByteArrayLong(receive(8));
    }

    public String receiveString() throws IOException {
        int sizeOfBuffer = receiveInt();
        return new String(receive(sizeOfBuffer), StandardCharsets.UTF_8);
    }

    public int fromByteArray(byte[] bytes) {
        return bytes[0] << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF);
    }

    public static long fromByteArrayLong(byte[] b) {
        long result = 0;
        for (int i = 0; i < 8; i++) {
            result <<= 8;
            result |= (b[i] & 0xFF);
        }
        return result;
    }

    public void sendString(String string) throws IOException {
        formatter.sendString(string);
    }

    public void sendBoolean(boolean value) throws IOException {
        formatter.sendBoolean(value);
    }

    public void sendInt(int value) throws IOException {
        formatter.sendInt(value);
    }

    public void sendLong(long value) throws IOException {
        formatter.sendLong(value);
    }

    public void sendRaw(byte[] buffer) throws IOException {
        formatter.sendRaw(buffer);
    }

    public byte[] getBytes() {
        return formatter.getBytes();
    }

}


text:
@interface AreaView : UIView

@end


text:
<?php
   /*
   Nagios Operations Dashboard
   Pat O'Brien https://obrienlabs.net
   Description: Displays a quick glance overview of the environment. Requires MK Livestatus.
   Version: config.php -> DASHBOARD_VERSION
   */

require_once( "../functions.php" );

?>

Los Angeles, CA

				<?php get_weather('la'); ?>
				<?php get_location_time('America/Los_Angeles'); ?>

Chicago, IL

				<?php get_weather('chicago'); ?>
				<?php get_location_time('America/Chicago'); ?>

Springfield, MA

				<?php get_weather('springfield'); ?>
				<?php get_location_time('America/New_York'); ?>

London, UK

				<?php get_weather('london'); ?>
				<?php get_location_time('Europe/London'); ?>

Hong Kong, CN

				<?php get_weather('hongkong'); ?>
				<?php get_location_time('Asia/Hong_Kong'); ?>

Tokyo, Japan

				<?php get_weather('tokyo'); ?>
				<?php get_location_time('Asia/Tokyo'); ?>

Sydney, AU

				<?php get_weather('sydney'); ?>
				<?php get_location_time('Australia/Sydney'); ?>


text:
Land Use simulation package for VisionEval
This package contains a number of modules that work in the VisionEval framework to calculate land use characteristics.

See [Getting Started](https://github.com/gregorbj/VisionEval/wiki/Getting-Started)