text:
package com.linecorp.armeria.client;

import static com.linecorp.armeria.client.ClientFactoryBuilder.MIN_PING_INTERVAL_MILLIS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;

import java.util.Map;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIfSystemProperty;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

import com.linecorp.armeria.common.Flags;
import com.linecorp.armeria.internal.common.util.BouncyCastleKeyFactoryProvider;

import io.netty.channel.ChannelOption;
import io.netty.resolver.DefaultAddressResolverGroup;

class ClientFactoryBuilderTest {

    @Test
    void addressResolverGroupFactoryAndDomainNameResolverCustomizerAreMutuallyExclusive() {
        final ClientFactoryBuilder builder1 = ClientFactory.builder();
        builder1.addressResolverGroupFactory(eventLoopGroup -> null);
        assertThatThrownBy(() -> builder1.domainNameResolverCustomizer(b -> {}))
                .isInstanceOf(IllegalStateException.class)
                .hasMessageContaining("mutually exclusive");

        final ClientFactoryBuilder builder2 = ClientFactory.builder();
        builder2.domainNameResolverCustomizer(b -> {});
        assertThatThrownBy(() -> builder2.addressResolverGroupFactory(eventLoopGroup -> null))
                .isInstanceOf(IllegalStateException.class)
                .hasMessageContaining("mutually exclusive");
    }

    @Test
    void maxNumEventLoopsAndEventLoopSchedulerFactoryAreMutuallyExclusive() {
        final ClientFactoryBuilder builder1 = ClientFactory.builder();
        builder1.maxNumEventLoopsPerEndpoint(2);

        assertThatThrownBy(() -> builder1.eventLoopSchedulerFactory(
                eventLoopGroup -> mock(EventLoopScheduler.class))).isInstanceOf(IllegalStateException.class);

        final ClientFactoryBuilder builder2 = ClientFactory.builder();
        builder2.eventLoopSchedulerFactory(eventLoopGroup -> mock(EventLoopScheduler.class));

        assertThatThrownBy(() -> builder2.maxNumEventLoopsPerEndpoint(2))
                .isInstanceOf(IllegalStateException.class)
                .hasMessageContaining("mutually exclusive");
    }

    @Test
    void shouldInheritClientFactoryOptions() {
        final ClientFactory factory1 = ClientFactory.builder()
                                                    .maxNumEventLoopsPerEndpoint(2)
                                                    .connectTimeoutMillis(5000)
                                                    .build();

        final ClientFactory factory2 = ClientFactory.builder()
                                                    .options(factory1.options())
                                                    .idleTimeoutMillis(30000)
                                                    .build();

        final ClientFactoryOptions factory1Option = factory1.options();
        final ClientFactoryOptions factory2Option = factory2.options();
        for (ClientFactoryOptionValue<?> optionValue : factory2.options()) {
            final ClientFactoryOption<?> option = optionValue.option();
            if (option.compareTo(ClientFactoryOption.IDLE_TIMEOUT_MILLIS) == 0) {
                assertThat(factory1Option.get(option)).isNotEqualTo(factory2Option.get(option));
            } else {
                assertThat(factory1Option.get(option)).isEqualTo(factory2Option.get(option));
            }
        }
    }

    @Test
    void shouldPreserveChannelOptionInClientFactory() {
        final ClientFactory factory = ClientFactory.builder()
                .options(ClientFactoryOptions.of())
                .build();
        final Map<ChannelOption<?>, Object> channelOptions =
                factory.options().get(ClientFactoryOption.CHANNEL_OPTIONS);
        final int connectTimeoutMillis = (int) channelOptions.get(ChannelOption.CONNECT_TIMEOUT_MILLIS);
        assertThat(connectTimeoutMillis).isEqualTo(Flags.defaultConnectTimeoutMillis());
    }

    @Test
    @EnabledIfSystemProperty(named = "com.linecorp.armeria.useJdkDnsResolver", matches = "true")
    void useDefaultAddressResolverGroup() {
        final DefaultClientFactory clientFactory = (DefaultClientFactory) ClientFactory.ofDefault();
        assertThat(clientFactory.addressResolverGroup()).isSameAs(DefaultAddressResolverGroup.INSTANCE);
    }

    @Test
    @DisabledIfSystemProperty(named = "com.linecorp.armeria.useJdkDnsResolver",  matches = "true")
    void useRefreshingAddressResolverGroup() {
        final DefaultClientFactory clientFactory = (DefaultClientFactory) ClientFactory.ofDefault();
        assertThat(clientFactory.addressResolverGroup()).isInstanceOf(RefreshingAddressResolverGroup.class);
    }

    @ParameterizedTest
    @CsvSource({ "pkcs5.key", "pkcs8.key" })
    void shouldAllowPkcsPrivateKeys(String privateKeyPath) {
        final String resourceRoot =
                '/' + BouncyCastleKeyFactoryProvider.class.getPackage().getName().replace('.', '/') + '/';
        ClientFactory.builder().tlsCustomizer(sslCtxBuilder -> {
            sslCtxBuilder.keyManager(
                    getClass().getResourceAsStream(resourceRoot + "test.crt"),
                    getClass().getResourceAsStream(resourceRoot + privateKeyPath));
        }).build();
    }

    @Test
    void positivePingIntervalShouldBeGreaterThan10seconds() {
        final ClientFactory factory1 = ClientFactory.builder()
                                                    .idleTimeoutMillis(10000)
                                                    .pingIntervalMillis(0)
                                                    .build();
        assertThat(factory1.options().idleTimeoutMillis()).isEqualTo(10000);
        assertThat(factory1.options().pingIntervalMillis()).isEqualTo(0);

        assertThatThrownBy(() -> {
            ClientFactory.builder()
                         .idleTimeoutMillis(10000)
                         .pingIntervalMillis(5000)
                         .build();
        }).isInstanceOf(IllegalArgumentException.class)
          .hasMessageContaining("(expected: >= " + MIN_PING_INTERVAL_MILLIS + " or == 0)");

        final ClientFactory factory3 = ClientFactory.builder()
                                                    .idleTimeoutMillis(10000)
                                                    .pingIntervalMillis(15000)
                                                    .build();
        assertThat(factory3.options().idleTimeoutMillis()).isEqualTo(10000);
        assertThat(factory3.options().pingIntervalMillis()).isEqualTo(0);

        final ClientFactory factory4 = ClientFactory.builder()
                                                    .idleTimeoutMillis(15000)
                                                    .pingIntervalMillis(10000)
                                                    .build();
        assertThat(factory4.options().idleTimeoutMillis()).isEqualTo(15000);
        assertThat(factory4.options().pingIntervalMillis()).isEqualTo(10000);

        final ClientFactory factory5 = ClientFactory.builder()
                                                    .idleTimeoutMillis(15000)
                                                    .pingIntervalMillis(12000)
                                                    .build();
        assertThat(factory5.options().idleTimeoutMillis()).isEqualTo(15000);
        assertThat(factory5.options().pingIntervalMillis()).isEqualTo(12000);
    }

    @CsvSource({
            "0,     10000",
            "15000, 20000",
            "20000, 15000",
    })
    @ParameterizedTest
    void pingIntervalShouldBeLessThanIdleTimeout(long idleTimeoutMillis, long pingIntervalMillis) {
        final ClientFactory factory1 = ClientFactory.builder()
                                                    .idleTimeoutMillis(idleTimeoutMillis)
                                                    .pingIntervalMillis(pingIntervalMillis)
                                                    .build();
        assertThat(factory1.options().idleTimeoutMillis()).isEqualTo(idleTimeoutMillis);
        if (idleTimeoutMillis > 0 && pingIntervalMillis >= idleTimeoutMillis) {
            assertThat(factory1.options().pingIntervalMillis()).isEqualTo(0);
        } else {
            assertThat(factory1.options().pingIntervalMillis()).isEqualTo(pingIntervalMillis);
        }
    }
}


text:
Methods that follow JavaBean naming contract for accessors are
expected to have no side effects. The
recommended convention is to use a parameterless method whenever there are no parameters and the method have no side
effect. This convention supports the uniform access
principle, which says that client code should not be affected by a decision to implement an attribute as a field
or method.

* Refer to Programming in Scala, 10.3 Defining parameterless methods

redpajama_set_name: RedPajamaGithub


text:
import sys
from time import sleep
import subprocess
import math
import logging

# Initialize logging
logging.basicConfig(format='%(asctime)s [%(levelname)s] %(name)s - %(message)s', level=logging.WARNING)
lib_log = logging.getLogger( __name__ )

#lib_log.setLevel(logging.INFO)
lib_log.setLevel(logging.DEBUG)

# Global data
VSM_RESP_DELAY 		= 15
PORT_DELETE_DELAY 	= 2
NET_DELETE_DELAY 	= 2
USER_DELETE_DELAY	= 2
TENANT_DELETE_DELAY	= 2

# Create network profile depending on various parameters
def create_nw_profile( nw_prof_name, seg_type, **kwargs ):

    # Reference dictionary for specifying cmd options
    # There are many optional arguments available for
    # quantum cisco-network-profile-create command. Add more to the
    # reference dictionary as needed
    nw_prf_ref_dict = { 'tenant_id': "--tenant-id", 'sub_type': "--sub_type",
			'seg_range': "--segment_range", 'phys_nw': "--physical_network"}

    cmd = "quantum cisco-network-profile-create %s %s" % (nw_prof_name, seg_type)

    # Build the cmd string using ref dict above
    for arg, value in kwargs.items():

	cmd = cmd + " " + "".join( "%s %s" % ( nw_prf_ref_dict[ arg ], value ))

    lib_log.info( cmd )

    try:
        cmd_out = subprocess.check_output( cmd, shell=True, stderr=subprocess.STDOUT )
        lib_log.debug( "%s\n%s\n" % ( cmd, cmd_out ))
    except subprocess.CalledProcessError as err:
        lib_log.warning( "Something went wrong! \nreturncode - '%s'\ncmd - '%s'\noutput - %s" % ( err.returncode, err.cmd, err.output ))
        sys.exit(1)

    for line in cmd_out.split('\n'):
        temp = line.split('|')
        # We need to exclude the first line of the output which can not be split on '|'
        if len( temp ) > 1:
            # Extract the network guid from the output
            if temp[ 1 ].strip() == 'id':
                nw_prf_id = temp[ 2 ].strip()
                lib_log.info( "nw profile id:\n%s\n ", nw_prf_id )
                break

        else:
            continue

    lib_log.info( "nw profile id:\n%s\n ", nw_prf_id )
    return nw_prf_id

def get_policy_profiles():

    # Dictionary to maintain parsed policy profile guids and their names
    pp_table = {}

    try:
        cmd_out = subprocess.check_output( "quantum cisco-policy-profile-list", shell=True, stderr=subprocess.STDOUT )
        lib_log.debug( "quantum cisco-policy-profile-list\n%s\n" % cmd_out )
    except subprocess.CalledProcessError as err:
        lib_log.warning( "Something went wrong! \nreturncode - '%s'\ncmd - '%s'\noutput - %s" % ( err.returncode, err.cmd, err.output ))
        sys.exit(1)

    for line in cmd_out.split('\n'):
        temp = line.split('|')
        # We need to exclude the first line of the output which can not be split on '|'
        if len( temp ) > 1:
            # Extract the policy profile id and its name and add it into a dict
	    pp_guid = temp[ 1 ].strip( )
            pp_name = temp[ 2 ].strip( )
	    if pp_guid != 'id':
		pp_table[ pp_guid ] = pp_name

        else:
            continue

    lib_log.info( "Policy Profile Table:\n%s\n ", pp_table )
    return pp_table

# Given a policy name, this function will return the policy id
def get_policy_profile_id( policy_name, policy_table ):

    policy_id = ""

    # policy table must be a dict object created through get_policy_profiles
    if not isinstance( policy_table, dict ):
	lib_log.warning( "policy_table is not 'dict' object")
	return policy_id

    for key, value in policy_table.items():
	#lib_log.debug( "%s, %s" % (key, value) )
	if value == policy_name:
	    policy_id = key
	    lib_log.info( "policy_id: %s" % policy_id )
	    break

    return policy_id

def get_n1k_network_profiles():

    # Dictionary to maintain parsed network profile guids and their names
    nw_prf_table = {}

    try:
        cmd_out = subprocess.check_output( "quantum cisco-network-profile-list", shell=True, stderr=subprocess.STDOUT )
        lib_log.debug( "quantum cisco-network-profile-list\n%s\n" % cmd_out )
    except subprocess.CalledProcessError as err:
        lib_log.warning( "Something went wrong! \nreturncode - '%s'\ncmd - '%s'\noutput - %s" % ( err.returncode, err.cmd, err.output ))
        sys.exit(1)

    for line in cmd_out.split('\n'):
        temp = line.split('|')
        # We need to exclude the first line of the output which can not be split on '|'
        if len( temp ) > 1:
            # Extract the policy profile id and its name and add it into a dict
            np_guid = temp[ 1 ].strip( )
            np_name = temp[ 2 ].strip( )
            if np_guid != 'id':
                nw_prf_table[ np_guid ] = np_name

        else:
            continue

    lib_log.info( "Policy Profile Table:\n%s\n ", nw_prf_table )
    return nw_prf_table

# Given an n1k network policy name, this function will return the policy id
def get_n1k_nw_profile_id( nw_prf_name, nw_prf_table ):

    nw_prf_id = ""

    # policy table must be a dict object created through get_n1k_network_profiles
    if not isinstance( nw_prf_table, dict ):
        lib_log.warning( "nw_prf_table is not 'dict' object")
        return nw_prf_id

    for key, value in nw_prf_table.items():
        #lib_log.debug( "%s, %s" % (key, value) )
        if value == nw_prf_name:
            nw_prf_id = key
            lib_log.info( "nw_prf_id: %s" % nw_prf_id )
            return nw_prf_id

# Returns a list of all quantum n1k network profile ids for quantum networks on the system
def get_nw_prf_ids( nw_prf_table ):

    nw_prf_id_list = []

    # nw_prf_table  must be a dict object created through get_n1k_network_profiles
    if not isinstance( nw_prf_table, dict ):
        lib_log.warning( "nw_prf_table is not 'dict' object")
        return nw_prf_id_list

    # Get all the nw_prf_id from the nw_prf_table
    for nw_prf_id in nw_prf_table:
        # If dhcp ports have to be excluded then just return all the port ids
        nw_prf_id_list.append( nw_prf_id )

    lib_log.info( "Quantum network profile id list:\n %s" % nw_prf_id_list )
    return nw_prf_id_list

# Function to delete quantum network profiles
def delete_n1k_nw_profiles( ):

    quantum_nw_prf_list = []

    # First get the net profile ids
    nw_prf_table = get_n1k_network_profiles()

    if len( nw_prf_table ) == 0:
        lib_log.info( "nw_prf_table is perhaps empty. No network profiles to delete on the system" )
        return

    # Get the list of network profiles
    quantum_nw_prf_list = get_nw_prf_ids( nw_prf_table )
    if len( quantum_nw_prf_list ) == 0:
        lib_log.info( "quantum_nw_prf_list is empty. No network profiles to delete on the system" )
        return

    # Delete ports one by one
    for nw_prf in quantum_nw_prf_list:

        # Set the number of attempts
        num_attempts = 2
        cmd = "quantum cisco-network-profile-delete %s" % nw_prf

        # Due to a known issue with VSM, sometimes profile delete fails, we retry after 30
        # seconds
        while num_attempts >= 1 :

            # Execute net-delete command
            try:
                lib_log.info( "\nDeleting n1k network profile %s" % nw_prf )
                cmd_out = subprocess.check_output( cmd, shell=True, stderr=subprocess.STDOUT )
                lib_log.debug( "%s\n%s" % ( cmd, cmd_out ))
                sleep( NET_DELETE_DELAY )
                break

            except subprocess.CalledProcessError as err:
                lib_log.warning( "Something went wrong! \nreturncode - '%s'\ncmd - '%s'\noutput - %s" % ( err.returncode, err.cmd, err.output ))
                num_attempts = num_attempts - 1
                if num_attempts != 0:
                    lib_log.warning( "Retrying after waiting for %s seconds.." % VSM_RESP_DELAY )
                    sleep( VSM_RESP_DELAY )
            else:
                # If try clause succeeds then parse the cmd_out
                if cmd_out.count( "Deleted network_profile" ) == 1:
                    lib_log.info( "quantum n1k network profile %s deleted" % nw_prf )
                else:
                    lib_log.warning( "quantum n1k network profile %s may not have been deleted. Check quantum cisco-network-profile-list output" % nw_prf )
        else:
            lib_log.warning( "Retrying quantum n1k network profile delete for %s did not work!" % nw_prf )

# Function to create a quantum network
def create_nw( nw_name, nw_prf_id, **kwargs ):

    net_id = ""

    # Set the number of attempts
    num_attempts = 2

    # Reference dictionary for specifying cmd options
    # There are many optional arguments available for
    # quantum net-create command. Add more to the
    # reference dictionary as needed
    nw_create_ref_dict = { 'tenant_id': "--tenant-id", 'admin_state': "--admin-state-down",
                        'shared': "--shared"}

    cmd = "quantum net-create %s --n1kv:profile_id %s" % ( nw_name, nw_prf_id )

    # Build the cmd string for optional args using ref dict above
    for arg, value in kwargs.items():

        cmd = cmd + " " + "".join( "%s %s" % ( nw_create_ref_dict[ arg ], value ))

    lib_log.info( cmd )

    # Due to a known issue with VSM, sometimes net-delete fails, we retry after 30
    # seconds
    while num_attempts >= 1 :
        # Execute the command
    	try:
            cmd_out = subprocess.check_output( cmd, shell=True, stderr=subprocess.STDOUT )
            lib_log.debug( "%s\n%s\n" % ( cmd, cmd_out ))
	except subprocess.CalledProcessError as err:
            lib_log.warning( "Something went wrong! \nreturncode - '%s'\ncmd - '%s'\noutput - %s" % ( err.returncode, err.cmd, err.output ))
            num_attempts = num_attempts - 1
            if num_attempts != 0:
                lib_log.warning( "Retrying after waiting for %s seconds.." % VSM_RESP_DELAY )
	    	sleep( VSM_RESP_DELAY )
        else:
	    # If try clause succeeds then parse the cmd_out
	    for line in cmd_out.split('\n'):
	        temp = line.split('|')
                # We need to exclude the first line of the output which can not be split on '|'
                if len( temp ) > 1:
	            # Extract the network guid from the output
        	    if temp[ 1 ].strip() == 'id':
                        net_id = temp[ 2 ].strip()
                        lib_log.debug( "Net id:\n%s\n ", net_id )
                        break

	    # Break out of the while loop
            break

    else:
	# Retries did not work, cant do much
        lib_log.warning( "Retrying quantum network create for %s did not work!. Returning from create_net" % nw_name )

    lib_log.info( "Net id:\n%s\n ", net_id )
    return net_id

def get_quantum_networks():

    # Dictionary to maintain parsed network guids and their names
    q_nw_table = {}

    try:
        cmd_out = subprocess.check_output( "quantum net-list", shell=True, stderr=subprocess.STDOUT )
        lib_log.debug( "quantum net-list\n%s\n" % cmd_out )
    except subprocess.CalledProcessError as err:
        lib_log.warning( "Something went wrong! \nreturncode - '%s'\ncmd - '%s'\noutput - %s" % ( err.returncode, err.cmd, err.output ))
        sys.exit(1)

    for line in cmd_out.split('\n'):
        temp = line.split('|')
        # We need to exclude the first line of the output which can not be split on '|'
        if len( temp ) > 1:
            # Extract the policy profile id and its name and add it into a dict
            net_guid = temp[ 1 ].strip( )
            net_name = temp[ 2 ].strip( )
            if net_guid != 'id':
                q_nw_table[ net_guid ] = net_name

        else:
            continue

    lib_log.info( "quantum networks Table:\n%s\n ", q_nw_table )
    return q_nw_table

# Given a quantum network name, this function will return the net id
def get_quantum_net_id( net_name, q_nw_table ):

    net_id = ""

    # quantum network table must be a dict object created through get_quantum_networks
    if not isinstance( q_nw_table, dict ):
        lib_log.warning( "q_nw_table is not 'dict' object")
        return net_id

    for key, value in q_nw_table.items():
       # lib_log.debug( "%s, %s" % (key, value) )
        if value == net_name:
            net_id = key
            lib_log.info( "net_id: %s" % net_id )
            return net_id

# Returns a list of all quantum net ids for quantum networks on the system
def get_net_ids( q_net_table ):

    q_net_id_list = []

    # q_net_table  must be a dict object created through get_quantum_networks
    if not isinstance( q_net_table, dict ):
        lib_log.warning( "q_net_table is not 'dict' object")
        return q_net_id_list

    # Get all the net_id from the q_net_table
    for net_id in q_net_table:
        # If dhcp ports have to be excluded then just return all the port ids
	q_net_id_list.append( net_id )

    lib_log.info( "Quantum net id list:\n %s" % q_net_id_list )
    return q_net_id_list

# Function to delete the created quantum networks
def delete_quantum_networks(  ):

    quantum_net_list = []

    # First get the net ids
    q_net_table = get_quantum_networks()

    if len( q_net_table ) == 0:
        lib_log.info( "q_net_table is perhaps empty. No networks to delete on the system" )
        return

    # Get the list of networks
    quantum_net_list = get_net_ids( q_net_table )
    if len( quantum_net_list ) == 0:
    	lib_log.info( "quantum_net_list is empty. No networks to delete on the system" )
        return

    # Delete ports one by one
    for net in quantum_net_list:

	# Set the number of attempts
        num_attempts = 2
        cmd = "quantum net-delete %s" % net

        # Due to a known issue with VSM, sometimes net-delete fails, we retry after 30
        # seconds
        while num_attempts >= 1 :

            # Execute net-delete command
            try:
                lib_log.info( "\nDeleting quantum network %s" % net )
                cmd_out = subprocess.check_output( cmd, shell=True, stderr=subprocess.STDOUT )
                lib_log.debug( "%s\n%s" % ( cmd, cmd_out ))
                sleep( NET_DELETE_DELAY )
                break

	    except subprocess.CalledProcessError as err:
                lib_log.warning( "Something went wrong! \nreturncode - '%s'\ncmd - '%s'\noutput - %s" % ( err.returncode, err.cmd, err.output ))
		num_attempts = num_attempts - 1
            	if num_attempts != 0:
                    lib_log.warning( "Retrying after waiting for %s seconds.." % VSM_RESP_DELAY )
                    sleep( VSM_RESP_DELAY )
            else:
                # If try clause succeeds then parse the cmd_out
                if cmd_out.count( "Deleted network" ) == 1:
                    lib_log.info( "quantum network %s deleted" % net )
                else:
                    lib_log.warning( "quantum network %s may not have been deleted. Check quantum net-list output" % net )
        else:
            lib_log.warning( "Retrying quantum network delete for %s did not work!" % net )

def create_subnet( nw_name, cidr, subnet_name, **kwargs ):

    subnet_id = ""

    # Set the number of attempts
    num_attempts = 2

    # Reference dictionary for specifying cmd options
    # There are many optional arguments available for
    # quantum subnet-create command. Add more to the
    # reference dictionary as needed
    subnet_create_ref_dict = { 'tenant_id': "--tenant-id", 'ip_ver': "--ip-version",
		'dns_servers': "--dns-nameserver", 'gateway': "--gateway",
		'alloc_pool': "--allocation-pool", 'disable_dhcp': "--disable-dhcp" }

    cmd = "quantum subnet-create %s %s --name %s" % ( nw_name, cidr, subnet_name )

    # Build the cmd string for optional args using ref dict above
    for arg, value in kwargs.items():

        cmd = cmd + " " + "".join( "%s %s" % ( subnet_create_ref_dict[ arg ], value ))

    lib_log.info( cmd )

    # Due to a known issue with VSM, sometimes net-delete fails, we retry after 30
    # seconds
    while num_attempts >= 1 :

    	# Execute the command
    	try:
            cmd_out = subprocess.check_output( cmd, shell=True, stderr=subprocess.STDOUT )
            lib_log.debug( "%s\n%s\n" % ( cmd, cmd_out ))
    	except subprocess.CalledProcessError as err:
            lib_log.warning( "Something went wrong! \nreturncode - '%s'\ncmd - '%s'\noutput - %s" % ( err.returncode, err.cmd, err.output ))
            num_attempts = num_attempts - 1
            if num_attempts != 0:
                lib_log.warning( "Retrying after waiting for %s seconds.." % VSM_RESP_DELAY )
		sleep( VSM_RESP_DELAY )
        else:
	    # If try clause succeeds then parse the cmd_out
	    for line in cmd_out.split('\n'):
        	temp = line.split('|')
        	# We need to exclude the first line of the output which can not be split on '|'
        	if len( temp ) > 1:
            	    # Extract the subnet guid from the output
            	    if temp[ 1 ].strip() == 'id':
                        subnet_id = temp[ 2 ].strip()
                        lib_log.debug( "Subnet id:\n%s\n ", subnet_id )
                        break

	    # Break out of the while loop
            break

    else:
	# Retries did not work, cant do much
        lib_log.warning( "Retrying quantum subnet-create for %s did not work!. Returning from create_subnet" % subnet_name )

    lib_log.info( "Subnet id:\n%s\n ", subnet_id )
    return subnet_id

def get_quantum_subnets():

    # Dictionary to maintain parsed subnet guids, their names, cidr info and allocation pool infor
    q_subnet_table = {}

    try:
        cmd_out = subprocess.check_output( "quantum subnet-list", shell=True, stderr=subprocess.STDOUT )
        lib_log.debug( "quantum subnet-list\n%s\n" % cmd_out )
    except subprocess.CalledProcessError as err:
        lib_log.warning( "Something went wrong! \nreturncode - '%s'\ncmd - '%s'\noutput - %s" % ( err.returncode, err.cmd, err.output ))
        sys.exit(1)

    for line in cmd_out.split('\n'):
        temp = line.split('|')
        # We need to exclude the first line of the output which can not be split on '|'
        if len( temp ) > 1:
            # Extract the subnet id,its name, cidr info and allocation pool
            subnet_guid = temp[ 1 ].strip( )
            if subnet_guid != 'id':
		subnet_name = temp[ 2 ].strip( )
            	subnet_cidr = temp[ 3 ].strip( )
            	subnet_alloc_pool =  eval( temp[ 4 ].strip( ) )
                q_subnet_table[ subnet_guid ] = {'name':subnet_name, 'cidr':subnet_cidr, 'alloc_pool':subnet_alloc_pool}

        else:
            continue

    lib_log.info( "quantum subnets Table:\n%s\n ", q_subnet_table )
    return q_subnet_table

# Given a quantum subnet name, this function will return the subnet id
def get_quantum_subnet_id( subnet_name, q_subnet_table ):

    subnet_id = ""

    # quantum subnet table must be a dict object created through get_quantum_subnets
    if not isinstance( q_subnet_table, dict ):
        lib_log.warning( "q_subnet_table is not 'dict' object")
        return net_id

    for key, value in q_subnet_table.items():
       # lib_log.debug( "%s, %s" % (key, value) )
        if value[ 'name' ] == subnet_name:
            subnet_id = key
            lib_log.info( "subnet_id: %s" % subnet_id )
            return subnet_id

# Returns a list of all quantum subnet ids for quantum networks on the system
def get_subnet_ids( q_subnet_table ):

    q_subnet_id_list = []

    # q_net_table  must be a dict object created through get_quantum_networks
    if not isinstance( q_subnet_table, dict ):
        lib_log.warning( "q_subnet_table is not 'dict' object")
        return q_subnet_id_list

    # Get all the subnet_id from the q_subnet_table
    for subnet_id in q_subnet_table:
        # Just iterate and append to the list
        q_subnet_id_list.append( subnet_id )

    lib_log.info( "Quantum subnet id list:\n %s" % q_subnet_id_list )
    return q_subnet_id_list

# Function to delete the created quantum networks
def delete_quantum_subnets(  ):

    quantum_subnet_list = []

    # First get the subnet ids
    q_subnet_table = get_quantum_subnets()

    if len( q_subnet_table ) == 0:
        lib_log.info( "q_subnet_table is perhaps empty. No subnets to delete on the system" )
        return

    # Get the list of networks
    quantum_subnet_list = get_subnet_ids( q_subnet_table )
    if len( quantum_subnet_list ) == 0:
        lib_log.info( "quantum_subnet_list is empty. No subnets to delete on the system" )
        return

    # Delete ports one by one
    for subnet in quantum_subnet_list:

        cmd = "quantum subnet-delete %s" % subnet

	# Set the number of attempts
        num_attempts = 2

        # Due to a known issue with VSM, sometimes subnet-delete fails, we retry after 30
        # seconds
        while num_attempts >= 1 :

            # Execute net-delete command
            try:
                lib_log.info( "\nDeleting quantum subnet %s" % subnet )
                cmd_out = subprocess.check_output( cmd, shell=True, stderr=subprocess.STDOUT )
                lib_log.debug( "%s\n%s" % ( cmd, cmd_out ))
                sleep( NET_DELETE_DELAY )
            except subprocess.CalledProcessError as err:
                lib_log.warning( "Something went wrong! \nreturncode - '%s'\ncmd - '%s'\noutput - %s" % ( err.returncode, err.cmd, err.output ))
		num_attempts = num_attempts - 1
            	if num_attempts != 0:
                    lib_log.warning( "Retrying after waiting for %s seconds.." % VSM_RESP_DELAY )
                    sleep( VSM_RESP_DELAY )
            else:
                # If try clause succeeds then parse the cmd_out
                if cmd_out.count( "Deleted subnet" ) == 1:
                    lib_log.info( "quantum subnet %s deleted" % subnet )
		else:
                    lib_log.warning( "quantum subnet %s may not have been deleted. Check quantum subnet-list output" % subnet )
		break
        else:
            lib_log.warning( "Retrying quantum subnet delete for %s did not work!. Continuing with remaining subnets" % subnet )

def create_port( nw_name, pp_prf_id, **kwargs ):

    port_id = ""
    num_attempts = 2

    # Reference dictionary for specifying cmd options
    # There are many optional arguments available for
    # quantum port-create command. Add more to the
    # reference dictionary as needed
    port_create_ref_dict = { 'tenant_id': "--tenant-id", 'port_name':"--name", 'admin_state': "--admin-state-down",
                           'mac_addr': "--mac-address", 'fixed_ip':"--fixed-ip"}

    cmd = "quantum port-create %s --n1kv:profile_id %s" % ( nw_name, pp_prf_id )

    # Build the cmd string for optional args using ref dict above
    for arg, value in kwargs.items():

        cmd = cmd + " " + "".join( "%s %s" % ( port_create_ref_dict[ arg ], value ))

    lib_log.info( cmd )

    # Due to a known issue with VSM, sometimes port-create fails, we retry after 30
    # seconds
    while num_attempts >= 1 :

	# Execute port-create command
	try:
            cmd_out = subprocess.check_output( cmd, shell=True, stderr=subprocess.STDOUT )
            lib_log.debug( "%s\n%s\n" % ( cmd, cmd_out ))
	except subprocess.CalledProcessError as err:
            lib_log.warning( "Something went wrong! \nreturncode - '%s'\ncmd - '%s'\noutput - %s" % ( err.returncode, err.cmd, err.output ))
	    num_attempts = num_attempts - 1
	    if num_attempts != 0:
		lib_log.warning( "Retrying after waiting for %s seconds.." % VSM_RESP_DELAY )
	    	sleep( VSM_RESP_DELAY )
	else:
	    # If try clause succeeds then parse the cmd_out
	    for line in cmd_out.split('\n'):
		temp = line.split('|')
	        # We need to exclude the first line of the output which can not be split on '|'
        	if len( temp ) > 1:
	            # Extract the network guid from the output
	            if temp[ 1 ].strip() == 'id':
	                port_id = temp[ 2 ].strip()
	                lib_log.debug( "Port id:\n%s\n ", port_id )
	                break

	    # Break out of the while loop
	    break
    else:
	# Retries did not work, cant do much
	lib_log.warning( "Retry did not work! returning from create_port" )

    lib_log.info( "Port id:\n%s\n ", port_id )
    return port_id

# Dictionary to maintain parsed port_ids, subnet and ip_address information
def get_port_info_table():

    # Dictionary to maintain parsed port_ids, subnet and ip_address information
    port_info_table = {}

    try:
        cmd_out = subprocess.check_output( "quantum port-list", shell=True, stderr=subprocess.STDOUT )
        lib_log.debug( "quantum port-list\n%s\n" % cmd_out )
    except subprocess.CalledProcessError as err:
        lib_log.warning( "Something went wrong! \nreturncode - '%s'\ncmd - '%s'\noutput - %s" % ( err.returncode, err.cmd, err.output ))
        sys.exit(1)

    for line in cmd_out.split('\n'):
        temp = line.split('|')
        # We need to exclude the first line of the output which can not be split on '|'
        if len( temp ) > 1:
            # Extract the port id as key, subnet id and ip address of the port as value
	    #  into the table
            p_guid = temp[ 1 ].strip( )
            if p_guid != 'id':
		subnet_ip_info = eval( temp[ 4 ].strip( ) )
                port_info_table[ p_guid ] = subnet_ip_info

        else:
            continue

    lib_log.debug( "quantum port, subnet and ip Table:\n%s\n ", port_info_table )
    return port_info_table

# Returns a list of quantum ports. Use exclude_dhcp_ports flag
# to specify whether you want dhcp port ids as well.
# Default is to exclude dhcp port ids
def get_port_ids( port_info_table, exclude_dhcp_ports=True ):

    port_id_list = []

    if not isinstance( exclude_dhcp_ports, bool ):
	lib_log.warning( "exclude_dhcp_ports must be 'bool' type" )
	lib_log.warning( "setting it to default value 'True'" )
	exclude_dhcp_ports = True

    # port_id_table  must be a dict object created through get_quantum_networks
    if not isinstance( port_info_table, dict ):
        lib_log.warning( "port_info_table is not 'dict' object")
        return port_id_list

    for port_id, subnet_ip_info in port_info_table.items():
	# If dhcp ports have to be excluded then just return all the port ids
	if not exclude_dhcp_ports:
	    port_id_list.append( port_id )
	# Else exclude dhcp ports from the list
	else:
	    # From value, extract the ip address and check if its
	    # a dhcp address (x.x.x.2)
	    ip_addr = subnet_ip_info[ 'ip_address'].split('.')
	    # If its not a dhcp port, then add the port id to the list
	    if int( ip_addr[ 3 ] ) != 2:
		port_id_list.append( port_id )
	    else:
		continue

    lib_log.info( "Port id list:\n %s" % port_id_list )
    return port_id_list

# Dictionary to maintain ip_address (of a port) and its associated port mapping
# !! In case you are using multiple subnets with same ip address range (since it is
# permitted my quantum using ip netns) this funtion will not work as expected!!
def get_ip_addr_port_table( port_info_table, exclude_dhcp_ports=True ):

    ip_addr_port_table = {}

    if not isinstance( exclude_dhcp_ports, bool ):
        lib_log.warning( "exclude_dhcp_ports must be 'bool' type" )
        lib_log.warning( "setting it to default value 'True'" )
        exclude_dhcp_ports = True

    # port_id_table  must be a dict object created through get_quantum_networks
    if not isinstance( port_info_table, dict ):
        lib_log.warning( "port_info_table is not 'dict' object")
        return ip_addr_port_table

    # Get the port list
    port_list = get_port_ids( port_info_table, exclude_dhcp_ports )

    for port_id in port_list:

	ip_address = port_info_table[ port_id ][ 'ip_address' ]
	ip_addr_port_table[ ip_address ] = port_id

    lib_log.debug( "quantum ip address and port Table:\n%s\n ", ip_addr_port_table )
    return ip_addr_port_table

# Function to delete the created quantum ports
def delete_quantum_ports( exclude_dhcp_ports=True ):

    port_id_list = []

    # First get the port table
    port_info_table = get_port_info_table()

    if len( port_info_table ) == 0:
	lib_log.info( "port_info_table is perhaps empty. No ports to delete on the system" )
	return

    # Get the list of ports
    port_id_list = get_port_ids( port_info_table, exclude_dhcp_ports )
    if len( port_id_list ) == 0:
	if exclude_dhcp_ports:
	    lib_log.info( "port_id_list is empty. No ports to delete on the system" )
	    lib_log.info( "However since exclude_dhcp_ports is True, dhcp ports were not deleted" )
	    lib_log.info( "If you wish to delete dhcp ports, set exclude_dhcp_ports to False" \
			  " and run the script again" )
	else:
	    lib_log.info( "port_id_list is empty. No ports to delete on the system" )

        return

    # Delete ports one by one
    for port in port_id_list:

	# Set the number of attempts
	num_attempts = 2

	cmd = "quantum port-delete %s" % port

	# Due to a known issue with VSM, sometimes port-delete fails, we retry after 30
    	# seconds
    	while num_attempts >= 1 :

      	    # Execute port-delete command
            try:
		lib_log.info( "\nDeleting port %s" % port )
                cmd_out = subprocess.check_output( cmd, shell=True, stderr=subprocess.STDOUT )
            	lib_log.debug( "%s\n%s" % ( cmd, cmd_out ))
		sleep( PORT_DELETE_DELAY )
            except subprocess.CalledProcessError as err:
            	lib_log.warning( "Something went wrong! \nreturncode - '%s'\ncmd - '%s'\noutput - %s" % ( err.returncode, err.cmd, err.output ))
 	   	num_attempts = num_attempts - 1
		if num_attempts != 0:
		    lib_log.warning( "Retrying after waiting for %s seconds.." % VSM_RESP_DELAY )
            	    sleep( VSM_RESP_DELAY )
            else:
            	# If try clause succeeds then parse the cmd_out
		if cmd_out.count( "Deleted port" ) == 1:
		    lib_log.info( "Port %s deleted\n" % port )
 		else:
		    lib_log.warning( "Port %s may not have been deleted. Check quantum port-list output\n" % port )
		break
     	else:
	    lib_log.warning( "Retrying port delete for %s did not work!. Continuing with remaining ports\n" % port )

def get_keystone_tenants():
    # Returns the keystone tenant ids and names on the system in a python dict

    tenant_table = {}

    try:
        cmd_out = subprocess.check_output( "keystone tenant-list", shell=True, stderr=subprocess.STDOUT )
        lib_log.debug( "keystone tenant-list\n%s\n" % cmd_out )
    except subprocess.CalledProcessError as err:
        lib_log.warning( "Something went wrong! \nreturncode - '%s'\ncmd - '%s'\noutput - %s" % ( err.returncode, err.cmd, err.output ))
        sys.exit(1)

    for line in cmd_out.split('\n'):
        temp = line.split('|')
        # We need to exclude the first line of the output which can not be split on '|'
        if len( temp ) > 1:
	    # Extract the tenant id and tenant name
	    tenant_id =  temp[ 1 ].strip( )
	    tenant_name = temp[ 2 ].strip( )

            # From the list we need to remove 'id' title
            if tenant_id != 'id':
                tenant_table[ tenant_id ] = tenant_name

        else:
            continue

    lib_log.info( "Tenant table:\n%s\n ", tenant_table )
    return tenant_table

# Given a keystone tenant name, this function will return its id
def get_tenant_id( tenant_name, tenant_table ):

    tenant_id = ""

    # tenant table must be a dict object created through get_keystone_tenants
    if not isinstance( tenant_table, dict ):
        lib_log.warning( "tenant_table is not 'dict' object")
        return tenant_id

    for key, value in tenant_table.items():
        #lib_log.debug( "%s, %s" % (key, value) )
        if value == tenant_name:
            tenant_id = key
            lib_log.info( "tenant_id: %s" % tenant_id )
            return tenant_id

def get_custom_tenant_names( tenant_table ):
    # Returns the user created keystone tenants (excludes 'admin' and services')
    # on the system as a python list

    tenant_names_list = []

    # tenant table must be a dict object created through get_keystone_tenants
    if not isinstance( tenant_table, dict ):
        lib_log.warning( "tenant_table is not 'dict' object")
        return tenant_names_list

    for key, value in tenant_table.items():
        lib_log.debug( "Inside get_custom_tenant_names:\n%s, %s" % (key, value) )
        if value != 'admin' and value != 'services':
            tenant_names_list.append( value )

    tenant_names_list.sort()
    lib_log.info( "tenant_names_list: %s" % tenant_names_list )
    return tenant_names_list

# Returns a list of tenant ids for sorted tenant names list
def get_custom_tenant_ids( tenant_table ):

    # Returns the tenant ids for user created keystone tenants
    # (excludes 'admin' and services') on the system as a python list

    tenant_ids_list = []
    tenant_names_list = []

    # tenant table must be a dict object created through get_keystone_tenants
    if not isinstance( tenant_table, dict ):
        lib_log.warning( "tenant_table is not 'dict' object")
        return tenant_ids_list

    lib_log.debug("Inside get_custom_tenant_ids\n%s", tenant_table)

    # First get the sorted list of tenant names
    tenant_names_list = get_custom_tenant_names( tenant_table )

    for tenant_name in tenant_names_list:
	tenant_id = get_tenant_id( tenant_name, tenant_table )
	tenant_ids_list.append( tenant_id )

    return tenant_ids_list

# Returns a sorted list of user created keystone users
def get_keystone_users():

    user_list = []

    try:
        cmd_out = subprocess.check_output( "keystone user-list", stderr=subprocess.STDOUT, shell=True )
        lib_log.debug( "keystone user-list\n%s\n" % cmd_out )
    except subprocess.CalledProcessError as err:
        lib_log.warning( "Something went wrong! \nreturncode - '%s'\ncmd - '%s'\noutput - %s" % ( err.returncode, err.cmd, err.output ))
        sys.exit(1)

    for line in cmd_out.split('\n'):
        temp = line.split('|')
        # We need to exclude the first line of the output which can not be split on '|'
        if len( temp ) > 1:
            user =  temp[ 2 ].strip( )
            # From the list we need to exclude the users added by quantum, nova, glance etc services
            # We also need to remove 'name' row
            if user != 'name' and user != 'admin' and \
               user != 'quantum' and user != 'cinder' and \
               user != 'glance' and user != 'nova':
                user_list.append( user )
        else:
            continue

    # Sort the list
    user_list.sort()
    lib_log.info( "User list:\n%s\n ", user_list )
    return user_list

# Returns the dictionary of which users belong to a specific tenant-id
#'tenant_id': 'user-name'
def get_user_tenant_mappings():

    user_tenant_map = {}
    tenant_table = {}

    # Get the users list
    user_list = get_keystone_users()

    # Get the tenant table. It will be used to print tenant names once we have the user_tenant_map
    tenant_table = get_keystone_tenants()

    if len( user_list ) == 0:
	lib_log.warning( "User list is empty. Please check if there are any user created users on the system" )
	return

    for user in user_list:

        cmd = "keystone user-get %s" % user
	# Execute user-get command for each user
        try:
            cmd_out = subprocess.check_output( cmd, shell=True, stderr=subprocess.STDOUT )
            lib_log.debug( "%s\n%s\n" % ( cmd, cmd_out ))
        except subprocess.CalledProcessError as err:
            lib_log.warning( "Something went wrong! \nreturncode - '%s'\ncmd - '%s'\noutput - %s" % ( err.returncode, err.cmd, err.output ))
    	    sys.exit(1)

	# Parse the cmd_out
        for line in cmd_out.split('\n'):
            temp = line.split('|')
            # We need to exclude the first line of the output which can not be split on '|'
            if len( temp ) > 1:
            	# Extract the tenantId from the output
                if temp[ 1 ].strip() == 'tenantId':
                    tenant_id = temp[ 2 ].strip()
		    tenant_name = tenant_table[ tenant_id ]
                    lib_log.debug( "User %s belongs to tenant - '%s' (%s)\n " % ( user, tenant_name, tenant_id ))
		    user_tenant_map[ tenant_id ] = user
                    break

    lib_log.info( "user_tenant_map:\n%s\n" % user_tenant_map )
    return user_tenant_map

# Delete all the keystone users other than admin, quantum, nova, cinder and glance
def delete_keystone_users():

    # Get the users list
    user_list = get_keystone_users()

    for user in user_list:

	cmd = "keystone user-delete %s" % user

	# Execute user-delete command
        try:
            lib_log.info( "\nDeleting user %s" % user )
            cmd_out = subprocess.check_output( cmd, shell=True, stderr=subprocess.STDOUT )
            lib_log.debug( "%s\n%s" % ( cmd, cmd_out ))
            sleep( USER_DELETE_DELAY )
        except subprocess.CalledProcessError as err:
            lib_log.warning( "Something went wrong! \nreturncode - '%s'\ncmd - '%s'\noutput - %s" % ( err.returncode, err.cmd, err.output ))
        else:
            # If try clause succeeds then parse the cmd_out
            lib_log.info( "User %s deleted\n" % user )

# Delete all the keystone tenants other than admin
def delete_keystone_tenants():

    # Get the tenants table
    tenant_table = get_keystone_tenants()

    # Get the tenant names except admin and services
    tenant_list = get_custom_tenant_names( tenant_table )
    if len( tenant_list ) == 0:
	lib_log.info( "tenant_list is perhaps empty. No user created tenants to delete on the system" )
        return

    for tenant_name in tenant_list:

        cmd = "keystone tenant-delete %s" % tenant_name

        # Execute tenant-delete command
        try:
            lib_log.info( "Deleting tenant %s" % tenant_name )
            cmd_out = subprocess.check_output( cmd, shell=True, stderr=subprocess.STDOUT )
            lib_log.debug( "%s\n%s" % ( cmd, cmd_out ))
            sleep( TENANT_DELETE_DELAY )
        except subprocess.CalledProcessError as err:
            lib_log.warning( "Something went wrong! \nreturncode - '%s'\ncmd - '%s'\noutput - %s" % ( err.returncode, err.cmd, err.output ))
        else:
            # If try clause succeeds then parse the cmd_out
            lib_log.info( "Tenant %s deleted\n" % tenant_name )

# This method will delete all the quantum network data on the controller
# including quantum dhcp ports
def clean_up_quantum_data( exclude_dhcp_ports=False ):

    # Delete quantum ports
    delete_quantum_ports( exclude_dhcp_ports )
    # Delete all the subnets
    delete_quantum_subnets()
    # Delete all the networks
    delete_quantum_networks()
    # Delete all the network profiles
    delete_n1k_nw_profiles()

if __name__ == '__main__':
#    get_policy_profiles()
#    get_user_tenant_mappings()
    port_info_table = get_port_info_table()
    get_ip_addr_port_table( port_info_table, exclude_dhcp_ports=True )


text:
<?php

namespace mageekguy\atoum\tests\units\template;

use
	mageekguy\atoum,
	mageekguy\atoum\template
;

require_once __DIR__ . '/../../runner.php';

class tag extends atoum\test
{
	public function test__construct()
	{
		$this->assert
			->testedClass->isSubClassOf('mageekguy\atoum\template')
		;

		$this->assert
			->exception(function() {
					$template = new template\tag('');
					}
				)
				->isInstanceOf('mageekguy\atoum\exceptions\logic')
				->hasMessage('Tag must not be an empty string')
			->exception(function() {
					$template = new template\tag(uniqid(), null, 0);
					}
				)
				->isInstanceOf('mageekguy\atoum\exceptions\logic')
				->hasMessage('Line must be greater than 0')
			->exception(function() {
						$template = new template\tag(uniqid(), null, - rand(1, PHP_INT_MAX));
					}
				)
				->isInstanceOf('mageekguy\atoum\exceptions\logic')
				->hasMessage('Line must be greater than 0')
			->exception(function() {
						$template = new template\tag(uniqid(), null, rand(1, PHP_INT_MAX), 0);
					}
				)
				->isInstanceOf('mageekguy\atoum\exceptions\logic')
				->hasMessage('Offset must be greater than 0')
			->exception(function() {
					$template = new template\tag(uniqid(), null, rand(1, PHP_INT_MAX), - rand(1, PHP_INT_MAX));
					}
				)
				->isInstanceOf('mageekguy\atoum\exceptions\logic')
				->hasMessage('Offset must be greater than 0')
		;

		$template = new template\tag($tag = uniqid());

		$this->assert
			->string($template->getTag())->isEqualTo($tag)
			->string($template->getData())->isEmpty()
			->variable($template->getLine())->isNull()
			->variable($template->getOffset())->isNull()
		;

		$template = new template\tag($tag = uniqid(), $data = uniqid(), $line = rand(1, PHP_INT_MAX), $offset = rand(1, PHP_INT_MAX));

		$this->assert
			->string($template->getTag())->isEqualTo($tag)
			->string($template->getData())->isEqualTo($data)
			->integer($template->getLine())->isEqualTo($line)
			->integer($template->getOffset())->isEqualTo($offset)
		;
	}

	public function testSetId()
	{
		$template = new template\tag(uniqid());

		$this->assert
			->exception(function() use ($template) {
						$template->setId('');
					}
				)
				->isInstanceOf('mageekguy\atoum\exceptions\logic')
				->hasMessage('Id must not be empty')
		;

		$this->assert
			->object($template->setId($id = uniqid()))->isIdenticalTo($template)
			->string($template->getId())->isEqualTo($id)
			->object($template->setId($id = uniqid()))->isIdenticalTo($template)
			->string($template->getId())->isEqualTo($id)
		;

		$root = new template\tag(uniqid());
		$root
			->setId($id = uniqid())
			->addChild($template = new template\tag(uniqid()))
		;

		$this->assert
			->exception(function() use ($template, $id) {
						$template->setId($id);
					}
				)
				->isInstanceOf('mageekguy\atoum\exceptions\logic')
				->hasMessage('Id \'' . $id . '\' is already defined in line unknown at offset unknown')
		;
	}

	public function testUnsetId()
	{
		$template = new template\tag(uniqid());

		$this->assert
			->variable($template->getId())->isNull()
			->object($template->unsetId())->isIdenticalTo($template)
			->variable($template->getId())->isNull()
		;

		$template->setId(uniqid());

		$this->assert
			->variable($template->getId())->isNotNull()
			->object($template->unsetId())->isIdenticalTo($template)
			->variable($template->getId())->isNull()
		;
	}

	public function testSetAttribute()
	{
		$template = new template\tag(uniqid());

		$this->assert
			->variable($template->getId())->isNull()
			->object($template->setAttribute('id', $id = uniqid()))->isIdenticalTo($template)
			->string($template->getId())->isEqualTo($id)
			->exception(function() use ($template, & $attribute) {
						$template->setAttribute($attribute = uniqid(), uniqid());
					}
				)
				->isInstanceOf('mageekguy\atoum\exceptions\logic')
				->hasMessage('Attribute \'' . $attribute . '\' is unknown')
		;
	}

	public function testUnsetAttribute()
	{
		$template = new template\tag(uniqid());

		$template->setAttribute('id', $id = uniqid());

		$this->assert
			->string($template->getId())->isEqualTo($id)
			->object($template->unsetAttribute('id'))->isIdenticalTo($template)
			->variable($template->getId())->isNull()
			->exception(function() use ($template, & $attribute) {
						$template->unsetAttribute($attribute = uniqid());
					}
				)
				->isInstanceOf('mageekguy\atoum\exceptions\logic')
				->hasMessage('Attribute \'' . $attribute . '\' is unknown')
		;
	}
}


text:
package ssl

/**
* Binding class showing the ecccurve that can be bound to sslprofile.
*/
type Sslprofileecccurvebinding struct {
	/**
	* Named ECC curve bound to vserver/service.
	*/
	Ecccurvename string `json:"ecccurvename,omitempty"`
	/**
	* Name of the SSL profile.
	*/
	Name string `json:"name,omitempty"`
	/**
	* Priority of the cipher binding
	*/
	Cipherpriority int `json:"cipherpriority,omitempty"`

}


text:
import {SchematicTestRunner} from '@angular-devkit/schematics/testing';
import {join} from 'path';
import {Tree} from '@angular-devkit/schematics';
import {createTestApp} from '../utils/testing';
import {getFileContent} from '@schematics/angular/utility/test';

const collectionPath = join(__dirname, '../collection.json');

describe('material-nav-schematic', () => {
  let runner: SchematicTestRunner;
  const options = {
    name: 'foo',
    path: 'app',
    sourceDir: 'src',
    inlineStyle: false,
    inlineTemplate: false,
    changeDetection: 'Default',
    styleext: 'css',
    spec: true,
    module: undefined,
    export: false,
    prefix: undefined,
    viewEncapsulation: undefined,
  };

  beforeEach(() => {
    runner = new SchematicTestRunner('schematics', collectionPath);
  });

  it('should create nav files and add them to module', () => {
    const tree = runner.runSchematic('nav', { ...options }, createTestApp());
    const files = tree.files;

    expect(files).toContain('/src/app/foo/foo.component.css');
    expect(files).toContain('/src/app/foo/foo.component.html');
    expect(files).toContain('/src/app/foo/foo.component.spec.ts');
    expect(files).toContain('/src/app/foo/foo.component.ts');

    const moduleContent = getFileContent(tree, '/src/app/app.module.ts');
    expect(moduleContent).toMatch(/import.*Foo.*from '.\/foo\/foo.component'/);
    expect(moduleContent).toMatch(/declarations:\s*\[[^\]]+?,\r?\n\s+FooComponent\r?\n/m);
  });

  it('should add nav imports to module', () => {
    const tree = runner.runSchematic('nav', { ...options }, createTestApp());
    const moduleContent = getFileContent(tree, '/src/app/app.module.ts');

    expect(moduleContent).toContain('LayoutModule');
    expect(moduleContent).toContain('MatToolbarModule');
    expect(moduleContent).toContain('MatButtonModule');
    expect(moduleContent).toContain('MatSidenavModule');
    expect(moduleContent).toContain('MatIconModule');
    expect(moduleContent).toContain('MatListModule');

    expect(moduleContent).toContain(`import { LayoutModule } from '@angular/cdk/layout';`);
    expect(moduleContent).toContain(
      // tslint:disable-next-line
      `import { MatToolbarModule, MatButtonModule, MatSidenavModule, MatIconModule, MatListModule } from '@angular/material';`);
  });

});


text:
package com.ctrip.framework.apollo.portal.spi;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public interface LogoutHandler {

  void logout(HttpServletRequest request, HttpServletResponse response);

}


text:
package iso20022

// Provides additional information such as the registration details.
type CorporateActionNarrative21 struct {

	// Provides additional information or specifies in more detail the content of a message. This field may only be used when the information to be transmitted, cannot be coded.
	AdditionalText []*Max350Text `xml:"AddtlTxt,omitempty"`

	// Provides information that can be ignored for automated processing; - reiteration of information that has been included within structured fields of this message, - or narrative information not needed for automatic processing.
	NarrativeVersion []*Max350Text `xml:"NrrtvVrsn,omitempty"`

	// Provides information required for the registration.
	RegistrationDetails []*Max350Text `xml:"RegnDtls,omitempty"`

	// Provides additional information regarding the party, for example, the contact unit or person responsible for the transaction identified in the message.
	PartyContactNarrative []*Max350Text `xml:"PtyCtctNrrtv,omitempty"`

	// Disclaimer relative to the information provided in the message. It may be ignored for automated processing. No information about the instruction itself is allowed here.
	Disclaimer []*Max350Text `xml:"Dsclmr,omitempty"`

	// Provides additional information on the basket or index underlying a security, for example a warrant.
	BasketOrIndexInformation []*Max350Text `xml:"BsktOrIndxInf,omitempty"`

	// Provides information required for the certification/breakdown.
	CertificationBreakdown []*Max350Text `xml:"CertfctnBrkdwn,omitempty"`
}

func (c *CorporateActionNarrative21) AddAdditionalText(value string) {
	c.AdditionalText = append(c.AdditionalText, (*Max350Text)(&value))
}

func (c *CorporateActionNarrative21) AddNarrativeVersion(value string) {
	c.NarrativeVersion = append(c.NarrativeVersion, (*Max350Text)(&value))
}

func (c *CorporateActionNarrative21) AddRegistrationDetails(value string) {
	c.RegistrationDetails = append(c.RegistrationDetails, (*Max350Text)(&value))
}

func (c *CorporateActionNarrative21) AddPartyContactNarrative(value string) {
	c.PartyContactNarrative = append(c.PartyContactNarrative, (*Max350Text)(&value))
}

func (c *CorporateActionNarrative21) AddDisclaimer(value string) {
	c.Disclaimer = append(c.Disclaimer, (*Max350Text)(&value))
}

func (c *CorporateActionNarrative21) AddBasketOrIndexInformation(value string) {
	c.BasketOrIndexInformation = append(c.BasketOrIndexInformation, (*Max350Text)(&value))
}

func (c *CorporateActionNarrative21) AddCertificationBreakdown(value string) {
	c.CertificationBreakdown = append(c.CertificationBreakdown, (*Max350Text)(&value))
}


text:
<?php
	// Report Options
	if (!empty($_POST['projTimeFromDate'])) {
		$projTimeFromDate = $mysqli->real_escape_string($_POST['projTimeFromDate']);
	}
	if (!empty($_POST['projTimeToDate'])) {
		$projTimeToDate = $mysqli->real_escape_string($_POST['projTimeToDate']);
	}
	$projId = $mysqli->real_escape_string($_POST['projId']);

	// Output headers so that the file is downloaded rather than displayed
	header('Content-Type: text/csv; charset=utf-8');
	header('Content-Disposition: attachment; filename=exportProjectTime.csv');

	// Create a file pointer connected to the output stream
	$output = fopen('php://output', 'w');

	// Output the column headings
	fputcsv($output, array(
		$projectNameField,
		$managerText,
		$yearText,
		$weekNoText,
		$dateInText,
		$timeInText,
		$dateOutText,
		$timeOutText,
		$totalHoursText
	));

	// Get Data
	$sql = "SELECT
				timeclock.clockId,
				timeclock.projectId,
				timeclock.adminId,
				timeclock.weekNo,
				timeclock.clockYear,
				timeentry.entryId,
				timeentry.startTime,
				DATE_FORMAT(timeentry.startTime,'%M %d, %Y') AS dateStarted,
				DATE_FORMAT(timeentry.startTime,'%h:%i %p') AS hourStarted,
				timeentry.endTime,
				DATE_FORMAT(timeentry.endTime,'%M %d, %Y') AS dateEnded,
				DATE_FORMAT(timeentry.endTime,'%h:%i %p') AS hourEnded,
				UNIX_TIMESTAMP(timeentry.startTime) AS orderDate,
				clientprojects.projectName,
				CONCAT(admins.adminFirstName,' ',admins.adminLastName) AS theAdmin
			FROM
				timeclock
				LEFT JOIN timeentry ON timeclock.clockId = timeentry.clockId
				LEFT JOIN clientprojects ON timeclock.projectId = clientprojects.projectId
				LEFT JOIN admins ON timeclock.adminId = admins.adminId
			WHERE
				timeclock.projectId = ".$projId." AND
				timeentry.endTime != '0000-00-00 00:00:00' AND
				timeentry.startTime >= '".$projTimeFromDate."' AND timeentry.startTime <= '".$projTimeToDate."'
			ORDER BY timeclock.adminId, orderDate";
    $res = mysqli_query($mysqli, $sql) or die('-1' . mysqli_error());

	// Loop through the rows
	while ($row = mysqli_fetch_assoc($res)) {
		$items_array = array();

		// Get the Time Total for each Time Entry
		$tot = "SELECT timeentry.startTime, timeentry.endTime FROM timeentry WHERE entryId = ".$row['entryId'];
		$results = mysqli_query($mysqli, $tot) or die('-3'.mysqli_error());
		$rows = mysqli_fetch_assoc($results);

		// Convert it to HH:MM
		$from = new DateTime($rows['startTime']);
		$to = new DateTime($rows['endTime']);
		$lineTotal = $from->diff($to)->format('%h:%i');

		$items_array[] = clean($row['projectName']);
		$items_array[] = clean($row['theAdmin']);
		$items_array[] = $row['clockYear'];
		$items_array[] = $row['weekNo'];
		$items_array[] = $row['dateStarted'];
		$items_array[] = $row['hourStarted'];
		$items_array[] = $row['dateEnded'];
		$items_array[] = $row['hourEnded'];
		$items_array[] = $lineTotal;

		// Output the Data to the CSV
		fputcsv($output, $items_array);
	}
?>


text:
module UseCase

  class ValidatorParent < Base

    def call_failure(status, message = nil)
      if respond_to?(:failure!)
        failure!(status, message)
      else
        failure(status, message)
      end
    end

  end

end


text:
package org.drools.core.command.impl;

import org.kie.api.KieBase;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.command.Context;
import org.kie.internal.command.World;
import org.kie.api.runtime.ExecutionResults;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.process.WorkItemManager;
import org.kie.api.runtime.rule.EntryPoint;

public class FixedKnowledgeCommandContext
        implements
        KnowledgeCommandContext {

    private Context                  context;
    private KnowledgeBuilder         kbuilder;
    private KieBase                  kbase;
    private KieSession               kSession;
    private EntryPoint        workingMemoryEntryPoint;
    private ExecutionResults         kresults;

    public FixedKnowledgeCommandContext(Context context,
                                        KnowledgeBuilder kbuilder,
                                        KieBase kbase,
                                        KieSession statefulKsession,
                                        ExecutionResults kresults) {
        this.context = context;
        this.kbuilder = kbuilder;
        this.kbase = kbase;
        this.kSession = statefulKsession;
        this.kresults = kresults;
    }

    public FixedKnowledgeCommandContext(Context context,
                                        KnowledgeBuilder kbuilder,
                                        KieBase kbase,
                                        KieSession statefulKsession,
                                        EntryPoint workingMemoryEntryPoint,
                                        ExecutionResults kresults) {
        this( context,
              kbuilder,
              kbase,
              statefulKsession,
              kresults );
        this.workingMemoryEntryPoint = workingMemoryEntryPoint;
    }

    public KnowledgeBuilder getKnowledgeBuilder() {
        return kbuilder;
    }

    public KieBase getKieBase() {
        return this.kbase;
    }

    public KieSession getKieSession() {
        return kSession;
    }

    public WorkItemManager getWorkItemManager() {
        return kSession.getWorkItemManager();
    }

    public ExecutionResults getExecutionResults() {
        return this.kresults;
    }

    public EntryPoint getWorkingMemoryEntryPoint() {
        return workingMemoryEntryPoint;
    }

    public void setWorkingMemoryEntryPoint(EntryPoint workingMemoryEntryPoint) {
        this.workingMemoryEntryPoint = workingMemoryEntryPoint;
    }

    public void setKnowledgeBuilder(KnowledgeBuilder kbuilder) {
        this.kbuilder = kbuilder;
    }

    public void setKbase(KieBase kbase) {
        this.kbase = kbase;
    }

    public World getContextManager() {
        return context.getContextManager();
    }

    public String getName() {
        return context.getName();
    }

    public Object get(String identifier) {
        return context.get( identifier );
    }

    public void set(String identifier,
                    Object value) {
        context.set( identifier,
                     value );
    }

    public void remove(String name) {
        context.remove( name );
    }

}


text:
var glu = require('pex-glu');
var gen = require('pex-gen');
var geom = require('pex-geom');
var materials = require('pex-materials');
var color = require('pex-color');

var Color = color.Color;
var Mesh = glu.Mesh;
var LineBuilder = gen.LineBuilder;
var ShowColors = materials.ShowColors;
var Vec3 = geom.Vec3;

function PerspectiveCameraHelper(camera, options) {
  options = options || { };
  this.camera = camera;
  this.lineBuilder = new LineBuilder();

  this.update();
  Mesh.call(this, this.lineBuilder, new ShowColors(), { lines: true });
}

PerspectiveCameraHelper.prototype = Object.create(Mesh.prototype);

PerspectiveCameraHelper.prototype.update = function() {
  var camera = this.camera;
  this.lineBuilder.reset();

  var position = camera.getPosition();
  var target = camera.getTarget();

  var frustumNear = camera.getNear();
  var frustumFar = camera.getFar();
  var frustumTop = Math.tan(camera.getFov() / 180 * Math.PI / 2) * frustumNear;
  var frustumRight = frustumTop * camera.getAspectRatio();
  var frustumLeft = -frustumTop;
  var frustumBottom = -frustumLeft;

  var front = Vec3.create().asSub(camera.getTarget(), camera.getPosition()).normalize();
  var up = camera.getUp().clone();
  var right = Vec3.create().asCross(front, up).normalize();

  var frustumNearTopLeft     = right.dup().scale(-frustumRight).add(up.dup().scale( frustumTop)).add(front.dup().scale(frustumNear));
  var frustumNearTopRight    = right.dup().scale( frustumRight).add(up.dup().scale( frustumTop)).add(front.dup().scale(frustumNear));
  var frustumNearBottomRight = right.dup().scale( frustumRight).add(up.dup().scale(-frustumTop)).add(front.dup().scale(frustumNear));
  var frustumNearBottomLeft  = right.dup().scale(-frustumRight).add(up.dup().scale(-frustumTop)).add(front.dup().scale(frustumNear));

  var farNearRatio = frustumFar / frustumNear;

  var frustumFarTopLeft     = frustumNearTopLeft.dup().scale(farNearRatio);
  var frustumFarTopRight    = frustumNearTopRight.dup().scale(farNearRatio);
  var frustumFarBottomRight = frustumNearBottomRight.dup().scale(farNearRatio);
  var frustumFarBottomLeft  = frustumNearBottomLeft.dup().scale(farNearRatio);

  this.lineBuilder.addLine(position, position.dup().add(frustumFarTopLeft), Color.White);
  this.lineBuilder.addLine(position, position.dup().add(frustumFarTopRight), Color.White);
  this.lineBuilder.addLine(position, position.dup().add(frustumFarBottomRight), Color.White);
  this.lineBuilder.addLine(position, position.dup().add(frustumFarBottomLeft), Color.White);

  this.lineBuilder.addLine(position.dup().add(frustumNearTopLeft), position.dup().add(frustumNearTopRight), Color.White);
  this.lineBuilder.addLine(position.dup().add(frustumNearTopRight), position.dup().add(frustumNearBottomRight), Color.White);
  this.lineBuilder.addLine(position.dup().add(frustumNearBottomRight), position.dup().add(frustumNearBottomLeft), Color.White);
  this.lineBuilder.addLine(position.dup().add(frustumNearBottomLeft), position.dup().add(frustumNearTopLeft), Color.White);

  this.lineBuilder.addLine(position.dup().add(frustumFarTopLeft), position.dup().add(frustumFarTopRight), Color.White);
  this.lineBuilder.addLine(position.dup().add(frustumFarTopRight), position.dup().add(frustumFarBottomRight), Color.White);
  this.lineBuilder.addLine(position.dup().add(frustumFarBottomRight), position.dup().add(frustumFarBottomLeft), Color.White);
  this.lineBuilder.addLine(position.dup().add(frustumFarBottomLeft), position.dup().add(frustumFarTopLeft), Color.White);

  this.lineBuilder.addLine(camera.getPosition(), camera.getPosition().dup().add(right), Color.Red);
  this.lineBuilder.addLine(camera.getPosition(), camera.getPosition().dup().add(up), Color.Green);
  this.lineBuilder.addLine(camera.getPosition(), camera.getPosition().dup().add(front), Color.Blue);
}

PerspectiveCameraHelper.prototype.draw = function(camera) {
  this.update(camera);
  Mesh.prototype.draw.call(this, camera);
}

module.exports = PerspectiveCameraHelper;


text:
<?php
	$default_fields = '<perch:categories id="setTitle" type="smarttext" label="Title" required="true" />
					   <perch:categories id="setSlug" type="slug" for="setTitle" />';

	$API  = new PerchAPI(1.0, 'categories');
	$Lang   = $API->get('Lang');
	$HTML   = $API->get('HTML');
	$Paging = $API->get('Paging');

	$Sets 		= new PerchCategories_Sets;

	$setID   = false;
	$Set     = false;
	$message = false;
	$details = array();
	$template = 'set.html';

	if (PerchUtil::get('id')) {
		$setID    = (int) PerchUtil::get('id');
		$Set      = $Sets->find($setID);
		$template = $Set->setTemplate();
		$details  = $Set->to_array();
	}

	if (!$CurrentUser->has_priv('categories.manage')) {
		PerchUtil::redirect(PERCH_LOGINPATH.'/core/apps/categories/');
	}

	$Template   = $API->get('Template');
	$Template->set('categories/'.$template, 'categories', $default_fields);
	$Template->disable_feature('categories');

	$Form = $API->get('Form');
	$Form->handle_empty_block_generation($Template);
    $Form->set_required_fields_from_template($Template, $details);

    if ($Form->submitted()) {

		$fixed_fields = $Form->receive(array('setTemplate', 'setCatTemplate'));
    	$data = $Form->get_posted_content($Template, $Sets, $Set);
    	$data = array_merge($data, $fixed_fields);

        if (!is_object($Set)) {
            $Set = $Sets->create($data);
            PerchUtil::redirect(PERCH_LOGINPATH .'/core/apps/categories/sets/edit/?id='.$Set->id().'&created=1');
        }

        $Set->update($data);

    	$Set->update_all_in_set();

        if (is_object($Set)) {
            $message = $HTML->success_message('Your set has been successfully edited. Return to %scategory listing%s', 'id().'" class="notification-link">', '');
        }else{
            $message = $HTML->failure_message('Sorry, that set could not be edited.');
        }

    }

    if (isset($_GET['created']) && !$message) {
        $message = $HTML->success_message('Your set has been successfully created. Return to %scategory listing%s', '', '');
    }


text:
using Frapid.Reports.Engine.Model;

namespace Frapid.Reports.Engine.Generators
{
    public sealed class ScriptGenerator : IGenerator
    {
        public int Order { get; } = 9999;
        public string Name => "Report Script";

        public string Generate(string tenant, Report report)
        {
            if (string.IsNullOrWhiteSpace(report.Title))
            {
                return string.Empty;
            }

            return "<script data-frapid-report-script type='text/javascript'>" + report.Script + "</script>";
        }
    }
}


text:
#include "config.h"
#include "core/frame/Console.h"

#include "bindings/core/v8/ScriptCallStackFactory.h"
#include "core/inspector/InspectorConsoleInstrumentation.h"
#include "core/inspector/InspectorTraceEvents.h"
#include "core/inspector/ScriptArguments.h"
#include "platform/TraceEvent.h"
#include "wtf/text/CString.h"
#include "wtf/text/WTFString.h"

namespace blink {

ConsoleBase::~ConsoleBase()
{
}

void ConsoleBase::debug(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments)
{
    internalAddMessage(LogMessageType, DebugMessageLevel, scriptState, arguments);
}

void ConsoleBase::error(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments)
{
    internalAddMessage(LogMessageType, ErrorMessageLevel, scriptState, arguments);
}

void ConsoleBase::info(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments)
{
    internalAddMessage(LogMessageType, InfoMessageLevel, scriptState, arguments);
}

void ConsoleBase::log(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments)
{
    internalAddMessage(LogMessageType, LogMessageLevel, scriptState, arguments);
}

void ConsoleBase::warn(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments)
{
    internalAddMessage(LogMessageType, WarningMessageLevel, scriptState, arguments);
}

void ConsoleBase::dir(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments)
{
    internalAddMessage(DirMessageType, LogMessageLevel, scriptState, arguments);
}

void ConsoleBase::dirxml(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments)
{
    internalAddMessage(DirXMLMessageType, LogMessageLevel, scriptState, arguments);
}

void ConsoleBase::table(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments)
{
    internalAddMessage(TableMessageType, LogMessageLevel, scriptState, arguments);
}

void ConsoleBase::clear(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments)
{
    internalAddMessage(ClearMessageType, LogMessageLevel, scriptState, arguments, true);
}

void ConsoleBase::trace(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments)
{
    internalAddMessage(TraceMessageType, LogMessageLevel, scriptState, arguments, true, true);
}

void ConsoleBase::assertCondition(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments, bool condition)
{
    if (condition)
        return;

    internalAddMessage(AssertMessageType, ErrorMessageLevel, scriptState, arguments, true);
}

void ConsoleBase::count(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments)
{
    InspectorInstrumentation::consoleCount(context(), scriptState, arguments);
}

void ConsoleBase::markTimeline(const String& title)
{
    timeStamp(title);
}

void ConsoleBase::profile(const String& title)
{
    InspectorInstrumentation::consoleProfile(context(), title);
}

void ConsoleBase::profileEnd(const String& title)
{
    InspectorInstrumentation::consoleProfileEnd(context(), title);
}

void ConsoleBase::time(const String& title)
{
    InspectorInstrumentation::consoleTime(context(), title);
    TRACE_EVENT_COPY_ASYNC_BEGIN0("blink.console", title.utf8().data(), this);
}

void ConsoleBase::timeEnd(ScriptState* scriptState, const String& title)
{
    TRACE_EVENT_COPY_ASYNC_END0("blink.console", title.utf8().data(), this);
    InspectorInstrumentation::consoleTimeEnd(context(), title, scriptState);
}

void ConsoleBase::timeStamp(const String& title)
{
    TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "TimeStamp", "data", InspectorTimeStampEvent::data(context(), title));
    // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
    InspectorInstrumentation::consoleTimeStamp(context(), title);
}

void ConsoleBase::timeline(ScriptState* scriptState, const String& title)
{
    InspectorInstrumentation::consoleTimeline(context(), title, scriptState);
}

void ConsoleBase::timelineEnd(ScriptState* scriptState, const String& title)
{
    InspectorInstrumentation::consoleTimelineEnd(context(), title, scriptState);
}

void ConsoleBase::group(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments)
{
    internalAddMessage(StartGroupMessageType, LogMessageLevel, scriptState, arguments, true);
}

void ConsoleBase::groupCollapsed(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> arguments)
{
    internalAddMessage(StartGroupCollapsedMessageType, LogMessageLevel, scriptState, arguments, true);
}

void ConsoleBase::groupEnd()
{
    internalAddMessage(EndGroupMessageType, LogMessageLevel, nullptr, nullptr, true);
}

void ConsoleBase::internalAddMessage(MessageType type, MessageLevel level, ScriptState* scriptState, PassRefPtrWillBeRawPtr<ScriptArguments> scriptArguments, bool acceptNoArguments, bool printTrace)
{
    RefPtrWillBeRawPtr<ScriptArguments> arguments = scriptArguments;
    if (!acceptNoArguments && (!arguments || !arguments->argumentCount()))
        return;

    String message;
    bool gotStringMessage = arguments ? arguments->getFirstArgumentAsString(message) : false;

    RefPtrWillBeRawPtr<ConsoleMessage> consoleMessage = ConsoleMessage::create(ConsoleAPIMessageSource, level, gotStringMessage? message : String());
    consoleMessage->setType(type);
    consoleMessage->setScriptState(scriptState);
    consoleMessage->setScriptArguments(arguments);

    size_t stackSize = printTrace ? ScriptCallStack::maxCallStackSizeToCapture : 1;
    RefPtrWillBeRawPtr<ScriptCallStack> callStack(createScriptCallStackForConsole(stackSize));
    consoleMessage->setCallStack(callStack);

    reportMessageToConsole(consoleMessage.release());
}

} // namespace blink


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Pang, Vrijmoed, Kong & Jones, Mycol. Progr. 2(1): 35 (2003)

#### Original name
Gnomonia longirostris Cribb & J.W. Cribb, 1956

### Remarks
null


text:
package main_test

import (
	"os"
	"syscall"
	"testing"
)

func TestGoBuildUmask(t *testing.T) {
	// Do not use tg.parallel; avoid other tests seeing umask manipulation.
	mask := syscall.Umask(0077) // prohibit low bits
	defer syscall.Umask(mask)
	tg := testgo(t)
	defer tg.cleanup()
	tg.tempFile("x.go", `package main; func main() {}`)
	// Make sure artifact will be output to /tmp/... in case the user
	// has POSIX acl's on their go source tree.
	// See issue 17909.
	exe := tg.path("x")
	tg.creatingTemp(exe)
	tg.run("build", "-o", exe, tg.path("x.go"))
	fi, err := os.Stat(exe)
	if err != nil {
		t.Fatal(err)
	}
	if mode := fi.Mode(); mode&0077 != 0 {
		t.Fatalf("wrote x with mode=%v, wanted no 0077 bits", mode)
	}
}


text:
import { filter } from 'fuzzaldrin-plus';
import { isEqual } from 'lodash';
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from 'react';
import {
  createFixtureTree,
  FlatFixtureTreeItem,
  flattenFixtureTree,
} from 'react-cosmos-shared2/fixtureTree';
import { FixtureId, FixtureList } from 'react-cosmos-shared2/renderer';
import {
  black60,
  grey128,
  grey160,
  grey176,
  grey208,
  grey224,
  grey248,
  grey64,
  HelpCircleIcon,
  quick,
  SearchIcon,
} from 'react-cosmos-shared2/ui';
import styled from 'styled-components';
import {
  KEY_DOWN,
  KEY_ENTER,
  KEY_ESC,
  KEY_FWD_SLASH,
  KEY_TAB,
  KEY_UP,
} from '../../shared/keys';
import { FixtureSearchResult } from './FixtureSearchResult';
import { FixtureSearchShortcuts } from './FixtureSearchShortcuts';

type Props = {
  searchText: string;
  fixturesDir: string;
  fixtureFileSuffix: string;
  fixtures: FixtureList;
  selectedFixtureId: null | FixtureId;
  onSetSearchText: (searchText: string) => unknown;
  onClose: () => unknown;
  onSelect: (fixtureId: FixtureId, revealFixture: boolean) => unknown;
};

type ActiveFixturePath = null | string;

type FixtureItemsByPath = Record<string, FlatFixtureTreeItem>;

export function FixtureSearchOverlay({
  searchText,
  fixturesDir,
  fixtureFileSuffix,
  fixtures,
  selectedFixtureId,
  onSetSearchText,
  onClose,
  onSelect,
}: Props) {
  // Fixture items are memoized purely to minimize computation
  const fixtureItems = useMemo<FixtureItemsByPath>(() => {
    const fixtureTree = createFixtureTree({
      fixtures,
      fixturesDir,
      fixtureFileSuffix,
    });
    const flatFixtureTree = flattenFixtureTree(fixtureTree);
    return flatFixtureTree.reduce((acc, item) => {
      const cleanPath = [...item.parents, item.fileName];
      if (item.name) cleanPath.push(item.name);
      return { ...acc, [cleanPath.join(' ')]: item };
    }, {});
  }, [fixtures, fixturesDir, fixtureFileSuffix]);

  const onInputChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      onSetSearchText(e.currentTarget.value);
    },
    [onSetSearchText]
  );

  const [matchingFixturePaths, setMatchingFixturePaths] = useState(
    getMatchingFixturePaths(fixtureItems, searchText)
  );

  const [activeFixturePath, setActiveFixturePath] = useState<ActiveFixturePath>(
    () => {
      const selectedFixturePath =
        selectedFixtureId && findFixturePath(fixtureItems, selectedFixtureId);
      return selectedFixturePath || getFirstFixturePath(matchingFixturePaths);
    }
  );

  useEffect(() => {
    const newMatchingFixturePaths = getMatchingFixturePaths(
      fixtureItems,
      searchText
    );

    if (!isEqual(newMatchingFixturePaths, matchingFixturePaths)) {
      setMatchingFixturePaths(newMatchingFixturePaths);
      // Reset active fixture to first matching fixture when search changes
      // WARNING: Putting this in a separate effect with only matchingFixturePaths
      // as a dependency looks nicer, but creates a flicker between some renders.
      // On searchText change, the component would first render a new list of
      // matching fixture paths (which may or may not contain the activeFixturePath),
      // and only in the (albeit almost instant) 2nd render would activeFixturePath
      // be updated to equal the first of the new list of matching fixture paths.
      setActiveFixturePath(getFirstFixturePath(newMatchingFixturePaths));
    }
  }, [fixtureItems, matchingFixturePaths, searchText]);

  const onInputKeyDown = useMemo(() => {
    function handleEscape() {
      onClose();
    }

    function handleEnter() {
      if (activeFixturePath !== null) {
        const { fixtureId } = fixtureItems[activeFixturePath];
        onSelect(fixtureId, true);
      }
    }

    function handleUp() {
      if (activeFixturePath) {
        const fixtureIndex = matchingFixturePaths.indexOf(activeFixturePath);
        if (fixtureIndex > 0) {
          setActiveFixturePath(matchingFixturePaths[fixtureIndex - 1]);
        }
      }
    }

    function handleDown() {
      if (activeFixturePath) {
        const fixtureIndex = matchingFixturePaths.indexOf(activeFixturePath);
        if (fixtureIndex < matchingFixturePaths.length - 1) {
          setActiveFixturePath(matchingFixturePaths[fixtureIndex + 1]);
        }
      }
    }

    function handleTab() {
      const matchingFixtureCount = matchingFixturePaths.length;
      if (matchingFixtureCount > 0) {
        if (!activeFixturePath) {
          setActiveFixturePath(matchingFixturePaths[0]);
        } else {
          const fixtureIndex = matchingFixturePaths.indexOf(activeFixturePath);
          const lastMatch = fixtureIndex === matchingFixtureCount - 1;
          if (lastMatch) {
            setActiveFixturePath(matchingFixturePaths[0]);
          } else {
            setActiveFixturePath(matchingFixturePaths[fixtureIndex + 1]);
          }
        }
      }
    }

    function handleTabReverse() {
      const matchingFixtureCount = matchingFixturePaths.length;
      if (matchingFixtureCount > 0) {
        if (!activeFixturePath) {
          setActiveFixturePath(matchingFixturePaths[matchingFixtureCount - 1]);
        } else {
          const fixtureIndex = matchingFixturePaths.indexOf(activeFixturePath);
          const lastMatch = fixtureIndex === 0;
          if (lastMatch) {
            setActiveFixturePath(
              matchingFixturePaths[matchingFixtureCount - 1]
            );
          } else {
            setActiveFixturePath(matchingFixturePaths[fixtureIndex - 1]);
          }
        }
      }
    }

    function handleQuestionMark(e: React.KeyboardEvent) {
      if (e.shiftKey) {
        e.preventDefault();
        setShowShortcuts(prev => !prev);
      }
    }

    return (e: React.KeyboardEvent) => {
      switch (e.keyCode) {
        case KEY_ESC:
          e.preventDefault();
          return handleEscape();
        case KEY_ENTER:
          e.preventDefault();
          return handleEnter();
        case KEY_UP:
          e.preventDefault();
          return handleUp();
        case KEY_DOWN:
          e.preventDefault();
          return handleDown();
        case KEY_TAB:
          e.preventDefault();
          return e.shiftKey ? handleTabReverse() : handleTab();
        case KEY_FWD_SLASH:
          return handleQuestionMark(e);
        default:
        // Nada
      }
    };
  }, [
    onClose,
    activeFixturePath,
    fixtureItems,
    onSelect,
    matchingFixturePaths,
  ]);

  const inputRef = useRef<HTMLInputElement>(null);

  // Auto focus when search input is created
  useEffect(() => {
    if (inputRef.current) {
      inputRef.current.focus();
      inputRef.current.select();
    }
  }, []);

  // 1. Prevent click propagation to overlay element (which calls onClose)
  // 2. Keep user focused on search input while search is open
  const onContentClick = useCallback((e: React.MouseEvent) => {
    e.stopPropagation();
    if (inputRef.current) {
      inputRef.current.focus();
    }
  }, []);

  const [showShortcuts, setShowShortcuts] = useState(false);

  const handleToggleHelp = useCallback(() => {
    setShowShortcuts(prev => !prev);
  }, []);

  return (
    <OverlayIE11 data-testid="fixtureSearchOverlay" onClick={onClose}>
      <Content data-testid="fixtureSearchContent" onClick={onContentClick}>
        <InputContainer>
          <SearchIconContainer>
            <SearchIcon />
          </SearchIconContainer>
          <SearchInput
            ref={inputRef}
            type="text"
            placeholder="Fixture search"
            value={searchText}
            onChange={onInputChange}
            onKeyDown={onInputKeyDown}
          />
          <HelpButton selected={showShortcuts} onClick={handleToggleHelp}>
            <HelpCircleIcon />
          </HelpButton>
        </InputContainer>
        <ShortcutsContainer visible={showShortcuts}>
          <FixtureSearchShortcuts />
        </ShortcutsContainer>
        <ResultsViewport>
          <ResultsContainer>
            {matchingFixturePaths.map(cleanFixturePath => (
              <FixtureSearchResult
                key={cleanFixturePath}
                cleanFixturePath={cleanFixturePath}
                fixtureItem={fixtureItems[cleanFixturePath]}
                active={cleanFixturePath === activeFixturePath}
                onSelect={onSelect}
              />
            ))}
            {matchingFixturePaths.length === 0 && (
              <NoResults>No results</NoResults>
            )}
          </ResultsContainer>
        </ResultsViewport>
      </Content>
    </OverlayIE11>
  );
}

function findFixturePath(
  fixtureItems: FixtureItemsByPath,
  fixtureId: FixtureId
) {
  const fixturePaths = Object.keys(fixtureItems);
  return fixturePaths.find(fixturePath =>
    isEqual(fixtureItems[fixturePath].fixtureId, fixtureId)
  );
}

function getFirstFixturePath(fixturePaths: string[]): null | string {
  return fixturePaths.length > 0 ? fixturePaths[0] : null;
}

function getMatchingFixturePaths(
  fixtureItems: FixtureItemsByPath,
  searchText: string
): string[] {
  const fixturePaths = Object.keys(fixtureItems);

  if (searchText === '') {
    return fixturePaths;
  }

  const fixtureSearchTexts: string[] = [];
  fixturePaths.forEach(cleanFixturePath => {
    const { fixtureId, parents } = fixtureItems[cleanFixturePath];
    const { path, name } = fixtureId;
    // Allow fixtures to be searched by their entire file path, suffixed by
    // their name in the case of named fixtures, as well as by parent path,
    // allowing users to query results in the format they are displayed
    const searchPath = [path];
    if (name) searchPath.push(name);
    searchPath.push(...parents);
    fixtureSearchTexts.push(searchPath.join(' '));
  });

  const machingFixtureSearchTexts = filter(fixtureSearchTexts, searchText);
  return machingFixtureSearchTexts.map(fixtureSearchText => {
    const fixtureIndex = fixtureSearchTexts.indexOf(fixtureSearchText);
    return fixturePaths[fixtureIndex];
  });
}

const Overlay = styled.div`
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: ${black60};
`;

const OverlayIE11 = styled(Overlay)`
  z-index: 10;
`;

const Content = styled.div`
  position: absolute;
  top: 20%;
  left: 50%;
  transform: translate(-50%, 0);
  width: 80%;
  max-width: 640px;
  border-radius: 3px;
  background: ${grey248};
  box-shadow: rgba(15, 15, 15, 0.05) 0px 0px 0px 1px,
    rgba(15, 15, 15, 0.1) 0px 5px 10px, rgba(15, 15, 15, 0.2) 0px 15px 40px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
`;

const InputContainer = styled.div`
  flex-shrink: 0;
  display: flex;
  flex-direction: row;
  align-items: center;
  height: 48px;
  padding: 0 12px;
  user-select: none;
  cursor: text;
`;

const SearchIconContainer = styled.div`
  flex-shrink: 0;
  width: 20px;
  height: 20px;
  margin: 2px 0 0 0;
  padding: 0 10px 0 6px;
  color: ${grey176};
`;

const SearchInput = styled.input`
  flex: 1;
  border: none;
  background: transparent;
  color: ${grey64};
  outline: none;
  font-size: 16px;
  line-height: 32px;

  ::placeholder {
    color: ${grey160};
  }
`;

const HelpButton = styled.div<{ selected: boolean }>`
  flex-shrink: 0;
  width: 20px;
  height: 20px;
  margin: 2px 0 0 0;
  padding: 6px;
  border-radius: 50%;
  background: ${props => (props.selected ? grey224 : 'transparent')};
  color: ${props => (props.selected ? grey128 : grey176)};
  cursor: pointer;
  transition: background ${quick}s, color ${quick}s;

  :hover {
    color: ${grey128};
  }
`;

const ShortcutsContainer = styled.div<{ visible: boolean }>`
  height: ${props => (props.visible ? 72 : 0)}px;
  overflow: hidden;
  opacity: ${props => (props.visible ? 1 : 0)};
  transition: height ${quick}s, opacity ${quick}s;
  user-select: none;
`;

const ResultsViewport = styled.div`
  max-height: 336px;
  border-top: 1px solid ${grey208};
  background: ${grey224};
  overflow-x: hidden;
  overflow-y: auto;
`;

const ResultsContainer = styled.div`
  padding: 8px 0;
`;

const NoResults = styled.div`
  padding: 0 24px 0 48px;
  line-height: 32px;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  user-select: none;
  color: ${grey128};
`;


text:
package org.springframework.cloud.contract.wiremock.issues.staticInit;

import java.net.URI;

import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class WebClient {

	private final RestTemplate restTemplate;

	private final ClientProperties clientProperties;

	public WebClient(RestTemplate restTemplate, ClientProperties clientProperties) {
		this.restTemplate = restTemplate;
		this.clientProperties = clientProperties;
	}

	public String get() {
		URI url = URI.create(clientProperties.getUrl());
		return restTemplate.getForObject(url, String.class);
	}

}


text:
@interface MCEffect : NSObject

@end