问:
UnsatisfiedDependencyException: Error creating bean with name 'trafficMapper'
I work with a Spring boot application and get the error provided below,

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'trafficMapper': Unsatisfied dependency expressed through field 'config'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.ratepay.iris.ella.config.MasterConfig' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546)
    at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:88)
    at com.ratepay.iris.ella.service.EllaServiceIntegrationTest.setup(EllaServiceIntegrationTest.java:72)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at com.github.tomakehurst.wiremock.junit.WireMockRule$1.evaluate(WireMockRule.java:73)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.ratepay.iris.ella.config.MasterConfig' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1644)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1203)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1164)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
    ... 38 more
</code>```

The error occurred when I try to do the setup for designing an integration test.

```<code>    @Before
    @SuppressWarnings( "resource" )
    public void setup() {
        int port = wireMockRule.port();

        System.setProperty( "ella.uri", "http://localhost:" + port + ELLA_ENDPOINT );
        //        System.setProperty( "freud.master.config", "src/test/resources/test-master-config.json" );
        System.setProperty( "ella.shadowmode", "enabled" );

        ApplicationContext context = new AnnotationConfigApplicationContext( EllaConfiguration.class );
        ellaService = context.getBean( EllaService.class );
    }
</code>```

This is the LOC that provides the error,

```<code>ApplicationContext context = new AnnotationConfigApplicationContext( EllaConfiguration.class );
</code>```

The EllaConfiguration class is provided below,

```<code>@Configuration
@ComponentScan( "com.ratepay.iris.ella" )
public class EllaConfiguration {

    public static final String ELLA_CONNECTOR_BEAN_NAME = "ellaConnector";

    private static final String URI_CONFIG_KEY = "ella.uri";
    private static final String CONNECTION_TIMEOUT_CONFIG_KEY = "ella.connection_timeout";
    private static final String READ_TIMEOUT_CONFIG_KEY = "ella.read_timeout";

    private static final int DEFAULT_CONNECTION_TIMEOUT = 100;
    private static final int DEFAULT_READ_TIMEOUT = 800;

    public static final String ELLA_SHADOW_MODE_KEY = "ella.shadowmode";
    public static final String ELLA_SHADOW_MODE_ENABLED_VALUE = "enabled";

    @Bean( name = ELLA_CONNECTOR_BEAN_NAME )
    public EntityServiceConnectable<EllaResponse> timeoutConfiguration( final Environment env ) {
        return ServiceConnectorBuilder.create( createConnectionConfiguration( env ) ).timeout( createTimeoutConfiguration( env ) ).build();
    }

    private SimpleTimeoutConfiguration createTimeoutConfiguration( final Environment env ) {
        return new SimpleTimeoutConfiguration( env.getProperty( CONNECTION_TIMEOUT_CONFIG_KEY, Integer.class, DEFAULT_CONNECTION_TIMEOUT ),
                                               env.getProperty( READ_TIMEOUT_CONFIG_KEY, Integer.class, DEFAULT_READ_TIMEOUT ) );
    }

    public boolean isEllaShadowModeEnabled( final Environment env ) {
        return env.getRequiredProperty( ELLA_SHADOW_MODE_KEY ).equals( ELLA_SHADOW_MODE_ENABLED_VALUE );
    }

    private PostConnectionConfiguration<EllaResponse> createConnectionConfiguration( final Environment env ) {
        return new SimplePostConnectionConfiguration<>( env.getRequiredProperty( URI_CONFIG_KEY ), EllaResponse.class );
    }
}
</code>```

The EllaService class is provided,

```<code>@Service
public class EllaService {

    public static final int IRIS_ACCEPT = 0;
    public static final int IRIS_REJECT = 100;

    @Autowired
    @Qualifier( ELLA_CONNECTOR_BEAN_NAME )
    private EntityServiceConnectable<EllaResponse> connector;

    @Autowired
    private TrafficMapper trafficMapper;

    @Autowired
    private EllaConfiguration config;

    @Autowired
    private Environment env;

    @Getter
    private boolean shadowModeEnabled = false;

    /**
     * Initialize the service.
     */
    @PostConstruct
    public void initialize() {
        this.shadowModeEnabled = config.isEllaShadowModeEnabled( env );
    }

    /**
     * Asynchronously call Ella. Determine if traffic is applicable for Ella and if yes forward to Ella.
     *
     * @param irisEo
     * @return List<ResultBo>
     * @throws EllaGatewayUnsuccessfulResponseException
     */
    @Async
    public void invokeEllaAsync( final IrisEo irisEo ) throws EllaGatewayUnsuccessfulResponseException {
        invokeEllaSync( irisEo );
    }

    /**
     * Synchronously call Ella. Determine if traffic is applicable for Ella and if yes forward to Ella.
     *
     * @param irisEo
     * @return List<ResultBo>
     * @throws EllaGatewayUnsuccessfulResponseException
     */
    public List<ResultBo> invokeEllaSync( final IrisEo irisEo ) throws EllaGatewayUnsuccessfulResponseException {

        Optional<String> mapId = trafficMapper.getApplicableMapId( irisEo );

        if( mapId.isPresent() && StringUtils.isNotEmpty( mapId.get() ) ) {

            try {
                return irisEo.getOrder().getProducts().stream().map( product -> fetchEllaResult( irisEo, mapId.get(), product ) )
                        .collect( Collectors.toList() );
            }
            catch( EllaGatewayUnsuccessfulResponseException ex ) {
                throw new EllaGatewayUnsuccessfulResponseException( ex.getMessage(), ex.getCause() );
            }
        }
        return Collections.emptyList();
    }

    private ResultBo fetchEllaResult( final IrisEo irisEo, String mapId, String product ) throws EllaGatewayUnsuccessfulResponseException {

        HttpHeaders freudHeaders = createRequestHeaders( irisEo );

        ServiceResponse<EllaResponse> response = connector
                .call( EllaDtoConverter.convertToRequest( irisEo, mapId, product ), freudHeaders );

        if( !response.isSuccess() ) {
            throw new EllaGatewayUnsuccessfulResponseException( response.getErrorMessage(), response.getException().getCause() );
        }

        EllaResult prediction = response.getResponse().getResult();

        return convertToResultBo( prediction, product );

    }

    private ResultBo convertToResultBo( EllaResult prediction, String product ) {

        ClassificationResult classification = prediction.getClassification();
        final int irisPrediction = ClassificationResult.FRAUD.equals( classification ) ? IRIS_REJECT : IRIS_ACCEPT;
        //        final int irisPrediction = Integer.valueOf( classification.getValue() ) < 900 ? IRIS_REJECT : IRIS_ACCEPT;

        return new ResultBo( product, irisPrediction );
    }

    private HttpHeaders createRequestHeaders( final IrisEo irisEo ) {

        HttpHeaders freudHeaders = new HttpHeaders();

        freudHeaders.add( ACCEPT, APPLICATION_JSON_UTF8_VALUE );
        RatepayHeaders.append( freudHeaders, irisEo.getRequestInfo() );

        return freudHeaders;
    }

}
</code>```

I get an NPE from the invokeEllaSync method in the LOC,

```<code>Optional<String> mapId = trafficMapper.getApplicableMapId( irisEo );
</code>```

The TrafficMapper class is provided,

```<code>@Component
public class TrafficMapper {

    @Autowired
    private MasterConfig config;

    private final Map<Integer, String> shopIdToMapId = new HashMap<>();

    /**
     * Initialize the component.
     */
    @PostConstruct
    public void initialize() {
        fillShopIdMap();
    }

    /**
     * Return an optional holding a specific map id.
     *
     * @param irisEo
     * @return Optional<String>
     */
    public Optional<String> getApplicableMapId( IrisEo irisEo ) {

        Integer shopId = irisEo.getOrder().getShopId();
        return Optional.ofNullable( this.shopIdToMapId.get( shopId ) );
    }

    private void fillShopIdMap() {

        this.config.getTrafficMappings().stream().forEach( trafficMapping -> trafficMapping.getTrafficDescription().getShopIds().stream()
                .forEach( shopId -> this.shopIdToMapId.put( shopId, trafficMapping.getMapId() ) ) );
    }
}
</code>```

The MasterConfig class is provided,

```<code>@Getter
@Setter
@ToString
public class MasterConfig {

    @NotNull
    @JsonProperty( "traffic_mappings" )
    private List<TrafficMapping> trafficMappings;
}
</code>```

The reason I provided the classes is I am unable to find the issue and wanted to provide more information for the investigation.

How do I solve the UnsatisfiedDependencyException error?

PS:

I can modify the question if not appropriate. Please, comment below if you have a valid concern.

答:
Add Component annotation to MasterConfig class.

@Component
@Getter
@Setter
@ToString
public class MasterConfig {

    @NotNull
    @JsonProperty( "traffic_mappings" )
    private List<TrafficMapping> trafficMappings;
}
```

Autowired means you want to inject a bean to the field or etc.

So MasterConfig should be a bean.  You can make it component or service or other beans.

Body:
I work with a Spring boot application and get the error provided below,

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'trafficMapper': Unsatisfied dependency expressed through field 'config'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.ratepay.iris.ella.config.MasterConfig' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546)
    at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:88)
    at com.ratepay.iris.ella.service.EllaServiceIntegrationTest.setup(EllaServiceIntegrationTest.java:72)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at com.github.tomakehurst.wiremock.junit.WireMockRule$1.evaluate(WireMockRule.java:73)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.ratepay.iris.ella.config.MasterConfig' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1644)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1203)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1164)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
    ... 38 more

The error occurred when I try to do the setup for designing an integration test.

    @Before
    @SuppressWarnings( "resource" )
    public void setup() {
        int port = wireMockRule.port();

        System.setProperty( "ella.uri", "http://localhost:" + port + ELLA_ENDPOINT );
        //        System.setProperty( "freud.master.config", "src/test/resources/test-master-config.json" );
        System.setProperty( "ella.shadowmode", "enabled" );

        ApplicationContext context = new AnnotationConfigApplicationContext( EllaConfiguration.class );
        ellaService = context.getBean( EllaService.class );
    }

This is the LOC that provides the error,

ApplicationContext context = new AnnotationConfigApplicationContext( EllaConfiguration.class );

The EllaConfiguration class is provided below,

@Configuration
@ComponentScan( "com.ratepay.iris.ella" )
public class EllaConfiguration {

    public static final String ELLA_CONNECTOR_BEAN_NAME = "ellaConnector";

    private static final String URI_CONFIG_KEY = "ella.uri";
    private static final String CONNECTION_TIMEOUT_CONFIG_KEY = "ella.connection_timeout";
    private static final String READ_TIMEOUT_CONFIG_KEY = "ella.read_timeout";

    private static final int DEFAULT_CONNECTION_TIMEOUT = 100;
    private static final int DEFAULT_READ_TIMEOUT = 800;

    public static final String ELLA_SHADOW_MODE_KEY = "ella.shadowmode";
    public static final String ELLA_SHADOW_MODE_ENABLED_VALUE = "enabled";

    @Bean( name = ELLA_CONNECTOR_BEAN_NAME )
    public EntityServiceConnectable<EllaResponse> timeoutConfiguration( final Environment env ) {
        return ServiceConnectorBuilder.create( createConnectionConfiguration( env ) ).timeout( createTimeoutConfiguration( env ) ).build();
    }

    private SimpleTimeoutConfiguration createTimeoutConfiguration( final Environment env ) {
        return new SimpleTimeoutConfiguration( env.getProperty( CONNECTION_TIMEOUT_CONFIG_KEY, Integer.class, DEFAULT_CONNECTION_TIMEOUT ),
                                               env.getProperty( READ_TIMEOUT_CONFIG_KEY, Integer.class, DEFAULT_READ_TIMEOUT ) );
    }

    public boolean isEllaShadowModeEnabled( final Environment env ) {
        return env.getRequiredProperty( ELLA_SHADOW_MODE_KEY ).equals( ELLA_SHADOW_MODE_ENABLED_VALUE );
    }

    private PostConnectionConfiguration<EllaResponse> createConnectionConfiguration( final Environment env ) {
        return new SimplePostConnectionConfiguration<>( env.getRequiredProperty( URI_CONFIG_KEY ), EllaResponse.class );
    }
}

The EllaService class is provided,

@Service
public class EllaService {

    public static final int IRIS_ACCEPT = 0;
    public static final int IRIS_REJECT = 100;

    @Autowired
    @Qualifier( ELLA_CONNECTOR_BEAN_NAME )
    private EntityServiceConnectable<EllaResponse> connector;

    @Autowired
    private TrafficMapper trafficMapper;

    @Autowired
    private EllaConfiguration config;

    @Autowired
    private Environment env;

    @Getter
    private boolean shadowModeEnabled = false;

    /**
     * Initialize the service.
     */
    @PostConstruct
    public void initialize() {
        this.shadowModeEnabled = config.isEllaShadowModeEnabled( env );
    }

    /**
     * Asynchronously call Ella. Determine if traffic is applicable for Ella and if yes forward to Ella.
     *
     * @param irisEo
     * @return List<ResultBo>
     * @throws EllaGatewayUnsuccessfulResponseException
     */
    @Async
    public void invokeEllaAsync( final IrisEo irisEo ) throws EllaGatewayUnsuccessfulResponseException {
        invokeEllaSync( irisEo );
    }

    /**
     * Synchronously call Ella. Determine if traffic is applicable for Ella and if yes forward to Ella.
     *
     * @param irisEo
     * @return List<ResultBo>
     * @throws EllaGatewayUnsuccessfulResponseException
     */
    public List<ResultBo> invokeEllaSync( final IrisEo irisEo ) throws EllaGatewayUnsuccessfulResponseException {

        Optional<String> mapId = trafficMapper.getApplicableMapId( irisEo );

        if( mapId.isPresent() && StringUtils.isNotEmpty( mapId.get() ) ) {

            try {
                return irisEo.getOrder().getProducts().stream().map( product -> fetchEllaResult( irisEo, mapId.get(), product ) )
                        .collect( Collectors.toList() );
            }
            catch( EllaGatewayUnsuccessfulResponseException ex ) {
                throw new EllaGatewayUnsuccessfulResponseException( ex.getMessage(), ex.getCause() );
            }
        }
        return Collections.emptyList();
    }

    private ResultBo fetchEllaResult( final IrisEo irisEo, String mapId, String product ) throws EllaGatewayUnsuccessfulResponseException {

        HttpHeaders freudHeaders = createRequestHeaders( irisEo );

        ServiceResponse<EllaResponse> response = connector
                .call( EllaDtoConverter.convertToRequest( irisEo, mapId, product ), freudHeaders );

        if( !response.isSuccess() ) {
            throw new EllaGatewayUnsuccessfulResponseException( response.getErrorMessage(), response.getException().getCause() );
        }

        EllaResult prediction = response.getResponse().getResult();

        return convertToResultBo( prediction, product );

    }

    private ResultBo convertToResultBo( EllaResult prediction, String product ) {

        ClassificationResult classification = prediction.getClassification();
        final int irisPrediction = ClassificationResult.FRAUD.equals( classification ) ? IRIS_REJECT : IRIS_ACCEPT;
        //        final int irisPrediction = Integer.valueOf( classification.getValue() ) < 900 ? IRIS_REJECT : IRIS_ACCEPT;

        return new ResultBo( product, irisPrediction );
    }

    private HttpHeaders createRequestHeaders( final IrisEo irisEo ) {

        HttpHeaders freudHeaders = new HttpHeaders();

        freudHeaders.add( ACCEPT, APPLICATION_JSON_UTF8_VALUE );
        RatepayHeaders.append( freudHeaders, irisEo.getRequestInfo() );

        return freudHeaders;
    }

}

I get an NPE from the invokeEllaSync method in the LOC,

Optional<String> mapId = trafficMapper.getApplicableMapId( irisEo );

The TrafficMapper class is provided,

@Component
public class TrafficMapper {

    @Autowired
    private MasterConfig config;

    private final Map<Integer, String> shopIdToMapId = new HashMap<>();

    /**
     * Initialize the component.
     */
    @PostConstruct
    public void initialize() {
        fillShopIdMap();
    }

    /**
     * Return an optional holding a specific map id.
     *
     * @param irisEo
     * @return Optional<String>
     */
    public Optional<String> getApplicableMapId( IrisEo irisEo ) {

        Integer shopId = irisEo.getOrder().getShopId();
        return Optional.ofNullable( this.shopIdToMapId.get( shopId ) );
    }

    private void fillShopIdMap() {

        this.config.getTrafficMappings().stream().forEach( trafficMapping -> trafficMapping.getTrafficDescription().getShopIds().stream()
                .forEach( shopId -> this.shopIdToMapId.put( shopId, trafficMapping.getMapId() ) ) );
    }
}

The MasterConfig class is provided,

@Getter
@Setter
@ToString
public class MasterConfig {

    @NotNull
    @JsonProperty( "traffic_mappings" )
    private List<TrafficMapping> trafficMappings;
}

The reason I provided the classes is I am unable to find the issue and wanted to provide more information for the investigation.

How do I solve the UnsatisfiedDependencyException error?

PS:

I can modify the question if not appropriate. Please, comment below if you have a valid concern.

Body:
Add Component annotation to MasterConfig class.

@Component
@Getter
@Setter
@ToString
public class MasterConfig {

    @NotNull
    @JsonProperty( "traffic_mappings" )
    private List<TrafficMapping> trafficMappings;
}

Autowired means you want to inject a bean to the field or etc.

So MasterConfig should be a bean.  You can make it component or service or other beans.


来源: stackexchange

问:
O(NLogN) shows better performance than O(N) if unordered_set is used
```<code>//Time sorting O(nlogn) + binary search for N items logN = 2NLogN =
//Time: O(NLogN).
//space - O(1).
bool TwoSum::TwoSumSortAndBinarySearch(int* arr, int size, int sum)
{
    sort(arr, arr + size);

    for (int i = 0; i < size; i++)
    {
        if (binary_search(arr + i + 1, arr + size, sum - arr[i]))
            return true;
    }
    return false;
}

//Time: O(N) as time complexity of Add and Search in hashset/unordered_set is O(1).
//Space: O(N)
bool TwoSum::TwoSumHashSet(int* arr, int size, int sum)
{
    unordered_set<int> hash;
    for (int i = 0; i < size; i++)
    {
        if (hash.find(sum - arr[i]) != hash.end())
            return true;
        hash.insert(arr[i]);
    }
    return false;
}

int* TwoSum::Testcase(int size)
{
    int* in = new int[size];
    for (int i = 0; i < size; i++)
    {
        in[i] = rand() % (size + 1);//random number b/w 0 to N.
    }
    return in;
}

int main()
{
    int size = 5000000;
    int* in = TwoSum::Testcase(size);

    auto start = std::chrono::system_clock::now();//clock start
    bool output = TwoSum::TwoSumHashSet(in, size, INT_MAX);
    auto end = std::chrono::system_clock::now();//clock end

    std::chrono::duration<double> elapsed_seconds = end - start;
    cout << "elapsed time: " << elapsed_seconds.count() << "s\n";
}
</code>```

I measured the performance of the above two methods, where I would like to find the TwoSum problem.
In the First approach, I am sorting the array then using binary search.
Time: O(NLogN).
space - O(1).

In the second approach, unordered_set is used whose complexity is constant on average, worst case linear in the size of the container.

//Time: O(N) as time complexity of Add and Search in hashset/unordered_set is O(1).
//Space: O(N)

Here are the three runs time taken by these two methods

TwoSumSortAndBinarySearch---------------TwoSumHashSet

8.05---------------------------------------15.15

7.76---------------------------------------14.47

7.74---------------------------------------14.28

So, it is clear that TwoSumSortAndBinarySearch performs definitely better than unordered_Set.

Which approach is more preferable and suggested in real scenario and why?

答:
This is because computational complexity doesn’t take into account the behavior of multi-level memory system present in every modern computer. And it is precisely because you measure that behavior via proxy using time (!!), that your measurement is not “like” theoretical computational complexity. Computational complexity predicts execution times only in very well controlled situations, when the code is optimal for the platform. If you want to measure complexity, you can’t measure time. Measure operation counts. It will agree with theory then.

In my limited experience, it is rather rare that computational complexity theory would predict runtimes on reasonably sized data sets, when the behavior is neither exponential nor cubic (or higher terms). Cache access patterns and utilization of architectural parallelism are major predictors of performance, before computational complexity comes into play.

ContentLicense: CC BY-SA 4.0

Body:
//Time sorting O(nlogn) + binary search for N items logN = 2NLogN =
//Time: O(NLogN).
//space - O(1).
bool TwoSum::TwoSumSortAndBinarySearch(int* arr, int size, int sum)
{
    sort(arr, arr + size);

    for (int i = 0; i < size; i++)
    {
        if (binary_search(arr + i + 1, arr + size, sum - arr[i]))
            return true;
    }
    return false;
}

//Time: O(N) as time complexity of Add and Search in hashset/unordered_set is O(1).
//Space: O(N)
bool TwoSum::TwoSumHashSet(int* arr, int size, int sum)
{
    unordered_set<int> hash;
    for (int i = 0; i < size; i++)
    {
        if (hash.find(sum - arr[i]) != hash.end())
            return true;
        hash.insert(arr[i]);
    }
    return false;
}

int* TwoSum::Testcase(int size)
{
    int* in = new int[size];
    for (int i = 0; i < size; i++)
    {
        in[i] = rand() % (size + 1);//random number b/w 0 to N.
    }
    return in;
}

int main()
{
    int size = 5000000;
    int* in = TwoSum::Testcase(size);

    auto start = std::chrono::system_clock::now();//clock start
    bool output = TwoSum::TwoSumHashSet(in, size, INT_MAX);
    auto end = std::chrono::system_clock::now();//clock end

    std::chrono::duration<double> elapsed_seconds = end - start;
    cout << "elapsed time: " << elapsed_seconds.count() << "s\n";
}

I measured the performance of the above two methods, where I would like to find the TwoSum problem.
In the First approach, I am sorting the array then using binary search.
Time: O(NLogN).
space - O(1).

In the second approach, unordered_set is used whose complexity is constant on average, worst case linear in the size of the container.

//Time: O(N) as time complexity of Add and Search in hashset/unordered_set is O(1).
//Space: O(N)

Here are the three runs time taken by these two methods

TwoSumSortAndBinarySearch---------------TwoSumHashSet

8.05---------------------------------------15.15

7.76---------------------------------------14.47

7.74---------------------------------------14.28

So, it is clear that TwoSumSortAndBinarySearch performs definitely better than unordered_Set.

Which approach is more preferable and suggested in real scenario and why?


问:
How to solve ImportError: cannot import name splitfn in python
i have write code to calibrate camera in my calibrate.py file,but when i run that file it shows error like, ImportError: cannot import name splitfn ..so how to solve this?...i have run this file using this command:

sudo python calibrate.py image4.jpg calibration.yaml --debug-dir out

so is this right command to execute this script?if any changes then plz suggest me.. my captured image for calibration(which i have gave as input) and output(RMS,camera matrix,distortion coefficient)is stored in calibration.yaml file?i need to make this file or it is automatically created?

答:
The splitfn just provides path, file_name(without ext) and ext of the input file.
One can use below implementation for the same. </p>

```<code>#from common import splitfn
def splitfn(file_path):

    file_path_parts = file_path.split(sep=os.sep)
    _path = os.path.join(*file_path_parts[:-1])
    file_name = file_path_parts[-1]
    file_name_parts = file_name.split(sep='.')
    return _path, file_name_parts[0], file_name_parts[1]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The splitfn just provides path, file_name(without ext) and ext of the input file.
One can use below implementation for the same.

#from common import splitfn
def splitfn(file_path):

    file_path_parts = file_path.split(sep=os.sep)
    _path = os.path.join(*file_path_parts[:-1])
    file_name = file_path_parts[-1]
    file_name_parts = file_name.split(sep='.')
    return _path, file_name_parts[0], file_name_parts[1]


问:
Creating array from instance variables of a class
I have to create an array from teh instance variables of a class (the values, not the names). Currently my code simply uses getters for each variable but with 14 variables this is unsightly and not exactly code efficient. Is there any other way to do it more efficiently?</p>

答:
Basically to get the fields defined in the class by reflection and get the value of the field for that object.

Example:

import java.lang.reflect.Field;
import java.util.Arrays;

public class ReflectionTest {
    public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
        Model m = new Model(100, 200, 300, 400, 500, 600);
        Field[] fields = m.getClass().getDeclaredFields();
        Object[] data = new Object[fields.length];
        int i = 0;
        for (Field field : fields) {
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            Object o = field.get(m);
            data[i] = o;
            i++;
        }
        System.out.println(Arrays.toString(data));
    }
}

class Model {
    private int a, b, c, d, e, f;
    public Model(int a, int b, int c, int d, int e, int f) {
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
        this.e = e;
        this.f = f;
    }
}
```

JDK: 1.8

Body:
Basically to get the fields defined in the class by reflection and get the value of the field for that object.

Example:

import java.lang.reflect.Field;
import java.util.Arrays;

public class ReflectionTest {
    public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
        Model m = new Model(100, 200, 300, 400, 500, 600);
        Field[] fields = m.getClass().getDeclaredFields();
        Object[] data = new Object[fields.length];
        int i = 0;
        for (Field field : fields) {
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            Object o = field.get(m);
            data[i] = o;
            i++;
        }
        System.out.println(Arrays.toString(data));
    }
}

class Model {
    private int a, b, c, d, e, f;
    public Model(int a, int b, int c, int d, int e, int f) {
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
        this.e = e;
        this.f = f;
    }
}

JDK: 1.8


问:
"position: sticky;" elements not quite lining up
So I run our secondary, cheesy school website for students. Summer just started so I'm doing a bunch of work on it. I have three button tags, and all of their positions are set to sticky. When I scroll down, they line up flush with the top of the page (because I set top: to 0px;). But when the page is scrolled up, they are offset by about two pixels from the top. But it's super obvious, and I think it looks ugly. There is also a lot of spacing between them. It would be nice to get rid of those two. The first button lines up how I want it. It just contains text. The other two, that don't line up, have  elements around them, and contain images. I think this Is why, but I am struggling to solve the problem. I'm posting this late at night, so I can't check any answers for another 10 hours or so. But It would be nice to have some help, Thanks.

PS, My website address is https://jeffthecow.com/
The class of all three buttons is "openbtn".

答:
Okay, thanks to @Ry I have made up a solution. My code looks like this:

.openbtn {
  white-space: nowrap;
  font-size: 25px;
  background-color: #333;
  text-align: left;
  top: 0px;
  color: lightgrey;
  border: none;
  height: 45px;
  z-index: 99999;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="
    height: 45px;
    position: sticky;
    border-bottom: 2px solid lightgrey;
    border-top: 2px solid lightgrey;
    width: fit-content;
    top: 0;
">
  <button class="openbtn" title="Open Menu" onclick="openNav()" style="
    float: left;
">☰</button>

  <button class="openbtn" title="Open Chat" style="/* align-self: stretch; */float: center;"><img src="https://jeffthecow.com/assets/images/Svg-Chat.webp"></button>

  <button class="openbtn" title="Back To Top" style="
    float: right;
"><img src="https://jeffthecow.com/assets/images/ScrollTop.webp"></button>
</div></code>```

Also, it doesn't quite look right if you run the snippet, but you get the idea. Pretty much, I took the three buttons, and wrapped them up nice and tight in a div element, and set the div's position to sticky.

Body:
Okay, thanks to @Ry I have made up a solution. My code looks like this:

.openbtn {
  white-space: nowrap;
  font-size: 25px;
  background-color: #333;
  text-align: left;
  top: 0px;
  color: lightgrey;
  border: none;
  height: 45px;
  z-index: 99999;
}

<div style="
    height: 45px;
    position: sticky;
    border-bottom: 2px solid lightgrey;
    border-top: 2px solid lightgrey;
    width: fit-content;
    top: 0;
">
  <button class="openbtn" title="Open Menu" onclick="openNav()" style="
    float: left;
">&#9776;</button>

  <a target="popup" style="padding: 0px;" onclick="window.open('https://jeffthecow.com/webchat/','name','width=510,height=412')"><button class="openbtn" title="Open Chat" style="/* align-self: stretch; */float: center;"><img src="https://jeffthecow.com/assets/images/Svg-Chat.webp"></button></a>

  <a href="#scrollBtnLocation"><button class="openbtn" title="Back To Top" style="
    float: right;
"><img src="https://jeffthecow.com/assets/images/ScrollTop.webp"></button></a>
</div>

Also, it doesn't quite look right if you run the snippet, but you get the idea. Pretty much, I took the three buttons, and wrapped them up nice and tight in a div element, and set the div's position to sticky.


问:
Having a trouble to applying sass css in react component
I am new in web development If can't explain the problem correctly, please post a comment so at least I can tell more.

Thanks a million in advance will appreciate if anyone can give me a little help

I have an HTML structure where I am trying to apply some CSS which is not working some reason.

I checked the same HTML and CSS in jsfiddle and Code-pen it work perfectly but when I applied the same thing in my react component it's doesn't show up anything

My code:

/*
    Common
*/

.wizard,
.tabcontrol {
  display: block;
  width: 100%;
  overflow: hidden;
}

.wizard a,
.tabcontrol a {
  outline: 0;
}

.wizard ul,
.tabcontrol ul {
  list-style: none !important;
  padding: 0;
  margin: 0;
}

.wizard ul>li,
.tabcontrol ul>li {
  display: block;
  padding: 0;
}

/* Accessibility */

.wizard>.steps .current-info,
.tabcontrol>.steps .current-info {
  position: absolute;
  left: -999em;
}

.wizard>.content>.title,
.tabcontrol>.content>.title {
  position: absolute;
  left: -999em;
}

/*
    Wizard
*/

.wizard>.steps {
  position: relative;
  display: block;
  width: 100%;
}

.wizard.vertical>.steps {
  display: inline;
  float: left;
  width: 30%;
}

.wizard>.steps .number {
  font-size: 1.429em;
}

.wizard>.steps>ul>li {
  width: 25%;
}

.wizard>.steps>ul>li,
.wizard>.actions>ul>li {
  float: left;
}

.wizard.vertical>.steps>ul>li {
  float: none;
  width: 100%;
}

.wizard>.steps a,
.wizard>.steps a:hover,
.wizard>.steps a:active {
  display: block;
  width: auto;
  margin: 0 0.5em 0.5em;
  padding: 1em 1em;
  text-decoration: none;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
}

.wizard>.steps .disabled a,
.wizard>.steps .disabled a:hover,
.wizard>.steps .disabled a:active {
  background: #f3f4fa;
  color: #aaa;
  cursor: default;
}

.wizard>.steps .current a,
.wizard>.steps .current a:hover,
.wizard>.steps .current a:active {
  background: #008cff;
  color: #fff;
  cursor: default;
}

.wizard>.steps .done a,
.wizard>.steps .done a:hover,
.wizard>.steps .done a:active {
  background: #9dc8e2;
  color: #fff;
}

.wizard>.steps .error a,
.wizard>.steps .error a:hover,
.wizard>.steps .error a:active {
  background: #fd3550;
  color: #fff;
}

.wizard>.content {
  background: #f3f4fa;
  display: block;
  margin: 0.5em;
  min-height: 35em;
  overflow: hidden;
  position: relative;
  width: auto;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
}

.wizard.vertical>.content {
  display: inline;
  float: left;
  margin: 0 2.5% 0.5em 2.5%;
  width: 65%;
}

.wizard>.content>.body {
  float: left;
  position: absolute;
  width: 95%;
  height: 95%;
  padding: 2.5%;
}

.wizard>.content>.body ul {
  list-style: disc !important;
}

.wizard>.content>.body ul>li {
  display: list-item;
}

.wizard>.content>.body>iframe {
  border: 0 none;
  width: 100%;
  height: 100%;
}

.wizard>.content>.body input {
  display: block;
  border: 1px solid #ccc;
}

.wizard>.content>.body input[type="checkbox"] {
  display: inline-block;
}

.wizard>.content>.body input.error {
  background: rgb(251, 227, 228);
  border: 1px solid #fbc2c4;
  color: #8a1f11;
}

.wizard>.content>.body label {
  display: inline-block;
  margin-bottom: 0.5em;
}

.wizard>.content>.body label.error {
  color: #8a1f11;
  display: inline-block;
  margin-left: 1.5em;
}

.wizard>.actions {
  position: relative;
  display: block;
  text-align: right;
  width: 100%;
}

.wizard.vertical>.actions {
  display: inline;
  float: right;
  margin: 0 2.5%;
  width: 95%;
}

.wizard>.actions>ul {
  display: inline-block;
  text-align: right;
}

.wizard>.actions>ul>li {
  margin: 0 0.5em;
}

.wizard.vertical>.actions>ul>li {
  margin: 0 0 0 1em;
}

.wizard>.actions a,
.wizard>.actions a:hover,
.wizard>.actions a:active {
  background: #008cff;
  color: #fff;
  display: block;
  padding: 0.5em 1em;
  text-decoration: none;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
}

.wizard>.actions .disabled a,
.wizard>.actions .disabled a:hover,
.wizard>.actions .disabled a:active {
  background: #f3f4fa;
  color: #aaa;
}

.wizard>.loading {}

.wizard>.loading .spinner {}

/*
    Tabcontrol
*/

.tabcontrol>.steps {
  position: relative;
  display: block;
  width: 100%;
}

.tabcontrol>.steps>ul {
  position: relative;
  margin: 6px 0 0 0;
  top: 1px;
  z-index: 1;
}

.tabcontrol>.steps>ul>li {
  float: left;
  margin: 5px 2px 0 0;
  padding: 1px;
  -webkit-border-top-left-radius: 5px;
  -webkit-border-top-right-radius: 5px;
  -moz-border-radius-topleft: 5px;
  -moz-border-radius-topright: 5px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
}

.tabcontrol>.steps>ul>li:hover {
  background: #edecec;
  border: 1px solid #bbb;
  padding: 0;
}

.tabcontrol>.steps>ul>li.current {
  background: #fff;
  border: 1px solid #bbb;
  border-bottom: 0 none;
  padding: 0 0 1px 0;
  margin-top: 0;
}

.tabcontrol>.steps>ul>li>a {
  color: #5f5f5f;
  display: inline-block;
  border: 0 none;
  margin: 0;
  padding: 10px 30px;
  text-decoration: none;
}

.tabcontrol>.steps>ul>li>a:hover {
  text-decoration: none;
}

.tabcontrol>.steps>ul>li.current>a {
  padding: 15px 30px 10px 30px;
}

.tabcontrol>.content {
  position: relative;
  display: inline-block;
  width: 100%;
  height: 35em;
  overflow: hidden;
  border-top: 1px solid #bbb;
  padding-top: 20px;
}

.tabcontrol>.content>.body {
  float: left;
  position: absolute;
  width: 95%;
  height: 95%;
  padding: 2.5%;
}

.tabcontrol>.content>.body ul {
  list-style: disc !important;
}

.tabcontrol>.content>.body ul>li {
  display: list-item;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wizard-vertical" role="application" class="wizard clearfix vertical">
  <div class="steps clearfix">
    <ul role="tablist">
      <li role="tab" class="first current" aria-disabled="false" aria-selected="true">

          <span class="current-info audible">current step: </span>
          <span class="number">1.</span> Account
      </li>
      <li role="tab" class="done" aria-disabled="false" aria-selected="false">

          <span class="number">2.</span> Profile
      </li>
      <li role="tab" class="done" aria-disabled="false" aria-selected="false">

          <span class="number">3.</span> Hints
      </li>
      <li role="tab" class="last done" aria-disabled="false" aria-selected="false">

          <span class="number">4.</span> Finish
      </li>
    </ul>
  </div>

  <div class="content clearfix">
    <h3 id="wizard-vertical-h-0" tabindex="-1" class="title current">Account</h3>
    <section id="wizard-vertical-p-0" role="tabpanel" aria-labelledby="wizard-vertical-h-0" class="body current" aria-hidden="false" style="display: block;">
      <div class="form-group">
        <label>User name *</label>
        <input class="form-control" type="text" />
      </div>
      <div class="form-group">
        <label> Password *</label>
        <input type="text" class="form-control" />
      </div>
      <div class="form-group">
        <label>Confirm Password *</label>
        <input type="text" class="form-control" />
      </div>
      <div class="form-group">
        <label class="col-lg-12">(*) Mandatory</label>
      </div>
    </section>
    <h3 id="wizard-vertical-h-1" tabindex="-1" class="title">Profile</h3>
    <section id="wizard-vertical-p-1" role="tabpanel" aria-labelledby="wizard-vertical-h-1" class="body" aria-hidden="true" style="display: none;">
      <div class="form-group">
        <label> First name *</label>
        <input type="text" class="form-control" />
      </div>
      <div class="form-group">
        <label> Last name *</label>
        <input type="text" class="form-control" />
      </div>

      <div class="form-group">
        <label>Email *</label>
        <input type="text" class="form-control" />
      </div>

      <div class="form-group">
        <label>Address *</label>
        <input type="text" class="form-control" />
      </div>

      <div class="form-group">
        <label class="col-lg-12">(*) Mandatory</label>
      </div>
    </section>

    <h3 id="wizard-vertical-h-2" tabindex="-1" class="title">Hints</h3>
    <section id="wizard-vertical-p-2" role="tabpanel" aria-labelledby="wizard-vertical-h-2" class="body" aria-hidden="true" style="display: none;">
      <div class="form-group">
        <div class="col-lg-12">
          <ul>
            <li>Jonathan Smith </li>
            <li>Lab</li>
            <li>jonathan@example.com</li>
            <li>Your city, Cityname</li>
          </ul>
        </div>
      </div>

    </section>
    <h3 id="wizard-vertical-h-3" tabindex="-1" class="title">Finish</h3>
    <section id="wizard-vertical-p-3" role="tabpanel" aria-labelledby="wizard-vertical-h-3" class="body" aria-hidden="true" style="display: none;">
      <div class="form-group">
        <div class="col-lg-12">
          <div class="checkbox checkbox-primary">
            <input id="checkbox-v" type="checkbox" />
            <label for="checkbox-v">
                                        I agree with the Terms and Conditions.
                                    </label>
          </div>
        </div>
      </div>
    </section>

  </div>
  <div class="actions clearfix">
    <ul role="menu" aria-label="Pagination">
      <li class="disabled" aria-disabled="true">
        Previous</li>
      <li aria-hidden="false" aria-disabled="false" class="" style="display: block;">
        Next</li>
      <li aria-hidden="true" style="display: none;">
        Finish
      </li>
    </ul>
  </div>
</div></code>```

答: you have to link the css file to HTML document. You can use  where custom.css is the css file where you write styles. It works on jsfiddle because we dont have to define the link between css file and HTML document</p>

Body:
I am new in web development If can't explain the problem correctly, please post a comment so at least I can tell more.

Thanks a million in advance will appreciate if anyone can give me a little help

I have an HTML structure where I am trying to apply some CSS which is not working some reason.

I checked the same HTML and CSS in jsfiddle and Code-pen it work perfectly but when I applied the same thing in my react component it's doesn't show up anything

My code:

/*
    Common
*/

.wizard,
.tabcontrol {
  display: block;
  width: 100%;
  overflow: hidden;
}

.wizard a,
.tabcontrol a {
  outline: 0;
}

.wizard ul,
.tabcontrol ul {
  list-style: none !important;
  padding: 0;
  margin: 0;
}

.wizard ul>li,
.tabcontrol ul>li {
  display: block;
  padding: 0;
}

/* Accessibility */

.wizard>.steps .current-info,
.tabcontrol>.steps .current-info {
  position: absolute;
  left: -999em;
}

.wizard>.content>.title,
.tabcontrol>.content>.title {
  position: absolute;
  left: -999em;
}

/*
    Wizard
*/

.wizard>.steps {
  position: relative;
  display: block;
  width: 100%;
}

.wizard.vertical>.steps {
  display: inline;
  float: left;
  width: 30%;
}

.wizard>.steps .number {
  font-size: 1.429em;
}

.wizard>.steps>ul>li {
  width: 25%;
}

.wizard>.steps>ul>li,
.wizard>.actions>ul>li {
  float: left;
}

.wizard.vertical>.steps>ul>li {
  float: none;
  width: 100%;
}

.wizard>.steps a,
.wizard>.steps a:hover,
.wizard>.steps a:active {
  display: block;
  width: auto;
  margin: 0 0.5em 0.5em;
  padding: 1em 1em;
  text-decoration: none;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
}

.wizard>.steps .disabled a,
.wizard>.steps .disabled a:hover,
.wizard>.steps .disabled a:active {
  background: #f3f4fa;
  color: #aaa;
  cursor: default;
}

.wizard>.steps .current a,
.wizard>.steps .current a:hover,
.wizard>.steps .current a:active {
  background: #008cff;
  color: #fff;
  cursor: default;
}

.wizard>.steps .done a,
.wizard>.steps .done a:hover,
.wizard>.steps .done a:active {
  background: #9dc8e2;
  color: #fff;
}

.wizard>.steps .error a,
.wizard>.steps .error a:hover,
.wizard>.steps .error a:active {
  background: #fd3550;
  color: #fff;
}

.wizard>.content {
  background: #f3f4fa;
  display: block;
  margin: 0.5em;
  min-height: 35em;
  overflow: hidden;
  position: relative;
  width: auto;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
}

.wizard.vertical>.content {
  display: inline;
  float: left;
  margin: 0 2.5% 0.5em 2.5%;
  width: 65%;
}

.wizard>.content>.body {
  float: left;
  position: absolute;
  width: 95%;
  height: 95%;
  padding: 2.5%;
}

.wizard>.content>.body ul {
  list-style: disc !important;
}

.wizard>.content>.body ul>li {
  display: list-item;
}

.wizard>.content>.body>iframe {
  border: 0 none;
  width: 100%;
  height: 100%;
}

.wizard>.content>.body input {
  display: block;
  border: 1px solid #ccc;
}

.wizard>.content>.body input[type="checkbox"] {
  display: inline-block;
}

.wizard>.content>.body input.error {
  background: rgb(251, 227, 228);
  border: 1px solid #fbc2c4;
  color: #8a1f11;
}

.wizard>.content>.body label {
  display: inline-block;
  margin-bottom: 0.5em;
}

.wizard>.content>.body label.error {
  color: #8a1f11;
  display: inline-block;
  margin-left: 1.5em;
}

.wizard>.actions {
  position: relative;
  display: block;
  text-align: right;
  width: 100%;
}

.wizard.vertical>.actions {
  display: inline;
  float: right;
  margin: 0 2.5%;
  width: 95%;
}

.wizard>.actions>ul {
  display: inline-block;
  text-align: right;
}

.wizard>.actions>ul>li {
  margin: 0 0.5em;
}

.wizard.vertical>.actions>ul>li {
  margin: 0 0 0 1em;
}

.wizard>.actions a,
.wizard>.actions a:hover,
.wizard>.actions a:active {
  background: #008cff;
  color: #fff;
  display: block;
  padding: 0.5em 1em;
  text-decoration: none;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
}

.wizard>.actions .disabled a,
.wizard>.actions .disabled a:hover,
.wizard>.actions .disabled a:active {
  background: #f3f4fa;
  color: #aaa;
}

.wizard>.loading {}

.wizard>.loading .spinner {}

/*
    Tabcontrol
*/

.tabcontrol>.steps {
  position: relative;
  display: block;
  width: 100%;
}

.tabcontrol>.steps>ul {
  position: relative;
  margin: 6px 0 0 0;
  top: 1px;
  z-index: 1;
}

.tabcontrol>.steps>ul>li {
  float: left;
  margin: 5px 2px 0 0;
  padding: 1px;
  -webkit-border-top-left-radius: 5px;
  -webkit-border-top-right-radius: 5px;
  -moz-border-radius-topleft: 5px;
  -moz-border-radius-topright: 5px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
}

.tabcontrol>.steps>ul>li:hover {
  background: #edecec;
  border: 1px solid #bbb;
  padding: 0;
}

.tabcontrol>.steps>ul>li.current {
  background: #fff;
  border: 1px solid #bbb;
  border-bottom: 0 none;
  padding: 0 0 1px 0;
  margin-top: 0;
}

.tabcontrol>.steps>ul>li>a {
  color: #5f5f5f;
  display: inline-block;
  border: 0 none;
  margin: 0;
  padding: 10px 30px;
  text-decoration: none;
}

.tabcontrol>.steps>ul>li>a:hover {
  text-decoration: none;
}

.tabcontrol>.steps>ul>li.current>a {
  padding: 15px 30px 10px 30px;
}

.tabcontrol>.content {
  position: relative;
  display: inline-block;
  width: 100%;
  height: 35em;
  overflow: hidden;
  border-top: 1px solid #bbb;
  padding-top: 20px;
}

.tabcontrol>.content>.body {
  float: left;
  position: absolute;
  width: 95%;
  height: 95%;
  padding: 2.5%;
}

.tabcontrol>.content>.body ul {
  list-style: disc !important;
}

.tabcontrol>.content>.body ul>li {
  display: list-item;
}

          current step:
          1. Account

          2. Profile

          3. Hints

          4. Finish

Account

        User name *
        <input class="form-control" type="text" />

         Password *
        <input type="text" class="form-control" />

        Confirm Password *
        <input type="text" class="form-control" />

        (*) Mandatory

Profile

         First name *
        <input type="text" class="form-control" />

         Last name *
        <input type="text" class="form-control" />

        Email *
        <input type="text" class="form-control" />

        Address *
        <input type="text" class="form-control" />

        (*) Mandatory

Hints

Jonathan Smith

Lab

jonathan@example.com

Your city, Cityname

Finish

            <input id="checkbox-v" type="checkbox" />

                                        I agree with the Terms and Conditions.

        Previous

        Next

        Finish


问:
How to get DayOfWeek from an Instant.now()
Assuming the following code...

```<code>Instant x = Instant.now();
</code>```

How do I get day of week from x?

答:
You have to convert it to ZonedDateTime

```<code>Instant.now().atZone(ZoneId.systemDefault()).getDayOfWeek()
</code>```

Body:
Assuming the following code...

Instant x = Instant.now();

How do I get day of week from x?

Body:
You have to convert it to ZonedDateTime

Instant.now().atZone(ZoneId.systemDefault()).getDayOfWeek()


问:
How to override "OnActionExecuting" defined in the Startup class inside a controller?
This code run for every incoming request to check whether it contains a valid JWT token.

```<code>services.AddMvc(options =>
       options.Filters.Add(typeof(JwtAttribute)));
</code>```

That's what I want in most case, except for the first time (when the user is attempting to log in). Because it's running at every request, user can't log in.

I've tried to add an attribute on top of the login action, but it's still not working.

```<code>[HttpPost]
[AllowAnonymous]
public async Task<JsonResult> Login([FromBody]Credentials formData)
{

}
</code>```

What should I do to override the OnActionExecuting in the startup class just in this one case, so that user can log in.

Thanks for helping

答:
By using a custom filter, instead of the built-in authentication and authorization system, you will not be able to use [AllowAnonymous] here since that is directly linked to the auth framework.

What you can do is add additional metadata which you then check as part of your JwtAttribute filter. For example, create another attribute like so:

```<code>public class DisableJwtAttribute : Attribute, IFilterMetadata
{ }
</code>```

You can now add this attribute to your controller action with [DisableJwt].

And inside of your JwtAttribute filter, you can now check for that filter’s existence to stop processing the request. E.g. if your filter is an authorization filter, that would look like this:

```<code>public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
    if (context.Filters.Any(item => item is DisableJwtAttribute))
        return;

    // filter is active
}
</code>```

That being said, the better solution would be to embrace the authentication system and have your JWT validation be part of the normal authentication process. That way, you could actually benefit from all the authentication and authorization things within ASP.NET Core.

Body:
This code run for every incoming request to check whether it contains a valid JWT token.

services.AddMvc(options =>
       options.Filters.Add(typeof(JwtAttribute)));

That's what I want in most case, except for the first time (when the user is attempting to log in). Because it's running at every request, user can't log in.

I've tried to add an attribute on top of the login action, but it's still not working.

[HttpPost]
[AllowAnonymous]
public async Task<JsonResult> Login([FromBody]Credentials formData)
{

}

What should I do to override the OnActionExecuting in the startup class just in this one case, so that user can log in.

Thanks for helping

Body:
By using a custom filter, instead of the built-in authentication and authorization system, you will not be able to use [AllowAnonymous] here since that is directly linked to the auth framework.

What you can do is add additional metadata which you then check as part of your JwtAttribute filter. For example, create another attribute like so:

public class DisableJwtAttribute : Attribute, IFilterMetadata
{ }

You can now add this attribute to your controller action with [DisableJwt].

And inside of your JwtAttribute filter, you can now check for that filter’s existence to stop processing the request. E.g. if your filter is an authorization filter, that would look like this:

public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
    if (context.Filters.Any(item => item is DisableJwtAttribute))
        return;

    // filter is active
}

That being said, the better solution would be to embrace the authentication system and have your JWT validation be part of the normal authentication process. That way, you could actually benefit from all the authentication and authorization things within ASP.NET Core.


问:
Pandas plotting graph with timestamp
pandas 0.23.4
python 3.5.3

I have some code that looks like below

```<code>import pandas as pd
from datetime import datetime

from matplotlib import pyplot

def dateparse():
    return datetime.strptime("2019-05-28T00:06:20,927", '%Y-%m-%dT%H:%M:%S,%f')

series = pd.read_csv('sample.csv', delimiter=";", parse_dates=True,
                     date_parser=dateparse, header=None)
series.plot()
pyplot.show()
</code>```

The CSV file looks like below

```<code>2019-05-28T00:06:20,167;2070
2019-05-28T00:06:20,426;147
2019-05-28T00:06:20,927;453
2019-05-28T00:06:22,688;2464
2019-05-28T00:06:27,260;216
</code>```

As you can see 2019-05-28T00:06:20,167 is the timestamp with milliseconds and 2070 is the value that I want plotted.

When I run this the graph gets printed however on the X-Axis I see numbers which is a bit odd. I was expecting to see actual timestamps (like MS Excel). Can someone tell me what I am doing wrong?

答:
You did not set datetime as index. Aslo, you don't need a date parser, just pass the columns you want to parse:

```<code>dfstr = '''2019-05-28T00:06:20,167;2070
2019-05-28T00:06:20,426;147
2019-05-28T00:06:20,927;453
2019-05-28T00:06:22,688;2464
2019-05-28T00:06:27,260;216'''

df = pd.read_csv(pd.compat.StringIO(dfstr), sep=';',
                 header=None, parse_dates=[0])

plt.plot(df[0], df[1])
plt.show()
</code>```

Output:

Or:

```<code>df.set_index(0)[1].plot()
</code>```

gives a little better plot:

Title: Pandas plotting graph with timestamp

Body:
pandas 0.23.4
python 3.5.3

I have some code that looks like below

import pandas as pd
from datetime import datetime

from matplotlib import pyplot

def dateparse():
    return datetime.strptime("2019-05-28T00:06:20,927", '%Y-%m-%dT%H:%M:%S,%f')

series = pd.read_csv('sample.csv', delimiter=";", parse_dates=True,
                     date_parser=dateparse, header=None)
series.plot()
pyplot.show()

The CSV file looks like below

2019-05-28T00:06:20,167;2070
2019-05-28T00:06:20,426;147
2019-05-28T00:06:20,927;453
2019-05-28T00:06:22,688;2464
2019-05-28T00:06:27,260;216

As you can see 2019-05-28T00:06:20,167 is the timestamp with milliseconds and 2070 is the value that I want plotted.

When I run this the graph gets printed however on the X-Axis I see numbers which is a bit odd. I was expecting to see actual timestamps (like MS Excel). Can someone tell me what I am doing wrong?

Body:
You did not set datetime as index. Aslo, you don't need a date parser, just pass the columns you want to parse:

dfstr = '''2019-05-28T00:06:20,167;2070
2019-05-28T00:06:20,426;147
2019-05-28T00:06:20,927;453
2019-05-28T00:06:22,688;2464
2019-05-28T00:06:27,260;216'''

df = pd.read_csv(pd.compat.StringIO(dfstr), sep=';',
                 header=None, parse_dates=[0])

plt.plot(df[0], df[1])
plt.show()

Output:

Or:

df.set_index(0)[1].plot()

gives a little better plot:


答:
Provide below @Component() in MasterConfig class. Here it is like this. It is better to provide @Primary() also.</p>

```<code>@Component() @primary()
@Getter
@Setter
@ToString
public class MasterConfig {

    @NotNull
    @JsonProperty( "traffic_mappings" )
    private List<TrafficMapping> trafficMappings;
}
</code>```

Title: UnsatisfiedDependencyException: Error creating bean with name 'trafficMapper'

Body:
Provide below @Component() in MasterConfig class. Here it is like this. It is better to provide @Primary() also.

@Component() @primary()
@Getter
@Setter
@ToString
public class MasterConfig {

    @NotNull
    @JsonProperty( "traffic_mappings" )
    private List<TrafficMapping> trafficMappings;
}


问:
Angular routing not working when deployed to tomcat 9 (Ubuntu 18.04)
I coded an angular project on my own PC, everything worked fine when I ran it locally with the command ng serve. Now I want to deploy it on tomcat on a VM (provided by my school) because my project needs to be public.

I created a git repository and downloaded the angular project on the VM. Followed a tutorial to deploy the app in tomcat, which simply consisted of 2 steps:

Run ng build --base-href=/angular/ to generate some files

Copy the generated files to tomcat's /webapps subfolder

But it does not work as intended. To me it seems like there's an issue with routing.

Here's my routing module:

```<code>const appRoutes: Routes = [
  {path: 'coachPortal', component: CoachPortalComponent},
  {path: 'userPortal', component: UserPortalComponent},
  {path: 'users', component: UsersComponent},
  {path: 'userDetails/:id', component: UserDetailsComponent},
  {path: 'mySessions', component: MySessionsComponent},
  {path: '', redirectTo: '/coachPortal', pathMatch: 'full'},
  {path: '**', component: CoachPortalComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(appRoutes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

To navigate between routes, I use this old simple code: window.location.href = '/users';

This worked like a charm when I ran it locally on my pc.

But I'm guessing the reason why it's not working anymore after deploying on tomcat is because tomcat adds the prefix angular/.

When running locally on my pc the urls were localhost:4200/{componenturl}.

But on the VM it's x.x.x.x:8080/angular/{componenturl}

But because of the routing redirects I am getting 404 errors. When I first visit the root url x.x.x.x:8080/angular, it matches with the rule {path: '', redirectTo: '/coachPortal', pathMatch: 'full'}. and loads the coachPortal component and even changes the url to angular/coachPortal. But refreshing the page or manually entering angular/coachPortal gives a 404 error. And all other links don't work either.

Also on the coachPortal I have an image with src ../../../assets/logo.png and it obviously doesn't load because of how the generated files in webapps folder have different folder structure... How can I fix this? The image is directly under assets folder.

答:
You can try use useHash: true. For me its working.

Example:

```<code>@NgModule({
    imports: [RouterModule.forRoot(routes, { useHash: true })],
    exports: [RouterModule],
})
</code>```

and url on the VM will be x.x.x.x:8080/angular/#/{componenturl}

Body:
I coded an angular project on my own PC, everything worked fine when I ran it locally with the command ng serve. Now I want to deploy it on tomcat on a VM (provided by my school) because my project needs to be public.

I created a git repository and downloaded the angular project on the VM. Followed a tutorial to deploy the app in tomcat, which simply consisted of 2 steps:

Run ng build --base-href=/angular/ to generate some files

Copy the generated files to tomcat's /webapps subfolder

But it does not work as intended. To me it seems like there's an issue with routing.

Here's my routing module:

const appRoutes: Routes = [
  {path: 'coachPortal', component: CoachPortalComponent},
  {path: 'userPortal', component: UserPortalComponent},
  {path: 'users', component: UsersComponent},
  {path: 'userDetails/:id', component: UserDetailsComponent},
  {path: 'mySessions', component: MySessionsComponent},
  {path: '', redirectTo: '/coachPortal', pathMatch: 'full'},
  {path: '**', component: CoachPortalComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(appRoutes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

To navigate between routes, I use this old simple code: window.location.href = '/users';

This worked like a charm when I ran it locally on my pc.

But I'm guessing the reason why it's not working anymore after deploying on tomcat is because tomcat adds the prefix angular/.

When running locally on my pc the urls were localhost:4200/{componenturl}.

But on the VM it's x.x.x.x:8080/angular/{componenturl}

But because of the routing redirects I am getting 404 errors. When I first visit the root url x.x.x.x:8080/angular, it matches with the rule {path: '', redirectTo: '/coachPortal', pathMatch: 'full'}. and loads the coachPortal component and even changes the url to angular/coachPortal. But refreshing the page or manually entering angular/coachPortal gives a 404 error. And all other links don't work either.

Also on the coachPortal I have an image with src ../../../assets/logo.png and it obviously doesn't load because of how the generated files in webapps folder have different folder structure... How can I fix this? The image is directly under assets folder.

Body:
You can try use useHash: true. For me its working.

Example:

@NgModule({
    imports: [RouterModule.forRoot(routes, { useHash: true })],
    exports: [RouterModule],
})

and url on the VM will be x.x.x.x:8080/angular/#/{componenturl}


问:
Terraform AWS credentials file not found
In reading the docs over at Terraform it says there are 3 options for finding AWS credientials:

Static Credentials( embedded in the source file )

Environment variables.

From the AWS credentials file

I am trying to have my setup just use the credential file. I've checked that the environment variables are cleared and I have left the relevant variables in Terraform blank.

When I do this and run 'Terraform Plan' I get the error:

No Valid credential sources found for AWS Provider.

I've even tried adding the location of my credentials file into my provider block and that didn't help either:

```<code>provider "aws" {
    region  = "${var.region}"
    profile = "${var.profile}"
    shared_credentials_file = "/Users/david/.aws/credentials"
    profile = "testing"
}
</code>```

Is there something I'm missing to get Terraform to read this file and not require environment variables?

答:
I just had this same problem with terraform aws provider (2.12.0) and this is how I solved it.

In my case the provider couldn't handle that my default profile in $HOME/.aws/credentials did NOT have my access key and secret but it had a "source_profile" in it instead.  It seems the terraform aws provider cannot handle this (yet this works for Java SDK and AWS CLI just fine since I've had this setup for awhile now).

Here is what I had that didn't work, notice the default profile has a role_arn and source_profile:

```<code>[default]
role_arn = arn:aws:iam::<ACCT_ID>:role/readonly
source_profile = account
region = us-east-1

[other-profile]
role_arn = arn:aws:iam::<ACCT_ID>:role/other-role
source_profile = account
region = us-east-1

[account]
region = us-east-1
aws_access_key_id=****
aws_secret_access_key=****
</code>```

I changed it to the following which resulted in the aws provider working for me.  Notice I consolidated two profiles into the "default" profile:

```<code>[other-profile]
role_arn = arn:aws:iam::<ACCT_ID>:role/other-role
source_profile = default
region = us-east-1

[default]
region = us-east-1
aws_access_key_id=****
aws_secret_access_key=****
role_arn = arn:aws:iam::<ACCT_ID>:role/readonly
source_profile = default
</code>```

This seems to work fine for the AWS CLI (defaults to the readonly role and supports switching to "other-profile") as well as allowing terraform to read credentials correctly.

Body:
In reading the docs over at Terraform it says there are 3 options for finding AWS credientials:

Static Credentials( embedded in the source file )

Environment variables.

From the AWS credentials file

I am trying to have my setup just use the credential file. I've checked that the environment variables are cleared and I have left the relevant variables in Terraform blank.

When I do this and run 'Terraform Plan' I get the error:

No Valid credential sources found for AWS Provider.

I've even tried adding the location of my credentials file into my provider block and that didn't help either:

provider "aws" {
    region  = "${var.region}"
    profile = "${var.profile}"
    shared_credentials_file = "/Users/david/.aws/credentials"
    profile = "testing"
}

Is there something I'm missing to get Terraform to read this file and not require environment variables?

Body:
I just had this same problem with terraform aws provider (2.12.0) and this is how I solved it.

In my case the provider couldn't handle that my default profile in $HOME/.aws/credentials did NOT have my access key and secret but it had a "source_profile" in it instead.  It seems the terraform aws provider cannot handle this (yet this works for Java SDK and AWS CLI just fine since I've had this setup for awhile now).

Here is what I had that didn't work, notice the default profile has a role_arn and source_profile:

[default]
role_arn = arn:aws:iam::<ACCT_ID>:role/readonly
source_profile = account
region = us-east-1

[other-profile]
role_arn = arn:aws:iam::<ACCT_ID>:role/other-role
source_profile = account
region = us-east-1

[account]
region = us-east-1
aws_access_key_id=****
aws_secret_access_key=****

I changed it to the following which resulted in the aws provider working for me.  Notice I consolidated two profiles into the "default" profile:

[other-profile]
role_arn = arn:aws:iam::<ACCT_ID>:role/other-role
source_profile = default
region = us-east-1

[default]
region = us-east-1
aws_access_key_id=****
aws_secret_access_key=****
role_arn = arn:aws:iam::<ACCT_ID>:role/readonly
source_profile = default

This seems to work fine for the AWS CLI (defaults to the readonly role and supports switching to "other-profile") as well as allowing terraform to read credentials correctly.


问:
Hashing types at compile-time in C++17/C++2a
Consider the following code:

```<code>#include <iostream>
#include <type_traits>

template <class T>
constexpr std::size_t type_hash(T) noexcept
{
    // Compute a hash for the type
    // DO SOMETHING SMART HERE
}

int main(int argc, char* argv[])
{
    auto x = []{};
    auto y = []{};
    auto z = x;
    std::cout << std::is_same_v<decltype(x), decltype(y)> << std::endl; // 0
    std::cout << std::is_same_v<decltype(x), decltype(z)> << std::endl; // 1
    constexpr std::size_t xhash = type_hash(x);
    constexpr std::size_t yhash = type_hash(y);
    constexpr std::size_t zhash = type_hash(z);
    std::cout << (xhash == yhash) << std::endl; // should be 0
    std::cout << (yhash == zhash) << std::endl; // should be 1
    return 0;
}
</code>```

I would like the type_hash function to return a hash key unique to the type, at compile-time. Is there a way to do that in C++17, or in C++2a (ideally only relying on the standard and without relying compiler intrinsics)?

答:
I will agree with the other answers that it's not generally possible as-stated in standard C++ yet, but we may solve a constrained version of the problem.

Since this is all compile-time programming, we cannot have mutable state, so if you're willing to use a new variable for each state change, then something like this is possible:

hash_state1 = hash(type1)

hash_state2 = hash(type2, hash_state1)

hash_state3 = hash(type3, hash_state2)

Where "hash_state" is really just a unique typelist of all the types we've hashed so far. It can also provide a size_t value as a result of hashing a new type.
If a type that we seek to hash is already present in the typelist, we return the index of that type.

This requires quite a bit of boilerplate:

Ensuring types are unique within a typelist: I used @Deduplicator's answer here: https://stackoverflow.com/a/56259838/27678

Finding a type in a unique typelist

Using if constexpr to check if a type is in the typelist (C++17)

Live Demo

Part 1: a unique typelist:

Again, all credit to @Deduplicator's answer here on this part. The following code saves compile-time performance by doing lookups on a typelist in O(log N) time thanks to leaning on the implementation of tuple-cat.

The code is written almost frustratingly generically, but the nice part is that it allows you to work with any generic typelist (tuple, variant, something custom).

```<code>namespace detail {
    template <template <class...> class TT, template <class...> class UU, class... Us>
    auto pack(UU<Us...>)
    -> std::tuple<TT<Us>...>;

    template <template <class...> class TT, class... Ts>
    auto unpack(std::tuple<TT<Ts>...>)
    -> TT<Ts...>;

    template <std::size_t N, class T>
    using TET = std::tuple_element_t<N, T>;

    template <std::size_t N, class T, std::size_t... Is>
    auto remove_duplicates_pack_first(T, std::index_sequence<Is...>)
    -> std::conditional_t<(... || (N > Is && std::is_same_v<TET<N, T>, TET<Is, T>>)), std::tuple<>, std::tuple<TET<N, T>>>;

    template <template <class...> class TT, class... Ts, std::size_t... Is>
    auto remove_duplicates(std::tuple<TT<Ts>...> t, std::index_sequence<Is...> is)
    -> decltype(std::tuple_cat(remove_duplicates_pack_first<Is>(t, is)...));

    template <template <class...> class TT, class... Ts>
    auto remove_duplicates(TT<Ts...> t)
    -> decltype(unpack<TT>(remove_duplicates<TT>(pack<TT>(t), std::make_index_sequence<sizeof...(Ts)>())));
}

template <class T>
using remove_duplicates_t = decltype(detail::remove_duplicates(std::declval<T>()));
</code>```

Next, I declare my own custom typelist for using the above code. A pretty straightforward empty struct that most of you have seen before:

```<code>template<class...> struct typelist{};
</code>```

Part 2: our "hash_state"

"hash_state", which I'm calling hash_token:

```<code>template<size_t N, class...Ts>
struct hash_token
{
    template<size_t M, class... Us>
    constexpr bool operator ==(const hash_token<M, Us...>&)const{return N == M;}
    constexpr size_t value() const{return N;}
};
</code>```

Simply encapsulates a size_t for the hash value (which you can also access via the value() function) and a comparator to check if two hash_tokens are identical (because you can have two different type lists but the same hash value. e.g., if you hash int to get a token and then compare that token to one where you've hashed (int, float, char, int)).

Part 3: type_hash function

Finally our type_hash function:

```<code>template<class T, size_t N, class... Ts>
constexpr auto type_hash(T, hash_token<N, Ts...>) noexcept
{
    if constexpr(std::is_same_v<remove_duplicates_t<typelist<Ts..., T>>, typelist<Ts...>>)
    {
        return hash_token<detail::index_of<T, Ts...>(), Ts...>{};
    }
    else
    {
        return hash_token<N+1, Ts..., T>{};
    }
}

template<class T>
constexpr auto type_hash(T) noexcept
{
    return hash_token<0, T>{};
}
</code>```

The first overload is for the generic case; you've already "hashed" a number of types, and you want to hash yet another one. It checks to see if the type you're hashing has already been hashed, and if so, it returns the index of the type in the unique type list.

To accomplish getting the index of a type in a typelist, I used simple template expansion to save some compile time template instantiations (avoiding a recursive lookup):

```<code>// find the first index of T in Ts (assuming T is in Ts)
template<class T, class... Ts>
constexpr size_t index_of()
{
    size_t index = 0;
    size_t toReturn = 0;
    using swallow = size_t[];
    (void)swallow{0, (void(std::is_same_v<T, Ts> ? toReturn = index : index), ++index)...};

    return toReturn;
}
</code>```

The second overload of type_hash is for creating an initial hash_token starting at 0.

Usage:

```<code>int main()
{
    auto x = []{};
    auto y = []{};
    auto z = x;
    std::cout << std::is_same_v<decltype(x), decltype(y)> << std::endl; // 0
    std::cout << std::is_same_v<decltype(x), decltype(z)> << std::endl; // 1

    constexpr auto xtoken = type_hash(x);
    constexpr auto xytoken = type_hash(y, xtoken);
    constexpr auto xyztoken = type_hash(z, xytoken);
    std::cout << (xtoken == xytoken) << std::endl; // 0
    std::cout << (xtoken == xyztoken) << std::endl; // 1
}
</code>```

Conclusion:

Not really useful in a lot of code, but this may help solve some constrained meta-programming problems.

Body:
Consider the following code:

#include <iostream>
#include <type_traits>

template <class T>
constexpr std::size_t type_hash(T) noexcept
{
    // Compute a hash for the type
    // DO SOMETHING SMART HERE
}

int main(int argc, char* argv[])
{
    auto x = []{};
    auto y = []{};
    auto z = x;
    std::cout << std::is_same_v<decltype(x), decltype(y)> << std::endl; // 0
    std::cout << std::is_same_v<decltype(x), decltype(z)> << std::endl; // 1
    constexpr std::size_t xhash = type_hash(x);
    constexpr std::size_t yhash = type_hash(y);
    constexpr std::size_t zhash = type_hash(z);
    std::cout << (xhash == yhash) << std::endl; // should be 0
    std::cout << (yhash == zhash) << std::endl; // should be 1
    return 0;
}

I would like the type_hash function to return a hash key unique to the type, at compile-time. Is there a way to do that in C++17, or in C++2a (ideally only relying on the standard and without relying compiler intrinsics)?

Body:
I will agree with the other answers that it's not generally possible as-stated in standard C++ yet, but we may solve a constrained version of the problem.

Since this is all compile-time programming, we cannot have mutable state, so if you're willing to use a new variable for each state change, then something like this is possible:

hash_state1 = hash(type1)

hash_state2 = hash(type2, hash_state1)

hash_state3 = hash(type3, hash_state2)

Where "hash_state" is really just a unique typelist of all the types we've hashed so far. It can also provide a size_t value as a result of hashing a new type.
If a type that we seek to hash is already present in the typelist, we return the index of that type.

This requires quite a bit of boilerplate:

Ensuring types are unique within a typelist: I used @Deduplicator's answer here: https://stackoverflow.com/a/56259838/27678

Finding a type in a unique typelist

Using if constexpr to check if a type is in the typelist (C++17)

Live Demo

Part 1: a unique typelist:

Again, all credit to @Deduplicator's answer here on this part. The following code saves compile-time performance by doing lookups on a typelist in O(log N) time thanks to leaning on the implementation of tuple-cat.

The code is written almost frustratingly generically, but the nice part is that it allows you to work with any generic typelist (tuple, variant, something custom).

namespace detail {
    template <template <class...> class TT, template <class...> class UU, class... Us>
    auto pack(UU<Us...>)
    -> std::tuple<TT<Us>...>;

    template <template <class...> class TT, class... Ts>
    auto unpack(std::tuple<TT<Ts>...>)
    -> TT<Ts...>;

    template <std::size_t N, class T>
    using TET = std::tuple_element_t<N, T>;

    template <std::size_t N, class T, std::size_t... Is>
    auto remove_duplicates_pack_first(T, std::index_sequence<Is...>)
    -> std::conditional_t<(... || (N > Is && std::is_same_v<TET<N, T>, TET<Is, T>>)), std::tuple<>, std::tuple<TET<N, T>>>;

    template <template <class...> class TT, class... Ts, std::size_t... Is>
    auto remove_duplicates(std::tuple<TT<Ts>...> t, std::index_sequence<Is...> is)
    -> decltype(std::tuple_cat(remove_duplicates_pack_first<Is>(t, is)...));

    template <template <class...> class TT, class... Ts>
    auto remove_duplicates(TT<Ts...> t)
    -> decltype(unpack<TT>(remove_duplicates<TT>(pack<TT>(t), std::make_index_sequence<sizeof...(Ts)>())));
}

template <class T>
using remove_duplicates_t = decltype(detail::remove_duplicates(std::declval<T>()));

Next, I declare my own custom typelist for using the above code. A pretty straightforward empty struct that most of you have seen before:

template<class...> struct typelist{};

Part 2: our "hash_state"

"hash_state", which I'm calling hash_token:

template<size_t N, class...Ts>
struct hash_token
{
    template<size_t M, class... Us>
    constexpr bool operator ==(const hash_token<M, Us...>&)const{return N == M;}
    constexpr size_t value() const{return N;}
};

Simply encapsulates a size_t for the hash value (which you can also access via the value() function) and a comparator to check if two hash_tokens are identical (because you can have two different type lists but the same hash value. e.g., if you hash int to get a token and then compare that token to one where you've hashed (int, float, char, int)).

Part 3: type_hash function

Finally our type_hash function:

template<class T, size_t N, class... Ts>
constexpr auto type_hash(T, hash_token<N, Ts...>) noexcept
{
    if constexpr(std::is_same_v<remove_duplicates_t<typelist<Ts..., T>>, typelist<Ts...>>)
    {
        return hash_token<detail::index_of<T, Ts...>(), Ts...>{};
    }
    else
    {
        return hash_token<N+1, Ts..., T>{};
    }
}

template<class T>
constexpr auto type_hash(T) noexcept
{
    return hash_token<0, T>{};
}

The first overload is for the generic case; you've already "hashed" a number of types, and you want to hash yet another one. It checks to see if the type you're hashing has already been hashed, and if so, it returns the index of the type in the unique type list.

To accomplish getting the index of a type in a typelist, I used simple template expansion to save some compile time template instantiations (avoiding a recursive lookup):

// find the first index of T in Ts (assuming T is in Ts)
template<class T, class... Ts>
constexpr size_t index_of()
{
    size_t index = 0;
    size_t toReturn = 0;
    using swallow = size_t[];
    (void)swallow{0, (void(std::is_same_v<T, Ts> ? toReturn = index : index), ++index)...};

    return toReturn;
}

The second overload of type_hash is for creating an initial hash_token starting at 0.

Usage:

int main()
{
    auto x = []{};
    auto y = []{};
    auto z = x;
    std::cout << std::is_same_v<decltype(x), decltype(y)> << std::endl; // 0
    std::cout << std::is_same_v<decltype(x), decltype(z)> << std::endl; // 1

    constexpr auto xtoken = type_hash(x);
    constexpr auto xytoken = type_hash(y, xtoken);
    constexpr auto xyztoken = type_hash(z, xytoken);
    std::cout << (xtoken == xytoken) << std::endl; // 0
    std::cout << (xtoken == xyztoken) << std::endl; // 1
}

Conclusion:

Not really useful in a lot of code, but this may help solve some constrained meta-programming problems.


问:
How do I count distinct values from same id?
How do I count distinct values from a column if there are some duplicates for each ID?

I've tried COUNT, DISTINCT, CASE and everything but I can't count distinct values for each ID. I have a table like this.

```<code>ID          Symptom
1           Headache
1           Headache
1           Hematuria
1           Leg pain
1           Headache
2           Cough
2           Headache
2           Cough
3           Cough
3           Cough
3           Cough
</code>```

I want to obtain something like this.

```<code>ID    Symptom
1     Headache
1     Hematuria
1     Leg pain
2     Cough
2     Headache
3     Cough
</code>```

Or how do I obtain the total count? Like there are 5 distinct symtomps but not 11 symptoms (If I use DISTINCT I would obtain 4).

答:
Try this:</p>

```<code>SELECT ID, Symptom
FROM MY_TABLE
GROUP BY 1,2
</code>```

Body:
How do I count distinct values from a column if there are some duplicates for each ID?

I've tried COUNT, DISTINCT, CASE and everything but I can't count distinct values for each ID. I have a table like this.

ID          Symptom
1           Headache
1           Headache
1           Hematuria
1           Leg pain
1           Headache
2           Cough
2           Headache
2           Cough
3           Cough
3           Cough
3           Cough

I want to obtain something like this.

ID    Symptom
1     Headache
1     Hematuria
1     Leg pain
2     Cough
2     Headache
3     Cough

Or how do I obtain the total count? Like there are 5 distinct symtomps but not 11 symptoms (If I use DISTINCT I would obtain 4).

Body:
Try this:

SELECT ID, Symptom
FROM MY_TABLE
GROUP BY 1,2


问:
How to get lines from the last match to the end of file?
Need to print lines after the last match to the end of file. The number of matches could be anything and not definite. I have some text as shown below.

```<code>MARKER
aaa
bbb
ccc
MARKER
ddd
eee
fff
MARKER
ggg
hhh
iii
MARKER
jjj
kkk
lll
</code>```

Output desired is

```<code>jjj
kkk
lll
</code>```

Do I use awk with RS and FS to get the desired output?

答:
You can try Perl as well</p>

```<code>$ perl -0777 -ne ' /.*MARKER(.*)/s and print $1 ' input.txt

jjj
kkk
lll

$
</code>```

Body:
Need to print lines after the last match to the end of file. The number of matches could be anything and not definite. I have some text as shown below.

MARKER
aaa
bbb
ccc
MARKER
ddd
eee
fff
MARKER
ggg
hhh
iii
MARKER
jjj
kkk
lll

Output desired is

jjj
kkk
lll

Do I use awk with RS and FS to get the desired output?

Body:
You can try Perl as well

$ perl -0777 -ne ' /.*MARKER(.*)/s and print $1 ' input.txt

jjj
kkk
lll

$