问:
Unable to disable ContextCredentialsAutoConfiguration in Spring boot application
I am working on a Spring Batch application that should use aws cloud only for specific profiles.  Currently I have a profile that uses aws and another that shouldn't as it runs the application locally with a local database, local files, etc.  (Meanwhile the AWS profile will use RDS, S3 ,etc)

For my configuration using the AWS profile I have the following:

```<code>@Configuration
@Profile("!localDev")

public class FileReaderConfigAWS {

@Value("${cloud.aws.s3.bucket}")
private String amazonS3Bucket;

@Autowired
private ResourceLoader resourceLoader;

private static final Logger logger = LoggerFactory.getLogger(FileReaderConfigAWS.class);

@Bean
@StepScope
public FlatFileItemReader<Object> flatFileReader(@Value("#{jobParameters['inputFile']}") String inputFile,  LineMapper
    lineMapper) {
    FlatFileItemReader<Object> flatFileItemReader = new FlatFileItemReader<>();

    flatFileItemReader.setResource(resourceLoader.getResource("s3://" + this.amazonS3Bucket + "/" + inputFile));

    flatFileItemReader.setLineMapper(lineMapper);

    return flatFileItemReader;
}

@Bean
public AbstractFileValidator inputFileValidator() {
    InputS3Validator inputS3Validator = new InputS3Validator();
    inputS3Validator.setRequiredKeys(new String[]{InputFileSystemValidator.INPUT_FILE});
    return inputS3Validator;
}

}
</code>```

For my localDev Profile I have the following:

```<code>@Profile("localDev")
@Configuration
public class FileReaderConfigLocalDev {

@Bean
@StepScope
public FlatFileItemReader<Object> flatFileReader(@Value("#{jobParameters['inputFile']}") String inputFile, LineMapper lineMapper) {
    FlatFileItemReader<Object> flatFileItemReader = new FlatFileItemReader<>();
    flatFileItemReader.setResource(new FileSystemResource(inputFile));

    flatFileItemReader.setLineMapper(lineMapper);

    return flatFileItemReader;
}

@Bean
public AbstractFileValidator inputFileValidator() {
    InputFileSystemValidator inputFileValidator = new InputFileSystemValidator();
    inputFileValidator.setRequiredKeys(new String[]{InputFileSystemValidator.INPUT_FILE});
    return inputFileValidator;
}

}
</code>```

When I try to run the Spring Boot Main class using the localDev profile (-Dspring.profiles.active=localDev) I get the following error:

```<code>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'amazonS3': Invocation of init method failed; nested exception is java.lang.IllegalStateException: There is not EC2 meta data available, because the application is not running in the EC2 environment. Region detection is only possible if the application is running on a EC2 instance
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    ... 18 common frames omitted
Caused by: java.lang.IllegalStateException: There is not EC2 meta data available, because the application is not running in the EC2 environment. Region detection is only possible if the application is running on a EC2 instance
    at org.springframework.util.Assert.state(Assert.java:70) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.cloud.aws.core.region.Ec2MetadataRegionProvider.getRegion(Ec2MetadataRegionProvider.java:39) ~[spring-cloud-aws-core-1.2.1.RELEASE.jar:1.2.1.RELEASE]
    at org.springframework.cloud.aws.core.config.AmazonWebserviceClientFactoryBean.createInstance(AmazonWebserviceClientFactoryBean.java:98) ~[spring-cloud-aws-core-1.2.1.RELEASE.jar:1.2.1.RELEASE]
    at org.springframework.cloud.aws.core.config.AmazonWebserviceClientFactoryBean.createInstance(AmazonWebserviceClientFactoryBean.java:44) ~[spring-cloud-aws-core-1.2.1.RELEASE.jar:1.2.1.RELEASE]
    at org.springframework.beans.factory.config.AbstractFactoryBean.afterPropertiesSet(AbstractFactoryBean.java:134) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    ... 25 common frames omitted
</code>```

As I started debugging I found that once you add spring-cloud-aws-autoconfigure to your pom.xml then there seems to be no way to disable aws autoconfigure for non-aws environments at runtime.

I tried the following:

```<code>@EnableAutoConfiguration(exclude = {ContextCredentialsAutoConfiguration.class, ContextStackAutoConfiguration.class})
</code>```

but still won't work, any ideas anyone?

Thanks in advance!

答:
As for version of spring cloud Brixton.SR7, to configure manually the region you would set in your application.properties (or .xml, .yml whatever you're using). This parameter should be ONLY for your dev env, unless you truly need to specify it.

```<code>cloud.aws.region.static=us-east-1
</code>```

I also had to set next property for dev, but maybe you dont need it.

```<code>cloud.aws.stack.auto=false
</code>```

more reference information in http://cloud.spring.io/spring-cloud-static/spring-cloud-aws/1.1.4.RELEASE/#_region_configuration

Body:
I am working on a Spring Batch application that should use aws cloud only for specific profiles.  Currently I have a profile that uses aws and another that shouldn't as it runs the application locally with a local database, local files, etc.  (Meanwhile the AWS profile will use RDS, S3 ,etc)

For my configuration using the AWS profile I have the following:

@Configuration
@Profile("!localDev")

public class FileReaderConfigAWS {

@Value("${cloud.aws.s3.bucket}")
private String amazonS3Bucket;

@Autowired
private ResourceLoader resourceLoader;

private static final Logger logger = LoggerFactory.getLogger(FileReaderConfigAWS.class);

@Bean
@StepScope
public FlatFileItemReader<Object> flatFileReader(@Value("#{jobParameters['inputFile']}") String inputFile,  LineMapper
    lineMapper) {
    FlatFileItemReader<Object> flatFileItemReader = new FlatFileItemReader<>();

    flatFileItemReader.setResource(resourceLoader.getResource("s3://" + this.amazonS3Bucket + "/" + inputFile));

    flatFileItemReader.setLineMapper(lineMapper);

    return flatFileItemReader;
}

@Bean
public AbstractFileValidator inputFileValidator() {
    InputS3Validator inputS3Validator = new InputS3Validator();
    inputS3Validator.setRequiredKeys(new String[]{InputFileSystemValidator.INPUT_FILE});
    return inputS3Validator;
}

}

For my localDev Profile I have the following:

@Profile("localDev")
@Configuration
public class FileReaderConfigLocalDev {

@Bean
@StepScope
public FlatFileItemReader<Object> flatFileReader(@Value("#{jobParameters['inputFile']}") String inputFile, LineMapper lineMapper) {
    FlatFileItemReader<Object> flatFileItemReader = new FlatFileItemReader<>();
    flatFileItemReader.setResource(new FileSystemResource(inputFile));

    flatFileItemReader.setLineMapper(lineMapper);

    return flatFileItemReader;
}

@Bean
public AbstractFileValidator inputFileValidator() {
    InputFileSystemValidator inputFileValidator = new InputFileSystemValidator();
    inputFileValidator.setRequiredKeys(new String[]{InputFileSystemValidator.INPUT_FILE});
    return inputFileValidator;
}

}

When I try to run the Spring Boot Main class using the localDev profile (-Dspring.profiles.active=localDev) I get the following error:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'amazonS3': Invocation of init method failed; nested exception is java.lang.IllegalStateException: There is not EC2 meta data available, because the application is not running in the EC2 environment. Region detection is only possible if the application is running on a EC2 instance
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    ... 18 common frames omitted
Caused by: java.lang.IllegalStateException: There is not EC2 meta data available, because the application is not running in the EC2 environment. Region detection is only possible if the application is running on a EC2 instance
    at org.springframework.util.Assert.state(Assert.java:70) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.cloud.aws.core.region.Ec2MetadataRegionProvider.getRegion(Ec2MetadataRegionProvider.java:39) ~[spring-cloud-aws-core-1.2.1.RELEASE.jar:1.2.1.RELEASE]
    at org.springframework.cloud.aws.core.config.AmazonWebserviceClientFactoryBean.createInstance(AmazonWebserviceClientFactoryBean.java:98) ~[spring-cloud-aws-core-1.2.1.RELEASE.jar:1.2.1.RELEASE]
    at org.springframework.cloud.aws.core.config.AmazonWebserviceClientFactoryBean.createInstance(AmazonWebserviceClientFactoryBean.java:44) ~[spring-cloud-aws-core-1.2.1.RELEASE.jar:1.2.1.RELEASE]
    at org.springframework.beans.factory.config.AbstractFactoryBean.afterPropertiesSet(AbstractFactoryBean.java:134) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.7.RELEASE.jar:4.3.7.RELEASE]
    ... 25 common frames omitted

As I started debugging I found that once you add spring-cloud-aws-autoconfigure to your pom.xml then there seems to be no way to disable aws autoconfigure for non-aws environments at runtime.

I tried the following:

@EnableAutoConfiguration(exclude = {ContextCredentialsAutoConfiguration.class, ContextStackAutoConfiguration.class})

but still won't work, any ideas anyone?

Thanks in advance!

Body:
As for version of spring cloud Brixton.SR7, to configure manually the region you would set in your application.properties (or .xml, .yml whatever you're using). This parameter should be ONLY for your dev env, unless you truly need to specify it.

cloud.aws.region.static=us-east-1

I also had to set next property for dev, but maybe you dont need it.

cloud.aws.stack.auto=false

more reference information in http://cloud.spring.io/spring-cloud-static/spring-cloud-aws/1.1.4.RELEASE/#_region_configuration


来源: stackexchange

问:
Appending empty Data frame and list index out of range error
The Line 2:13 is the existing data format which I want it in the format as dispalyed in line 16:19

The Code I have written is

```<code>import xlrd
import pandas as pd

book = xlrd.open_workbook(
    "C:/Users/Vinod/Desktop/DataSet Mining/python-pandas.xlsx")
sheet = book.sheet_by_name('Sheet1')

df1 = pd.DataFrame()

n = sheet.nrows
print(n)
n2 = sheet.ncols
print(n2)

for row_index in range(0, n):
    for col_index in range(0, n2):

        col = sheet.cell(row_index, col_index).value
        df = pd.DataFrame()
        l1 = []
        l2 = []
        l3 = []
        l4 = []
        l5 = []
        l6 = []
        if (col == "Entity Name:"):
            EntityName = sheet.cell(row_index, col_index + 1).value

        if (col == "Counterparty Name:"):
            CounterpartyName = sheet.cell(row_index, col_index + 1).value
        if (col == "TradeRef"):
            row_index = row_index + 1
            value_1 = sheet.cell(row_index, col_index).value

            while (value_1 != ""):

                TradeRef = sheet.cell(row_index, col_index).value

                TradeDate = sheet.cell(row_index, col_index + 1).value

                TradeType = sheet.cell(row_index, col_index + 2).value
                ConfirmationMedium = sheet.cell(row_index, col_index + 3).value

                l1.append(TradeRef)
                l2.append(TradeDate)
                l3.append(TradeType)
                l4.append(ConfirmationMedium)

                row_index = row_index + 1
                if (row_index >= n):
                    value_1 = ""
                    col_index = 4

                else:
                    value_1 = sheet.cell(row_index, col_index).value
                    print(value_1)

            df['TradeRef'] = l1
            df['TradeDate'] = l2
            df['TradeType'] = l3
            df['ConfirmationMedium'] = l4
            df['EntityName'] = EntityName
            df['CoutrepartyName'] = CounterpartyName
            print(df)
            print(row_index)
            print(col_index)
            df1.append(df)
print(df1)
</code>```

答:
```<code>I got it resolved @Azat
import xlrd
import pandas as pd
book = xlrd.open_workbook("C:/Users/Vinod/Desktop/DataSet Mining/python-pandas.xlsx")
sheet = book.sheet_by_name('Sheet1')
df1=pd.DataFrame()
n=sheet.nrows
n2=sheet.ncols
for row_index in range(0,n):
    for col_index in range(0,n2):

        if(row_index)<n:
            col=sheet.cell(row_index,col_index).value
            df=pd.DataFrame()
            l1=[]
            l2=[]
            l3=[]
            l4=[]
            l5=[]
            l6=[]
            if(col=="Entity Name:"):

                EntityName=sheet.cell(row_index,col_index+1).value

            if(col=="Counterparty Name:"):
                CounterpartyName=sheet.cell(row_index,col_index+1).value
            if(col=="TradeRef"):
                row_index=row_index+1
                value_1=sheet.cell(row_index,col_index).value

                while( value_1!=""):

                  TradeRef=sheet.cell(row_index,col_index).value

                  TradeDate=sheet.cell(row_index,col_index+1).value

                  TradeType=sheet.cell(row_index,col_index+2).value
                  ConfirmationMedium=sheet.cell(row_index,col_index+3).value

                  l1.append(TradeRef)
                  l2.append(TradeDate)
                  l3.append(TradeType)
                  l4.append(ConfirmationMedium)

                  row_index=row_index+1
                  if(row_index>=n):

                      value_1=""
                      col_index=4

                  else:
                     value_1=sheet.cell(row_index,col_index).value

                df['TradeRef']=l1
                df['TradeDate']=l2
                df['TradeType']=l3
                df['ConfirmationMedium']=l4
                df['EntityName']=EntityName
                df['CoutrepartyName']=CounterpartyName
                df1=df1.append(df)
print(df1)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The Line 2:13 is the existing data format which I want it in the format as dispalyed in line 16:19

The Code I have written is

import xlrd
import pandas as pd

book = xlrd.open_workbook(
    "C:/Users/Vinod/Desktop/DataSet Mining/python-pandas.xlsx")
sheet = book.sheet_by_name('Sheet1')

df1 = pd.DataFrame()

n = sheet.nrows
print(n)
n2 = sheet.ncols
print(n2)

for row_index in range(0, n):
    for col_index in range(0, n2):

        col = sheet.cell(row_index, col_index).value
        df = pd.DataFrame()
        l1 = []
        l2 = []
        l3 = []
        l4 = []
        l5 = []
        l6 = []
        if (col == "Entity Name:"):
            EntityName = sheet.cell(row_index, col_index + 1).value

        if (col == "Counterparty Name:"):
            CounterpartyName = sheet.cell(row_index, col_index + 1).value
        if (col == "TradeRef"):
            row_index = row_index + 1
            value_1 = sheet.cell(row_index, col_index).value

            while (value_1 != ""):

                TradeRef = sheet.cell(row_index, col_index).value

                TradeDate = sheet.cell(row_index, col_index + 1).value

                TradeType = sheet.cell(row_index, col_index + 2).value
                ConfirmationMedium = sheet.cell(row_index, col_index + 3).value

                l1.append(TradeRef)
                l2.append(TradeDate)
                l3.append(TradeType)
                l4.append(ConfirmationMedium)

                row_index = row_index + 1
                if (row_index >= n):
                    value_1 = ""
                    col_index = 4

                else:
                    value_1 = sheet.cell(row_index, col_index).value
                    print(value_1)

            df['TradeRef'] = l1
            df['TradeDate'] = l2
            df['TradeType'] = l3
            df['ConfirmationMedium'] = l4
            df['EntityName'] = EntityName
            df['CoutrepartyName'] = CounterpartyName
            print(df)
            print(row_index)
            print(col_index)
            df1.append(df)
print(df1)


问:
Create PDF file from PHP
I am trying to create an PDF file from a PHP page with jsPDF but it is not working and I dont know whats wrong.

Can someone help me?

First I have a Iframe. The page I want to convert is displayed in the Iframe:

Iframe:

```<code><?php
    <iframe id="frame" name="frame" width="100%" height="1160px" frameborder="0" src="./page.php?id=' . $_GET['id'] . '"></iframe>
    <button id="cmd">Button</button>
?>
</code>```

When I hit Button the following script should convert the page to PDF

Script

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
<script type="text/javascript">
    var doc = new jsPDF();

    var specialElementHandlers = {
        '#editor': function(element, renderer){
            return true;
        }
    };

    $('#cmd').click(function () {
        doc.fromHTML($('frame').get(0), 15, 15, {
            'width': 170,
            'elementHandlers': specialElementHandlers
        });

    doc.save('sample-file.pdf');
    });
</script>
</code>```

But when I hit Button. Nothing is happening. Does someone know whats wrong?

答:
Apparently, jsPDF has limitations and/or bugs. It has problems with complex tables (especially with colspans). It throws javascript errors which stops the renderer which is why you're getting blank pdfs.

https://github.com/MrRio/jsPDF/issues/516

https://github.com/MrRio/jsPDF/issues/595

A fork has been posted here: https://github.com/jutunen/jsPDF-table_2 but I'm not sure if it addresses other limitations of jsPDF.

Title: Create PDF file from PHP

Body:
I am trying to create an PDF file from a PHP page with jsPDF but it is not working and I dont know whats wrong.

Can someone help me?

First I have a Iframe. The page I want to convert is displayed in the Iframe:

Iframe:

<?php

    <button id="cmd">Button</button>
?>

When I hit Button the following script should convert the page to PDF

Script

But when I hit Button. Nothing is happening. Does someone know whats wrong?


问:
Calling a method of MainActivity from other class
I am developing an Android app and thus, I have a MainActivity class. Inside of that MainActivity class, I have a method, let's call it doSomething():

```<code>public class MainActivity extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void doSomething(){
        // bla bla bla
    }
}
</code>```

I also have a different class (with different layout) that is called OtherActivity. I want to use the doSomething method inside it:

```<code>public class OtherActivity extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.other_activity_layout);

        // Let's use doSomething()
    }
}
</code>```

I tried this:

```<code>public class OtherActivity extends AppCompatActivity {
    MainActivity main;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.other_activity_layout);

        // Let's use doSomething()
        MainActivity main = new MainActivity();
        main.doSomething();
    }
}
</code>```

But it does not work. I also tried to make OtherActivity to extend the MainActivity, doing the following:

```<code>public class OtherActivity extends MainActivity{
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.other_activity_layout);

        // Let's use doSomething()
        super.doSomething();
    }
}
</code>```

But it does not allow me to initialize the layout...

How can I do?

Thanks in advance.

答:
Something like this should do the trick, I'm going to make a static navigator to handle your navigation logic.  If you are opposed to static methods you could also make them on your Application object to make it easier to manage dependencies, I'm just making it static for simplicity.

```<code>//Making this fully static for simplicity, this is fine for a small app
//you can make it a singleton on the application class for more flexibility
public class Navigator {
    //static member vars that determine navigation
    // pass in Context if needed for navigation purposes
    public static void doSomething(Context context){
        // bla bla bla
    }
}

public class MainActivity extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity_layout);
    }

    private void doSomething() {
        Navigator.doSomething(this);
    }
}

public class OtherActivity extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.other_activity_layout);
    }

    private void doSomething() {
        Navigator.doSomething(this);
    }
}
</code>```

Body:
I am developing an Android app and thus, I have a MainActivity class. Inside of that MainActivity class, I have a method, let's call it doSomething():

public class MainActivity extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void doSomething(){
        // bla bla bla
    }
}

I also have a different class (with different layout) that is called OtherActivity. I want to use the doSomething method inside it:

public class OtherActivity extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.other_activity_layout);

        // Let's use doSomething()
    }
}

I tried this:

public class OtherActivity extends AppCompatActivity {
    MainActivity main;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.other_activity_layout);

        // Let's use doSomething()
        MainActivity main = new MainActivity();
        main.doSomething();
    }
}

But it does not work. I also tried to make OtherActivity to extend the MainActivity, doing the following:

public class OtherActivity extends MainActivity{
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.other_activity_layout);

        // Let's use doSomething()
        super.doSomething();
    }
}

But it does not allow me to initialize the layout...

How can I do?

Thanks in advance.

Body:
Something like this should do the trick, I'm going to make a static navigator to handle your navigation logic.  If you are opposed to static methods you could also make them on your Application object to make it easier to manage dependencies, I'm just making it static for simplicity.

//Making this fully static for simplicity, this is fine for a small app
//you can make it a singleton on the application class for more flexibility
public class Navigator {
    //static member vars that determine navigation
    // pass in Context if needed for navigation purposes
    public static void doSomething(Context context){
        // bla bla bla
    }
}

public class MainActivity extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity_layout);
    }

    private void doSomething() {
        Navigator.doSomething(this);
    }
}

public class OtherActivity extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.other_activity_layout);
    }

    private void doSomething() {
        Navigator.doSomething(this);
    }
}


问:
Consume a single generator by multiple filtered generators
I have a file that contain records which look like this:

```<code>>uniqueid#BARCODE1
content content
content content
>uniqueid#BARCODE2
content content
content content
>uniqueid#BARCODE1
content content
content content
...
</code>```

There are ~10 million records with ~300 unique barcodes, and the order of barcodes is random. My goal is to split the file into 300 files. I'd like to do this passing through the file only once with a generator that yields records.

I have solved this problem in the past by reading through the file many times, or by loading the entire file into memory. I'd like to solve the problem using a generator approach to keep memory usage down and to only read through the file once.

Is it possible to instantiate 300 generators and have some logic that dispatches the records to the correct generator? Then I could simply write out the contents of each generator to a file. Would I need to then have handles open to all 300 files I want to write at once?

答:
Yes, it could be done with generators, but we don't need 300 of them, just 1 is enough.

As far as i understand 'uniqueid#BARCODE1' barcode consist of two parts:

'>uniqueid#' prefix,

'BARCODE1' barcode itself.

so let's start with writing simple checker

```<code>BAR_CODE_PREFIX = '>uniqueid#'

def is_bar_code(text):
    return text.startswith(BAR_CODE_PREFIX)
</code>```

then for parsing barcodes contents we can write generator

```<code>def parse_content(lines):
    lines_iterator = iter(lines)
    # we assume that the first line is a barcode
    bar_code = next(lines_iterator)
    contents = []
    for line in lines_iterator:
        if is_bar_code(line):
            # next barcode is found
            yield bar_code, contents
            bar_code = line
            contents = []
        else:
            contents.append(line)
    # to yield last barcode with its contents
    yield bar_code, contents
</code>```

then assuming you want to name files after barcodes we can write

```<code>def split_src(src_path):
    with open(src_path) as src_file:
        for bar_code, content_lines in parse_content(src_file):
            bar_code_index = bar_code[len(BAR_CODE_PREFIX):].rstrip('\n')
            # we use `append` mode
            # because in the different parts of file
            # there are contents of the same barcode
            with open(bar_code_index, mode='a') as dst_file:
                dst_file.writelines(content_lines)
</code>```

which walks exactly one time through whole file.

Test

Let's create src.txt file which consist of

```<code>>uniqueid#BARCODE1
content11
>uniqueid#BARCODE2
content21
>uniqueid#BARCODE1
content12
content12
>uniqueid#BARCODE3
content31
>uniqueid#BARCODE2
content22
</code>```

then after calling

```<code>split_src('src.txt')
</code>```

there will be created next files:

BARCODE1 with lines

```<code>content11
content12
content12
</code>```

BARCODE2 with lines

```<code>content21
content22
</code>```

BARCODE3 with lines

```<code>content31
</code>```

Body:
I have a file that contain records which look like this:

>uniqueid#BARCODE1
content content
content content
>uniqueid#BARCODE2
content content
content content
>uniqueid#BARCODE1
content content
content content
...

There are ~10 million records with ~300 unique barcodes, and the order of barcodes is random. My goal is to split the file into 300 files. I'd like to do this passing through the file only once with a generator that yields records.

I have solved this problem in the past by reading through the file many times, or by loading the entire file into memory. I'd like to solve the problem using a generator approach to keep memory usage down and to only read through the file once.

Is it possible to instantiate 300 generators and have some logic that dispatches the records to the correct generator? Then I could simply write out the contents of each generator to a file. Would I need to then have handles open to all 300 files I want to write at once?

Body:
Yes, it could be done with generators, but we don't need 300 of them, just 1 is enough.

As far as i understand 'uniqueid#BARCODE1' barcode consist of two parts:

'>uniqueid#' prefix,

'BARCODE1' barcode itself.

so let's start with writing simple checker

BAR_CODE_PREFIX = '>uniqueid#'

def is_bar_code(text):
    return text.startswith(BAR_CODE_PREFIX)

then for parsing barcodes contents we can write generator

def parse_content(lines):
    lines_iterator = iter(lines)
    # we assume that the first line is a barcode
    bar_code = next(lines_iterator)
    contents = []
    for line in lines_iterator:
        if is_bar_code(line):
            # next barcode is found
            yield bar_code, contents
            bar_code = line
            contents = []
        else:
            contents.append(line)
    # to yield last barcode with its contents
    yield bar_code, contents

then assuming you want to name files after barcodes we can write

def split_src(src_path):
    with open(src_path) as src_file:
        for bar_code, content_lines in parse_content(src_file):
            bar_code_index = bar_code[len(BAR_CODE_PREFIX):].rstrip('\n')
            # we use `append` mode
            # because in the different parts of file
            # there are contents of the same barcode
            with open(bar_code_index, mode='a') as dst_file:
                dst_file.writelines(content_lines)

which walks exactly one time through whole file.

Test

Let's create src.txt file which consist of

>uniqueid#BARCODE1
content11
>uniqueid#BARCODE2
content21
>uniqueid#BARCODE1
content12
content12
>uniqueid#BARCODE3
content31
>uniqueid#BARCODE2
content22

then after calling

split_src('src.txt')

there will be created next files:

BARCODE1 with lines

content11
content12
content12

BARCODE2 with lines

content21
content22

BARCODE3 with lines

content31


问:
querySelectorAll checked values
I have a list/group of checkboxes, that made by php; put in name="item[]" html property, and then follow with this:

```<code> var list = document.querySelectorAll("input[name^='item[']")
</code>```

So far, works well. I need to count only the checked ones, not all like:

```<code> list.length
</code>```

How can I access the values for eachone to check "checked" property or value?

答:
Rather than looking through your list, you can go back and ask querySelectorAll to return just the checked items:

```<code>var checkedList = document.querySelectorAll("input[name^='item[']:checked")
</code>```

Title: querySelectorAll checked values

Body:
I have a list/group of checkboxes, that made by php; put in name="item[]" html property, and then follow with this:

 var list = document.querySelectorAll("input[name^='item[']")

So far, works well. I need to count only the checked ones, not all like:

 list.length

How can I access the values for eachone to check "checked" property or value?

Body:
Rather than looking through your list, you can go back and ask querySelectorAll to return just the checked items:

var checkedList = document.querySelectorAll("input[name^='item[']:checked")


问:
placeholder value for select not showing when using ngmodel
I am trying to have a select drop down display the first option as a placeholder value

The following code works

```<code><form (ngSubmit)="citySubmit(f)" #f="ngForm">
        <select>
          <option value="" disabled selected>Select Your City</option>
        <option *ngFor="let c of cities" [value]="c">{{c}}</option>
      </select>

      </form>
</code>```

however the following code does not

```<code><form (ngSubmit)="citySubmit(f)" #f="ngForm">
        <select
        [ngModel]="city">
          <option value="" disabled selected>Select Your City</option>
        <option *ngFor="let c of cities" [value]="c">{{c}}</option>
      </select>

      </form>
</code>```

which leads me to believe I am using the ngmodel incorrectly.

Can I have some guidance please.

答:
It should be,

Change

From

```<code> <select [ngModel]="city">
</code>```

To

```<code><select [(ngModel)]="city">
</code>```

Body:
I am trying to have a select drop down display the first option as a placeholder value

The following code works

<form (ngSubmit)="citySubmit(f)" #f="ngForm">
        <select>
          <option value="" disabled selected>Select Your City</option>
        <option *ngFor="let c of cities" [value]="c">{{c}}</option>
      </select>

      </form>

however the following code does not

<form (ngSubmit)="citySubmit(f)" #f="ngForm">
        <select
        [ngModel]="city">
          <option value="" disabled selected>Select Your City</option>
        <option *ngFor="let c of cities" [value]="c">{{c}}</option>
      </select>

      </form>

which leads me to believe I am using the ngmodel incorrectly.

Can I have some guidance please.

Body:
It should be,

Change

From

 <select [ngModel]="city">

To

<select [(ngModel)]="city">


问:
JS if else statement and a reset
I want to prevent any actions if the button attack is not clicked. In this case i want to prevent If attack is clicked you can click on send troops, else alert('You need first to attack!'). Also when the time runs out, i want to the clock disappear if that is possible.

Clock

```<code>   <button class="attack" onclick="startTimer(60,document.querySelector('#time'))">ATTACK</button>
<button class="troops" onclick="send()">SEND TROOPS</button>
</code>```

JS

```<code>function startTimer(duration, display) {
  var timer = duration,minutes, seconds;
  var timers = setInterval(runner, 1000);
  function runner() {
    minutes = parseInt(timer / 60, 10);
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer <= 0) {
     clearInterval(timers)
     finish()
   }
 }

}
</code>```

答:
Do you mean something like this?

function startTimer(duration, display) {

  // Make troops button enabled when attack button is clicked
  document.getElementsByClassName("troops")[0].removeAttribute("disabled");

  var timer = duration,minutes, seconds;
  var timers = setInterval(runner, 1000);
  function runner() {
    minutes = parseInt(timer / 60, 10);
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer <= 0) {
     clearInterval(timers)
     finish()
   }
 }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="attack" onclick="startTimer(60,document.querySelector('#time'))">ATTACK</button>

<!-- declare troops button disabled before attack has been clicked -->
<button class="troops" disabled onclick="send()">SEND TROOPS</button></code>```

Title: JS if else statement and a reset

Body:
I want to prevent any actions if the button attack is not clicked. In this case i want to prevent If attack is clicked you can click on send troops, else alert('You need first to attack!'). Also when the time runs out, i want to the clock disappear if that is possible.

Clock

   <button class="attack" onclick="startTimer(60,document.querySelector('#time'))">ATTACK</button>
<button class="troops" onclick="send()">SEND TROOPS</button>

JS

function startTimer(duration, display) {
  var timer = duration,minutes, seconds;
  var timers = setInterval(runner, 1000);
  function runner() {
    minutes = parseInt(timer / 60, 10);
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer <= 0) {
     clearInterval(timers)
     finish()
   }
 }

}

Body:
Do you mean something like this?

function startTimer(duration, display) {

  // Make troops button enabled when attack button is clicked
  document.getElementsByClassName("troops")[0].removeAttribute("disabled");

  var timer = duration,minutes, seconds;
  var timers = setInterval(runner, 1000);
  function runner() {
    minutes = parseInt(timer / 60, 10);
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer <= 0) {
     clearInterval(timers)
     finish()
   }
 }

}

<button class="attack" onclick="startTimer(60,document.querySelector('#time'))">ATTACK</button>

<!-- declare troops button disabled before attack has been clicked -->
<button class="troops" disabled onclick="send()">SEND TROOPS</button>


问:
Ruby/C/Makefile, what is the default pcap.h file that is used in -lpcap/#include <pcap.h>
How can I determine what pcap.h file is being included in a C source that is being compiled/installed via a Makefile?

Specifically, it is a Ruby library (pcaprub) that is being installed via:

```<code>ruby extconf.rb && make && make install
</code>```

and the extconf.rb is:

```<code>require 'mkmf'

if /i386-mswin32/ =~ RUBY_PLATFORM
    pcap_dir        = with_config("pcap-dir", "C:\WpdPack")
    pcap_includedir = with_config("pcap-includedir", pcap_dir + "\\include")
    pcap_libdir     = with_config("pcap-libdir", pcap_dir + "\\lib")

    $CFLAGS  = "-DWIN32 -I#{pcap_includedir}"
    $LDFLAGS = "/link /LIBPATH:#{pcap_libdir}"
    have_library("wpcap", "pcap_open_live")
    have_library("wpcap", "pcap_setnonblock")
else
    have_library("pcap", "pcap_open_live")
    have_library("pcap", "pcap_setnonblock")
end

if ( RUBY_VERSION =~ /^1\.9/ )
    $CFLAGS += " -DRUBY_19"
end

create_makefile("pcaprub")
</code>```

答:
Can you look at the generated Makefile to see what -I options are being passed to gcc? You can also pass -H to gcc to display the header file that it ends up using:

```<code>   -H  Print the name of each header file used, in addition to other
       normal activities.  Each name is indented to show how deep in the
       #include stack it is.  Precompiled header files are also printed,
       even if they are found to be invalid; an invalid precompiled header
       file is printed with ...x and a valid one with ...! .
</code>```

ContentLicense: CC BY-SA 2.5

Body:
How can I determine what pcap.h file is being included in a C source that is being compiled/installed via a Makefile?

Specifically, it is a Ruby library (pcaprub) that is being installed via:

ruby extconf.rb && make && make install

and the extconf.rb is:

require 'mkmf'

if /i386-mswin32/ =~ RUBY_PLATFORM
    pcap_dir        = with_config("pcap-dir", "C:\WpdPack")
    pcap_includedir = with_config("pcap-includedir", pcap_dir + "\\include")
    pcap_libdir     = with_config("pcap-libdir", pcap_dir + "\\lib")

    $CFLAGS  = "-DWIN32 -I#{pcap_includedir}"
    $LDFLAGS = "/link /LIBPATH:#{pcap_libdir}"
    have_library("wpcap", "pcap_open_live")
    have_library("wpcap", "pcap_setnonblock")
else
    have_library("pcap", "pcap_open_live")
    have_library("pcap", "pcap_setnonblock")
end

if ( RUBY_VERSION =~ /^1\.9/ )
    $CFLAGS += " -DRUBY_19"
end

create_makefile("pcaprub")

Body:
Can you look at the generated Makefile to see what -I options are being passed to gcc? You can also pass -H to gcc to display the header file that it ends up using:

   -H  Print the name of each header file used, in addition to other
       normal activities.  Each name is indented to show how deep in the
       #include stack it is.  Precompiled header files are also printed,
       even if they are found to be invalid; an invalid precompiled header
       file is printed with ...x and a valid one with ...! .


问:
How to deploy multiple wars in tomcat using eclipse and then be able to debug the code
I am trying to setup an application, recently migrated to work with latest java version and tomcat, in eclispe. This application uses maven to generate two war files. I need to deploy these two war files to tomcat and be able to debug the code.

If I select the option in server to let eclipse take control over the deployment, whole application gets deployed and I am not able to access either of the modules using their context.

And if I choose to use tomcat installation, I have to manually copy the wars and run the server.Application runs but then I am not able to debug. I tried the remote debugging which worked but I was wondering if there is a cleaner approach on deploying two wars using eclipse and then access each app using its context.

答:
Alright, I tried tons of things and finally I was able to deploy/debug the code. It required some tweaking on the run/debug configuration side and some changes in the launch classes to provide the necessary setup required to launch the applications.

Created different configuration based on the application which needed to be deployed and debugged.


问:
How we can use loglevel-management by using Spring Boot Admin?
Currently i am using logback for logging purpose , i just heard about spring boot admin but does not get an exact idea about how to implement loglevel-management by using Spring Boot Admin , please any one tell me how we can implement this .Thanks in advance </p>

答: In case you are using spring boot admin 1.5.x and spring boot 1.5.x on your client you don't need to do anything - it should just work.</p>


问:
join strings in JS
I have an array A and array B:

```<code>A = ["1234","5678","4444"]
B = 7868,9090
</code>```

I want array C to be:

```<code>C = ["1234","5678","4444","7868","9090"]
</code>```

The length of array A and B can vary and array B should join the end of array A.

What is the best way to do this?

I tried using push() but I'm still having problems.

Thank you.

答:
In my opinion</p>

```<code>A.concat(B.split(','));
</code>```

Title: join strings in JS

Body:
I have an array A and array B:

A = ["1234","5678","4444"]
B = 7868,9090

I want array C to be:

C = ["1234","5678","4444","7868","9090"]

The length of array A and B can vary and array B should join the end of array A.

What is the best way to do this?

I tried using push() but I'm still having problems.

Thank you.

Body:
In my opinion

A.concat(B.split(','));


问:
Creating PDO Iterator
I'm flowing this article to create Database Iterator. I've similar tables and records. But when I executing I'm getting blank page. I think issue on $data = new DbRowIterator($stmt);, It's not returning proper iterator to run accept method in FilterIterator class. I'm using laravel

答:
PDOStatement is not iterable, it's traversable:

It doesn't implements the \Iterable interface but the \Traversable interface, meaning it can be used in a foreach but you can't iterate manually over it because it doesn't expose it's inner behavior.

I don't think this makes much difference in the present case but there is still a major difference between the two interfaces.

I stumbled upon this question looking for a way to properly iterate over a PDOStatement (without using a foreach) and the article mentioned, although pretty clumsy looks actually fine to me.

Title: Creating PDO Iterator


问:
CORS problems using angularjs $http
I get problems when using angularjs $http in a CORS request, my success function authenticateSuccess(data, status, headers) get wrong  headers. As we know, every CORS request will be twice in angularjs, I get twice response from server, the first time is the cors validation information, the second is needed response, but my success function get the headers in the first response. But it's data is from second response.</p>

```<code>function login(credentials) {

        var data = {
            username: credentials.username,
            password: credentials.password,
            rememberMe: credentials.rememberMe
        };
        console.log(data);
        return $http.post('//localhost:8080/api/authenticate', data).success(authenticateSuccess);

        function authenticateSuccess(data, status, headers) {
            console.log(headers());
            console.log(data);
            var bearerToken = headers('Authorization');
            if (angular.isDefined(bearerToken) && bearerToken.slice(0, 7) === 'Bearer ') {
                var jwt = bearerToken.slice(7, bearerToken.length);
                service.storeAuthenticationToken(jwt, credentials.rememberMe);
                return jwt;
            }
        }
    }
</code>```

答:
You are getting this problem as header which you are sending is not matched with the headers in backend

So let suppose In frontend you sending headers

contentHeaders = new Headers(); contentHeaders.append('Authorization', 'your token'); contentHeaders.append('Content-Type', 'application/json'); contentHeaders.append('Access-Control-Allow-Origin', '*');

So those headers like 'Authorization','Content-type', 'Access-Control-Allow-Origin' should matched with your header allow in backend.

So in backend 'Access-Control-Allow-Headers' should have all above headers see below

res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Authorization,content-type,Access-Control-Allow-Origin");

So here in Access-Control-Allow-Headers you have to passed all headers which you send from frontend : 'Authorization','Content-type', 'Access-Control-Allow-Origin'.

It will work perfectly when you use above concept.

Thanks

Title: CORS problems using angularjs $http

Body:
I get problems when using angularjs $http in a CORS request, my success function authenticateSuccess(data, status, headers) get wrong  headers. As we know, every CORS request will be twice in angularjs, I get twice response from server, the first time is the cors validation information, the second is needed response, but my success function get the headers in the first response. But it's data is from second response.

function login(credentials) {

        var data = {
            username: credentials.username,
            password: credentials.password,
            rememberMe: credentials.rememberMe
        };
        console.log(data);
        return $http.post('//localhost:8080/api/authenticate', data).success(authenticateSuccess);

        function authenticateSuccess(data, status, headers) {
            console.log(headers());
            console.log(data);
            var bearerToken = headers('Authorization');
            if (angular.isDefined(bearerToken) && bearerToken.slice(0, 7) === 'Bearer ') {
                var jwt = bearerToken.slice(7, bearerToken.length);
                service.storeAuthenticationToken(jwt, credentials.rememberMe);
                return jwt;
            }
        }
    }


问:
Dot and Square Bracket Notation
I'm trying to understand the difference between the Dot and the Square Bracket Notation. While going through various examples here on SO and on some other sites, I came across these two simple examples:

var obj = { "abc" : "hello" };
var x = "abc";
var y = obj[x];
console.log(y); //output - hello```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var user = {
  name: "John Doe",
  age: 30
};
var key = prompt("Enter the property to modify","name or age");
var value = prompt("Enter new value for " + key);
user[key] = value;
alert("New " + key + ": " + user[key]);</code>```

The first example returns y to be undefined if in third line I replace the obj[x] with obj.x. Why not "hello"

But in the second example the expression user[key] can simply be replaced with user.key without any anomalous behavior (at-least to me).
Now this confuses me as I recently learned that if we want to access properties by name stored in a variable, we use the [ ] Square bracket Notation.

答:
Accessing/Creation of properties from/in a JavaScript object can be done in two ways

Using Dot notation

Using Square Bracket notation

Whenever some property is not defined i.e. not present in the object and you try to access it, you will get undefined (obviously, because it's not there).

So, in the first example you are accessing a property and in the second example you are creating a property. Therefore, replacing the notation did not affect the code in the second example.

Title: Dot and Square Bracket Notation

Body:
I'm trying to understand the difference between the Dot and the Square Bracket Notation. While going through various examples here on SO and on some other sites, I came across these two simple examples:

var obj = { "abc" : "hello" };
var x = "abc";
var y = obj[x];
console.log(y); //output - hello

var user = {
  name: "John Doe",
  age: 30
};
var key = prompt("Enter the property to modify","name or age");
var value = prompt("Enter new value for " + key);
user[key] = value;
alert("New " + key + ": " + user[key]);

The first example returns y to be undefined if in third line I replace the obj[x] with obj.x. Why not "hello"

But in the second example the expression user[key] can simply be replaced with user.key without any anomalous behavior (at-least to me).
Now this confuses me as I recently learned that if we want to access properties by name stored in a variable, we use the [ ] Square bracket Notation.


问:
Power shell | Extract user name out of computer name in Domain Controller
How can I extract the user name in my active directory when I only have the computer name. </p>

<p>Obviously, no relation whats or ever between the computer name and the user name in terms of naming. </p>

答:
I recommend utilizing this cmdlet: Get-ADComputer.  After getting the AD information associated with this you can pipe the data out and utilize filters to get the information you require.  The filter code is also specified within the documentation.

Documentation can be found here: https://technet.microsoft.com/en-us/library/ee617192.aspx

Hope this helps (I'm not 100% sure if this is what you are looking for... The more details in your question the better)!

Body:
How can I extract the user name in my active directory when I only have the computer name.

Obviously, no relation whats or ever between the computer name and the user name in terms of naming.


问:
Variable repeating the same value when form closed
I have declared a variable called paymentId. When I open a windows form this paymentId is initialized to a certain value and I can add payments (Butter, bread..etc),save to the database and close the form. After closing the form I want to open the form so that I can add another payment (Milk etc..) but the paymentId is not changing and the same paymentId is saved in the database.</p>

```<code>public partial class PaymentAutoPayment : Form
{
    int firstRun = 0;
    double total = 0;
    public static Random rnd = new Random();
    String cashierId = "";
    public static int randomString = rnd.Next(9999, 99999)
    string paymentId = "RecId-" + randomString.ToString();
</code>```

答:
public static int randomString is static. It is initialized exactly once, ever.

```<code>public static int randomString = rnd.Next(9999, 99999);
</code>```

No matter now many times you convert the same int value to a string, it'll still be the same int.

```<code>string paymentId = "RecId-" + randomString.ToString();
</code>```

Try this:

```<code>string paymentId = "RecId-" + rnd.Next(9999, 99999).ToString();
</code>```

Body:
I have declared a variable called paymentId. When I open a windows form this paymentId is initialized to a certain value and I can add payments (Butter, bread..etc),save to the database and close the form. After closing the form I want to open the form so that I can add another payment (Milk etc..) but the paymentId is not changing and the same paymentId is saved in the database.

public partial class PaymentAutoPayment : Form
{
    int firstRun = 0;
    double total = 0;
    public static Random rnd = new Random();
    String cashierId = "";
    public static int randomString = rnd.Next(9999, 99999)
    string paymentId = "RecId-" + randomString.ToString();

Body:
public static int randomString is static. It is initialized exactly once, ever.

public static int randomString = rnd.Next(9999, 99999);

No matter now many times you convert the same int value to a string, it'll still be the same int.

string paymentId = "RecId-" + randomString.ToString();

Try this:

string paymentId = "RecId-" + rnd.Next(9999, 99999).ToString();


问:
What happened to clojure.xml/emit?
Many blogs refer to the clojure.xml/emit (or clojure.contrib.lazy-xml/emit) function, but it seems to be absent from the 1.2 documentation.

Was it deprecated? What has replaced it?

Can it be used to write Clojure-encoded XML (e.g.: {:tag :address :content {:tag :street ...} })?

UPDATE: I looked at the source code for clojure.contrib.lazy-xml/emit (by Chris Houser) and, although it too is not "official", it looks like a more stable solution than clojure.xml/emit.

BTW, I have "discovered" the clojure and clojure-contrib source code as great examples of well-written, idiomatic Clojure (especially the parts written by the masters, Rich Hickey, the two Stuarts, Chris Houser, etc.) I'll need to spend some time studying that code.

答:
Strangely enough, clojure.xml/emit still exists when you (use 'clojure.xml) that namespace at the REPL in 1.2.0.

To verify:

```<code>user=> (use 'clojure.xml)
user=> (emit (parse "http://feeds.feedburner.com/burningonesblog"))
</code>```

For full disclosure I discovered this using the useful (ns-map 'user) function

```<code>user=> (doc ns-map)
-------------------------
clojure.core/ns-map
([ns])
  Returns a map of all the mappings for the namespace.
nil
</code>```

Now please note that you are entirely correct about their disappearing from the documentation in 1.2 (clojure.xml and clojure.contrib.lazy-xml) for all but prxml which isn't really what you're looking for.  I can't speak to why that is the case but the reason they no longer show up in the web interface becomes evident upon examining their docstring.

```<code>user=> (doc emit)
-------------------------
clojure.xml/emit
([x])
  nil
nil
</code>```

Now there is this thread over at the Google Group which indicates that use of the emit function is discouraged for 2 reasons.

It is undocumented and thus subject to change without notice.

It, in general, does not produce valid xml (although I suppose if you know your data is valid it would emit valid xml).

At the end of that thread, Stuart Halloway talks about a project to extend Clojure's XML support.

Of course there's always dipping into the Java pool and using any of the excellent XML tools on the Java end.  It sounds like clojure's XML story is mostly told in parsing at this point.

Hope that helps.

ContentLicense: CC BY-SA 4.0

Title: What happened to clojure.xml/emit?

Body:
Strangely enough, clojure.xml/emit still exists when you (use 'clojure.xml) that namespace at the REPL in 1.2.0.

To verify:

user=> (use 'clojure.xml)
user=> (emit (parse "http://feeds.feedburner.com/burningonesblog"))

For full disclosure I discovered this using the useful (ns-map 'user) function

user=> (doc ns-map)
-------------------------
clojure.core/ns-map
([ns])
  Returns a map of all the mappings for the namespace.
nil

Now please note that you are entirely correct about their disappearing from the documentation in 1.2 (clojure.xml and clojure.contrib.lazy-xml) for all but prxml which isn't really what you're looking for.  I can't speak to why that is the case but the reason they no longer show up in the web interface becomes evident upon examining their docstring.

user=> (doc emit)
-------------------------
clojure.xml/emit
([x])
  nil
nil

Now there is this thread over at the Google Group which indicates that use of the emit function is discouraged for 2 reasons.

It is undocumented and thus subject to change without notice.

It, in general, does not produce valid xml (although I suppose if you know your data is valid it would emit valid xml).

At the end of that thread, Stuart Halloway talks about a project to extend Clojure's XML support.

Of course there's always dipping into the Java pool and using any of the excellent XML tools on the Java end.  It sounds like clojure's XML story is mostly told in parsing at this point.

Hope that helps.


问:
VueJs reactivity with parent component property object
I'm having difficulty to get parent component's property object, with dynamically populated properties to make the values available inside of the same component.

A bit hard to explain, so please have a look at the example below:

Parent Component

```<code><script>
    export default {
        data() {
            return {
                fields: {},
            }
        }
    }
</script>
</code>```

Child Component

```<code><template>
  <select
      @change="update()"
      v-model="field"
  >
      <option
          v-for="option in options"
          :value="option.value"
      >
          {{ option.name }}
      </option>
  </select>
</template>
<script>
    export default {
        props: {
            initialOptions: {
                type: Array,
                required: true
            }
        },
        data() {
            return {
                    field: '',
                options: this.initialOptions
            }
        },
        mounted() {
            if (
                (this.field === undefined || this.field === '') &&
                this.options.length > 0
            ) {
                this.field = this.options[0].value;
            }
            this.update();
        },
        methods: {
            update() {
                this.$emit('input', this.field);
            }
        }
    }
</script>
</code>```

DOM

```<code><parent-component inline-template>

    <div>

        <child-component>
            :initial-options="[{..}, {..}]"
          v-model="fields.type_id"
        ></child-component>

    </div>

    <div :class="{ dn : fields.type_id == 2 }">

        // ...

    </div>

</parent-component>
</code>```

Using Vue console I can see that fields object gets all of the child component models with their associated values as they emit input when they are mounted, however for some strange reason the :class="{ dn : fields.type_id == 2 }" does not append the class dn when the selection changes to 2. Dom doesn't seem to reflect the changes that are synced between parent and child components.

Any help on how to make it work?

答:
Here is what I was trying to get at in comments. Vue cannot detect changes to properties that are added dynamically to an object unless you add them using $set. Your fields object does not have a type_id property, but it gets added because you are using v-model="fields.type_id". As such, Vue does not know when it changes.

Here, I have added it and the color of the text changes as you would expect.

console.clear()

Vue.component("child-component", {
  template: `
    <select
        @change="update()"
        v-model="field"
    >
        <option
            v-for="option in options"
            :value="option.value"
        >
            {{ option.name }}
        </option>
    </select>
  `,
  props: {
    initialOptions: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      field: '',
      options: this.initialOptions
    }
  },
  mounted() {
    if (
      (this.field === undefined || this.field === '') &&
      this.options.length > 0
    ) {
      this.field = this.options[0].value;
    }
    this.update();
  },
  methods: {
    update() {
      this.$emit('input', this.field);
    }
  }
})

new Vue({
  el: "#app",
  data: {
    fields: {
      type_id: null
    }
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dn {
  color: red;
}</code>```

    <child-component :initial-options="[{name: 'test', value: 1}, {name: 'test2', value: 2}]" v-model="fields.type_id"></child-component>

    Stuff

```

Body:
I'm having difficulty to get parent component's property object, with dynamically populated properties to make the values available inside of the same component.

A bit hard to explain, so please have a look at the example below:

Parent Component

Child Component

<template>
  <select
      @change="update()"
      v-model="field"
  >
      <option
          v-for="option in options"
          :value="option.value"
      >
          {{ option.name }}
      </option>
  </select>
</template>

DOM

<parent-component inline-template>

        <child-component>
            :initial-options="[{..}, {..}]"
          v-model="fields.type_id"
        ></child-component>

        // ...

</parent-component>

Using Vue console I can see that fields object gets all of the child component models with their associated values as they emit input when they are mounted, however for some strange reason the :class="{ dn : fields.type_id == 2 }" does not append the class dn when the selection changes to 2. Dom doesn't seem to reflect the changes that are synced between parent and child components.

Any help on how to make it work?

Body:
Here is what I was trying to get at in comments. Vue cannot detect changes to properties that are added dynamically to an object unless you add them using $set. Your fields object does not have a type_id property, but it gets added because you are using v-model="fields.type_id". As such, Vue does not know when it changes.

Here, I have added it and the color of the text changes as you would expect.

console.clear()

Vue.component("child-component", {
  template: `
    <select
        @change="update()"
        v-model="field"
    >
        <option
            v-for="option in options"
            :value="option.value"
        >
            {{ option.name }}
        </option>
    </select>
  `,
  props: {
    initialOptions: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      field: '',
      options: this.initialOptions
    }
  },
  mounted() {
    if (
      (this.field === undefined || this.field === '') &&
      this.options.length > 0
    ) {
      this.field = this.options[0].value;
    }
    this.update();
  },
  methods: {
    update() {
      this.$emit('input', this.field);
    }
  }
})

new Vue({
  el: "#app",
  data: {
    fields: {
      type_id: null
    }
  }
})

.dn {
  color: red;
}

<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
<div id="app">
  <div>
    <child-component :initial-options="[{name: 'test', value: 1}, {name: 'test2', value: 2}]" v-model="fields.type_id"></child-component>
  </div>
  <div :class="{ dn : fields.type_id == 2 }">
    Stuff
  </div>
</div>


问:
Calling a stored procedure from another SQL Server Database Engine
From SQL Server Management Studio I have connected to an SQL Server database engine. This database engine has a lot of databases. From a store procedure defined in a database I am trying to call a store procedure in another database that it is in another SQL Server database engine. So I have done:

```<code>exec [MyDatabaseEngine].[MyDatabase].[MyStoreProcedure] param1, param2
</code>```

But it is not working.

I do not know if I have explained it correctly. If not, please let me know.

答: You are missing the schema. The format is [LinkServer].[Database].[Schema].[Object]</p>

Body:
From SQL Server Management Studio I have connected to an SQL Server database engine. This database engine has a lot of databases. From a store procedure defined in a database I am trying to call a store procedure in another database that it is in another SQL Server database engine. So I have done:

exec [MyDatabaseEngine].[MyDatabase].[MyStoreProcedure] param1, param2

But it is not working.

I do not know if I have explained it correctly. If not, please let me know.


问:
Extract integer from a list
I have a list like ['-1', '1,2,3', '2'] and I want to extract all the integers in it.
I don't know the number of integers in each position of the list ie the list can also be ['2,3,4','1,2,3','-1'] but it will never have an empty string.
So I want that the answer should be [2,3,4,1,2,3,-1]

What is the best way to do so in terms of complexity as well as less code.

Thanks...

答:
Here's a ist comprehension:</p>

```<code>new_list = [ int(i) for i in ','.join(old_list).split(',') ]
</code>```

Title: Extract integer from a list

Body:
Here's a ist comprehension:

new_list = [ int(i) for i in ','.join(old_list).split(',') ]


答:
```<code> public static int randomString = rnd.Next(9999, 99999)
</code>```

This is declared as static and only executed once during the whole program runtime, and never changes. Use instead:

```<code>string paymentId = "RecId-" + rnd.Next(9999, 99999).ToString();
</code>```

Title: Variable repeating the same value when form closed

Body:
 public static int randomString = rnd.Next(9999, 99999)

This is declared as static and only executed once during the whole program runtime, and never changes. Use instead:

string paymentId = "RecId-" + rnd.Next(9999, 99999).ToString();


问:
Working outside of application context; FlaskClient object has no attribute 'app_context'
We are getting FlaskClient object has no attribute 'app_context' with this test:

app.py:

```<code>import logging
from logging.handlers import RotatingFileHandler

from blueprints import default, otherstuff
from global_vars import app, db

def generate_app():
    app.config.from_object('config.flask_config')
    db.init_app(app)

   # registering blueprints
    app.register_blueprint(default.default)
    app.before_request(oauth_package.authenticate_all_requests)
    return app

if __name__ == '__main__':
    flask_app = generate_app()
    flask_app.run(port=5002, debug=True)
</code>```

testfile.py:

```<code>import unittest
import mock
from starter_file import generate_app
import flask
import blueprints

class TestBase(unittest.TestCase):

    def setUp(self):
        # creates a test client
        app = generate_app()
        app.testing = True
        self.app = app.test_client()
        # propagate the exceptions to the test client

    @mock.patch('blueprints.default.get_current_user_role')
    def test_qppage_without_coockie(self,  mocked_get_current_user_role):
        mocked_get_current_user_role.return_value = 'ap'
        with self.app.app_context():
            result = blueprints.default.home()
            print result
            # assert the status code of the response
            self.assertEqual(result.status_code, 302)

if __name__ == '__main__':
    unittest.main()
</code>```

and Runtime error: Working outside of application context with this code:

```<code>class TestBase(unittest.TestCase):

    def setUp(self):
        # creates a test client
        app = generate_app()
        app.testing = True
        self.app = app.test_client()
        # propagate the exceptions to the test client

    @mock.patch('blueprints.default.get_current_user_role')
    def test_qppage_without_coockie(self,  mocked_get_current_user_role):
        mocked_get_current_user_role.return_value = 'ap'
        result = blueprints.default.home()
        print result
        # assert the status code of the response
        self.assertEqual(result.status_code, 302)
</code>```

答:
Try to add this in your TestBase class:</p>

```<code>...

from flask import current_app

...

@classmethod
def setUpClass(cls):
    cls.app = generate_app()

def setUp(self):
    """Set up application for testing."""
    with self.app.app_context():
        self.test_app = current_app.test_client()

# Here goes the rest of your code
</code>```

Body:
We are getting FlaskClient object has no attribute 'app_context' with this test:

app.py:

import logging
from logging.handlers import RotatingFileHandler

from blueprints import default, otherstuff
from global_vars import app, db

def generate_app():
    app.config.from_object('config.flask_config')
    db.init_app(app)

   # registering blueprints
    app.register_blueprint(default.default)
    app.before_request(oauth_package.authenticate_all_requests)
    return app

if __name__ == '__main__':
    flask_app = generate_app()
    flask_app.run(port=5002, debug=True)

testfile.py:

import unittest
import mock
from starter_file import generate_app
import flask
import blueprints

class TestBase(unittest.TestCase):

    def setUp(self):
        # creates a test client
        app = generate_app()
        app.testing = True
        self.app = app.test_client()
        # propagate the exceptions to the test client

    @mock.patch('blueprints.default.get_current_user_role')
    def test_qppage_without_coockie(self,  mocked_get_current_user_role):
        mocked_get_current_user_role.return_value = 'ap'
        with self.app.app_context():
            result = blueprints.default.home()
            print result
            # assert the status code of the response
            self.assertEqual(result.status_code, 302)

if __name__ == '__main__':
    unittest.main()

and Runtime error: Working outside of application context with this code:

class TestBase(unittest.TestCase):

    def setUp(self):
        # creates a test client
        app = generate_app()
        app.testing = True
        self.app = app.test_client()
        # propagate the exceptions to the test client

    @mock.patch('blueprints.default.get_current_user_role')
    def test_qppage_without_coockie(self,  mocked_get_current_user_role):
        mocked_get_current_user_role.return_value = 'ap'
        result = blueprints.default.home()
        print result
        # assert the status code of the response
        self.assertEqual(result.status_code, 302)

Body:
Try to add this in your TestBase class:

...

from flask import current_app

...

@classmethod
def setUpClass(cls):
    cls.app = generate_app()

def setUp(self):
    """Set up application for testing."""
    with self.app.app_context():
        self.test_app = current_app.test_client()

# Here goes the rest of your code


问:
Avoiding Javascript Function expected error on implementing document ready function
I have a component on my page that needs to be hidden until the documented is ready. Therefore I have defined a couple of DIVs and implemented the document ready function:

```<code><div id="LoadingDiv" style="display:block;text-align:center">
    <i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i>
</div>
<div class="form-horizontal" id="LoadedDiv" style="display:none;">
   ...
</div>

<script  type="text/javascript">

$(document).ready(function () {
    setTimeout(function () {
        document.getElementById("LoadingDiv").style.display = "none";
        document.getElementById("LoadedDiv").style.display = "block";
    }, 500);
})

$(document).on("change", function () {
        window.onbeforeunload = function () {
            return "your changes to this form have not been saved";
        };
})
</script>
</code>```

Whilst this seems to work, it generates 'Function Expected' error in the browser's developer console. I've tried various different ways of expressing the function - see below. I've also tried replacing the function body with something simple like alert("me"). The error goes away if I remove the 'ready' function, but keep the document 'change' function. Therefore I'm now quite sure the problem lies in the 'ready' function definition.

Questions:

Why am I getting a Function expected error? The function seems to be properly formed and I'm setting properties rather using them as methods.

What is the correct convention for implementing a document ready function? Seemingly there are many approaches - e.g. $(document).on("ready", function () {...}; }). It would be great to agree on just one that works well and without error.

By the way, I'm using JQuery 2.2.0 with Bootstrap 3.3.6.

答:
Well spotted Gaurang! I need new spectacles ;-) The correct code is </p>

```<code><div id="LoadingDiv" style="display:block;text-align:center">
  <i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i>
</div>
<div class="form-horizontal" id="LoadedDiv" style="display:none;">
   ...
</div>

<script  type="text/javascript">

$(document).ready(function () {
   setTimeout(function () {
     document.getElementById("LoadingDiv").style.display = "none";
     document.getElementById("LoadedDiv").style.display = "block";
   }, 500);
});
</script>
</code>```

Body:
I have a component on my page that needs to be hidden until the documented is ready. Therefore I have defined a couple of DIVs and implemented the document ready function:

   ...

Whilst this seems to work, it generates 'Function Expected' error in the browser's developer console. I've tried various different ways of expressing the function - see below. I've also tried replacing the function body with something simple like alert("me"). The error goes away if I remove the 'ready' function, but keep the document 'change' function. Therefore I'm now quite sure the problem lies in the 'ready' function definition.

Questions:

Why am I getting a Function expected error? The function seems to be properly formed and I'm setting properties rather using them as methods.

What is the correct convention for implementing a document ready function? Seemingly there are many approaches - e.g. $(document).on("ready", function () {...}; }). It would be great to agree on just one that works well and without error.

By the way, I'm using JQuery 2.2.0 with Bootstrap 3.3.6.

Body:
Well spotted Gaurang! I need new spectacles ;-) The correct code is

<div id="LoadingDiv" style="display:block;text-align:center">
  <i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i>
</div>
<div class="form-horizontal" id="LoadedDiv" style="display:none;">
   ...
</div>

<script  type="text/javascript">

$(document).ready(function () {
   setTimeout(function () {
     document.getElementById("LoadingDiv").style.display = "none";
     document.getElementById("LoadedDiv").style.display = "block";
   }, 500);
});
</script>


问:
Symfony Security with Guard : User logged in and immediately logged out
I want to authenticate users from a webservice. I created a firewall and I use Guard and a custom user provider.

Here is my problem : when I log in, the user is authenticated and immediately logged out after the first redirection (web_profiler.intercept_redirects at truehelps me to deduce it).

I don't know what in my code or my config can be responsible of this. I created an authenticator that extends AbstractGuardAuthenticator. In the method checkCredentials(), I call the webservice and the answer is successful.

In onAuthenticationSuccess() method, I set a token given by the webservice in session and I redirect to the route the user was before the authentication is triggered. When the redirection is done, the user is no longer logged in.

I explored another point: my firewall is configured to work with specific hosts thanks to host key under my firewall configuration:

```<code>customer_account:
    pattern: ^(?!/admin[/]*).*$ # all but /admin
    host: "%extranet_domain_one%|%extranet_domain_two%"
    anonymous: ~
    provider: customer_account
    form_login:
        login_path: customer_account_login
        check_path: customer_account_login
    guard:
       authenticators:
           - app.customer_web_service_authenticator
    logout:
       path: customer_account_logout
       target: /
</code>```

Here are my access_controlconfig:

```<code>access_control:
        - { host: "%extranet_domain_one%|%extranet_domain_two%", path: ^/connexion, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { host: "%extranet_domain_one%|%extranet_domain_two%", path: ^/mot-de-passe, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { host: "%extranet_domain_one%|%extranet_domain_two%", path: ^/, roles: ROLE_CUSTOMER_ACCOUNT }
</code>```

In my provider, the method loadUserByUsername() returns a new user with the login and the token stored in session if it exists.

Any idea?

Additional informations:

CustomerWebServiceAuthenticator:

```<code><?php

namespace AppBundle\Security;

use AppBundle\Security\User\CustomerAccount;
use AppBundle\Security\User\CustomerAccountUserProvider;
use AppBundle\Services\Webservice;
use AppBundle\Services\MultisiteHelper;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserProviderInterface;

/**
 * Class CustomerWebServiceAuthenticator
 *
 * @package AppBundle\Security
 */
class CustomerWebServiceAuthenticator extends AbstractGuardAuthenticator
{

    /** @var webservice */
    protected $webservice;

    /** @var MultisiteHelper */
    protected $multisiteHelper;

    /** @var \Symfony\Component\Routing\RouterInterface */
    protected $router;

    /** @var SessionInterface */
    protected $session;

    /**
     * Indique si le site s'exécute en mode développement.
     *
     * @var boolean
     */
    private $dev;

    /**
     * Default message for authentication failure.
     *
     * @var string
     */
    private $failMessage = 'Mot de passe ou e-mail invalide';

    /**
     * WebServiceAuthenticator constructor.
     *
     * @param Webservice $webservice
     * @param MultisiteHelper  $multisiteHelper
     * @param RouterInterface  $router
     * @param SessionInterface $session
     * @param string $kernelEnvironment
     */
    public function __construct(
        Webservice $webservice,
        MultisiteHelper $multisiteHelper,
        RouterInterface $router,
        SessionInterface $session,
        $kernelEnvironment
    ) {
        $this->webservice = $webservice;
        $this->multisiteHelper  = $multisiteHelper;
        $this->router           = $router;
        $this->session          = $session;
        $this->dev              = $kernelEnvironment === 'dev';
    }

    /**
     * {@inheritdoc}
     * @param Request $request
     *
     * @return array|null
     */
    public function getCredentials(Request $request)
    {
        $url = $request->getRequestUri();

        if ($url !== $this->router->generate('customer_account_login') || !$request->isMethod('POST')) {
            return null;
        }

        return [
            'username' => $request->request->get('_username'),
            'password' => $request->request->get('_password'),
        ];
    }

    /**
     * {@inheritdoc}
     * @param mixed                 $credentials
     * @param UserProviderInterface $userProvider
     *
     * @return CustomerAccount|null|UserInterface
     */
    public function getUser($credentials, UserProviderInterface $userProvider)
    {
        if (!$userProvider instanceof CustomerAccountUserProvider) {
            return null;
        }

        try {
            return $userProvider->loadUserByUsername($credentials['username']);
        } catch (UsernameNotFoundException $e) {
            throw new CustomUserMessageAuthenticationException($this->failMessage);
        }
    }

    /**
     * {@inheritdoc}
     * @param mixed         $credentials
     * @param UserInterface $user
     *
     * @return bool
     */
    public function checkCredentials($credentials, UserInterface $user)
    {
        $xml = $this->webservice->loginCustomerAccount([
            'username'         => $credentials['username'],
            'password'         => ($credentials['password']),
        ]);

        if (isset($xml->identification) && isset($xml->identification['customer_id']) && isset($xml->identification['id_token_session'])) {
            /** @var $user CustomerAccount */
            $user
                ->setIdTokenSession((string) $xml->identification['id_token_session'])
                ->setCustomerId((string) $xml->identification['customer_id'])
            ;
            return true;
        }

        throw new CustomUserMessageAuthenticationException($this->failMessage);
    }

    /**
     * {@inheritdoc}
     */
    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        /** @var $user CustomerAccount */
        $user = $token->getUser();

        // Stockage en session, c'est ce qui maintient la connexion chez nous
        $this->session->clear();
        $this->session->set('customer_id', $user->getCustomerId());
        $this->session->set('id_token_session_customer', $user->getIdTokenSession());
        $this->session->set('login', $user->getUsername());

        // @todo LDA : adapter
        if ($this->session->has('_security.' . $providerKey . '.target_path')) {
            $url = $this->session->get('_security.' . $providerKey . '.target_path');
        } else {
            $url = $this->router->generate('customer_account_account');
        }

        return new RedirectResponse($url);
    }

    /**
     * {@inheritdoc}
     */
    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        $request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);
        $url = $this->router->generate('customer_account_login');

        return new RedirectResponse($url);
    }

    /**
     * {@inheritdoc}
     */
    public function start(Request $request, AuthenticationException $authException = null)
    {
        $url = $this->router->generate('customer_account_login');

        return new RedirectResponse($url);
    }

    /**
     * {@inheritdoc}
     */
    public function supportsRememberMe()
    {
        return false;
    }
}
</code>```

答:
Sorry for the delay: I found it!

There was a typo in isEqualTo() in my class CustomerAccount implementing Symfony\Component\Security\Core\User\EquatableInterface, so it can never return true.

Thanks for spending time helping me!

Body:
I want to authenticate users from a webservice. I created a firewall and I use Guard and a custom user provider.

Here is my problem : when I log in, the user is authenticated and immediately logged out after the first redirection (web_profiler.intercept_redirects at truehelps me to deduce it).

I don't know what in my code or my config can be responsible of this. I created an authenticator that extends AbstractGuardAuthenticator. In the method checkCredentials(), I call the webservice and the answer is successful.

In onAuthenticationSuccess() method, I set a token given by the webservice in session and I redirect to the route the user was before the authentication is triggered. When the redirection is done, the user is no longer logged in.

I explored another point: my firewall is configured to work with specific hosts thanks to host key under my firewall configuration:

customer_account:
    pattern: ^(?!/admin[/]*).*$ # all but /admin
    host: "%extranet_domain_one%|%extranet_domain_two%"
    anonymous: ~
    provider: customer_account
    form_login:
        login_path: customer_account_login
        check_path: customer_account_login
    guard:
       authenticators:
           - app.customer_web_service_authenticator
    logout:
       path: customer_account_logout
       target: /

Here are my access_controlconfig:

access_control:
        - { host: "%extranet_domain_one%|%extranet_domain_two%", path: ^/connexion, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { host: "%extranet_domain_one%|%extranet_domain_two%", path: ^/mot-de-passe, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { host: "%extranet_domain_one%|%extranet_domain_two%", path: ^/, roles: ROLE_CUSTOMER_ACCOUNT }

In my provider, the method loadUserByUsername() returns a new user with the login and the token stored in session if it exists.

Any idea?

Additional informations:

CustomerWebServiceAuthenticator:

<?php

namespace AppBundle\Security;

use AppBundle\Security\User\CustomerAccount;
use AppBundle\Security\User\CustomerAccountUserProvider;
use AppBundle\Services\Webservice;
use AppBundle\Services\MultisiteHelper;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserProviderInterface;

/**
 * Class CustomerWebServiceAuthenticator
 *
 * @package AppBundle\Security
 */
class CustomerWebServiceAuthenticator extends AbstractGuardAuthenticator
{

    /** @var webservice */
    protected $webservice;

    /** @var MultisiteHelper */
    protected $multisiteHelper;

    /** @var \Symfony\Component\Routing\RouterInterface */
    protected $router;

    /** @var SessionInterface */
    protected $session;

    /**
     * Indique si le site s'exécute en mode développement.
     *
     * @var boolean
     */
    private $dev;

    /**
     * Default message for authentication failure.
     *
     * @var string
     */
    private $failMessage = 'Mot de passe ou e-mail invalide';

    /**
     * WebServiceAuthenticator constructor.
     *
     * @param Webservice $webservice
     * @param MultisiteHelper  $multisiteHelper
     * @param RouterInterface  $router
     * @param SessionInterface $session
     * @param string $kernelEnvironment
     */
    public function __construct(
        Webservice $webservice,
        MultisiteHelper $multisiteHelper,
        RouterInterface $router,
        SessionInterface $session,
        $kernelEnvironment
    ) {
        $this->webservice = $webservice;
        $this->multisiteHelper  = $multisiteHelper;
        $this->router           = $router;
        $this->session          = $session;
        $this->dev              = $kernelEnvironment === 'dev';
    }

    /**
     * {@inheritdoc}
     * @param Request $request
     *
     * @return array|null
     */
    public function getCredentials(Request $request)
    {
        $url = $request->getRequestUri();

        if ($url !== $this->router->generate('customer_account_login') || !$request->isMethod('POST')) {
            return null;
        }

        return [
            'username' => $request->request->get('_username'),
            'password' => $request->request->get('_password'),
        ];
    }

    /**
     * {@inheritdoc}
     * @param mixed                 $credentials
     * @param UserProviderInterface $userProvider
     *
     * @return CustomerAccount|null|UserInterface
     */
    public function getUser($credentials, UserProviderInterface $userProvider)
    {
        if (!$userProvider instanceof CustomerAccountUserProvider) {
            return null;
        }

        try {
            return $userProvider->loadUserByUsername($credentials['username']);
        } catch (UsernameNotFoundException $e) {
            throw new CustomUserMessageAuthenticationException($this->failMessage);
        }
    }

    /**
     * {@inheritdoc}
     * @param mixed         $credentials
     * @param UserInterface $user
     *
     * @return bool
     */
    public function checkCredentials($credentials, UserInterface $user)
    {
        $xml = $this->webservice->loginCustomerAccount([
            'username'         => $credentials['username'],
            'password'         => ($credentials['password']),
        ]);

        if (isset($xml->identification) && isset($xml->identification['customer_id']) && isset($xml->identification['id_token_session'])) {
            /** @var $user CustomerAccount */
            $user
                ->setIdTokenSession((string) $xml->identification['id_token_session'])
                ->setCustomerId((string) $xml->identification['customer_id'])
            ;
            return true;
        }

        throw new CustomUserMessageAuthenticationException($this->failMessage);
    }

    /**
     * {@inheritdoc}
     */
    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        /** @var $user CustomerAccount */
        $user = $token->getUser();

        // Stockage en session, c'est ce qui maintient la connexion chez nous
        $this->session->clear();
        $this->session->set('customer_id', $user->getCustomerId());
        $this->session->set('id_token_session_customer', $user->getIdTokenSession());
        $this->session->set('login', $user->getUsername());

        // @todo LDA : adapter
        if ($this->session->has('_security.' . $providerKey . '.target_path')) {
            $url = $this->session->get('_security.' . $providerKey . '.target_path');
        } else {
            $url = $this->router->generate('customer_account_account');
        }

        return new RedirectResponse($url);
    }

    /**
     * {@inheritdoc}
     */
    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        $request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);
        $url = $this->router->generate('customer_account_login');

        return new RedirectResponse($url);
    }

    /**
     * {@inheritdoc}
     */
    public function start(Request $request, AuthenticationException $authException = null)
    {
        $url = $this->router->generate('customer_account_login');

        return new RedirectResponse($url);
    }

    /**
     * {@inheritdoc}
     */
    public function supportsRememberMe()
    {
        return false;
    }
}


问:
SQL Server - Converting to smalldatetime in dynamic SQL Statement
The below dynamic SQL throws an error:

The conversion failed when converting character string to smalldatetime data type

My code:

```<code>DECLARE @pTimeStamp smalldatetime
SET @pTimeStamp = '2017-05-22 12:15:00'

DECLARE @SQLQuery AS NVARCHAR(4000)
Set @SQLQuery = N'Select *' +
' From SampleTable'  +
' Where TimeStamp = ' + @pTimeStamp

EXECUTE sp_executesql @SQLQuery
</code>```

I've also tried

```<code>Convert(smalldatetime, @pTimeStamp, 20)
</code>```

as well as

```<code>CAST(@pTimeStamp AS smalldatetime)
</code>```

but I only get other errors. I also tried declaring @pTimeStamp as varchar(50) and then converting but still got errors.

Doing something simple like:

```<code>DECLARE @pTimeStamp smalldatetime
SET @pTimeStamp = '2012-01-22 12:15:00'

Select *
From SampleTable
Where TimeStamp = @pTimeStamp
</code>```

ran fine so I'm guessing it has to do with the dynamic SQL.

Please help....

答:
You need to embed the timestamp in single quotes.  Try:</p>

```<code>Set @SQLQuery = N'Select *' +
' From SampleTable'  +
' Where TimeStamp = ''' + @pTimeStamp + ''''
</code>```

Body:
The below dynamic SQL throws an error:

The conversion failed when converting character string to smalldatetime data type

My code:

DECLARE @pTimeStamp smalldatetime
SET @pTimeStamp = '2017-05-22 12:15:00'

DECLARE @SQLQuery AS NVARCHAR(4000)
Set @SQLQuery = N'Select *' +
' From SampleTable'  +
' Where TimeStamp = ' + @pTimeStamp

EXECUTE sp_executesql @SQLQuery

I've also tried

Convert(smalldatetime, @pTimeStamp, 20)

as well as

CAST(@pTimeStamp AS smalldatetime)

but I only get other errors. I also tried declaring @pTimeStamp as varchar(50) and then converting but still got errors.

Doing something simple like:

DECLARE @pTimeStamp smalldatetime
SET @pTimeStamp = '2012-01-22 12:15:00'

Select *
From SampleTable
Where TimeStamp = @pTimeStamp

ran fine so I'm guessing it has to do with the dynamic SQL.

Please help....

Body:
You need to embed the timestamp in single quotes.  Try:

Set @SQLQuery = N'Select *' +
' From SampleTable'  +
' Where TimeStamp = ''' + @pTimeStamp + ''''


问:
Changing first item in nested list using list comprehension
Let's say I have the following list of lists:

```<code>[['Hello im an item', 1234], ['I enjoy python', 'hello'], ['I only have one item']]
</code>```

I want to replace the spaces with underscores in the first item in each inner list so it looks like this:

```<code>[['Hello_im_an_item', 1234], ['I_enjoy_python', 'hello'], ['I_only_have_one_item']]
</code>```

I have tried the following with no success:

```<code>formatted = [first[0].replace(' ', '_') for first in formatted]
</code>```

formatted returns a list of only the first items, but with the correct formatting.
Does anyone have any idea how this can be accomplished?

答:
A list comprehension builds an entirely new list, so you need to ensure that that new list contains everything the old list contained. Concatenate the remainder of each sublist:

```<code>formatted = [[sub[0].replace(' ', '_')] + sub[1:] for sub in formatted]
</code>```

As a regular for loop, the above is roughly equivalent to:

```<code>_new = []
for sub in formatted:
    _element = [sub[0].replace(' ', '_')] + sub[1:]
    _new.append(_element)
formatted = _new
</code>```

Rather than use a list comprehension, you could just alter your list in-place with a regular loop:

```<code>for sub in formatted:
    sub[0] = sub[0].replace(' ', '_')
</code>```

Only use the list comprehension if you absolutely need a completely new list.

Body:
Let's say I have the following list of lists:

[['Hello im an item', 1234], ['I enjoy python', 'hello'], ['I only have one item']]

I want to replace the spaces with underscores in the first item in each inner list so it looks like this:

[['Hello_im_an_item', 1234], ['I_enjoy_python', 'hello'], ['I_only_have_one_item']]

I have tried the following with no success:

formatted = [first[0].replace(' ', '_') for first in formatted]

formatted returns a list of only the first items, but with the correct formatting.
Does anyone have any idea how this can be accomplished?

Body:
A list comprehension builds an entirely new list, so you need to ensure that that new list contains everything the old list contained. Concatenate the remainder of each sublist:

formatted = [[sub[0].replace(' ', '_')] + sub[1:] for sub in formatted]

As a regular for loop, the above is roughly equivalent to:

_new = []
for sub in formatted:
    _element = [sub[0].replace(' ', '_')] + sub[1:]
    _new.append(_element)
formatted = _new

Rather than use a list comprehension, you could just alter your list in-place with a regular loop:

for sub in formatted:
    sub[0] = sub[0].replace(' ', '_')

Only use the list comprehension if you absolutely need a completely new list.


问:
Where does the Spring Model that is passed to a JSP goes to?
I've been reading docs and tutorials about spring (3.0), so I've learnt how to return a ModelAndView with the JSP name and a Map as the model. I've learnt also that in a JSP, if you want to access one key of that map you do ${attributename} and so on. That's JSP EL. Now my questions:

What object of the page is the EL accessing? Is that PageContext? I tried to find those keys in PageContext.getAttribute but they are not there.

Whatever the object is, is it automatic that the things in the model go there?

Feel free to add resources to clarify my ideas

答:
When you do something like ${attributename}, JSP EL will check a variety of sources to find it, including the page and request contexts (in that order).

When your Spring controller returns a model (e.g. inside the ModelAndView), this model is decomposed by Spring's AbstractView class and inserted into the request context (this is the "magic" part), so that when your JSP EL expression refers to an item from the model, it's available to be used.