答:
Your constructor function AppViewModel takes in the Model upon construction. The resulting ViewModel will be two-way data-bound to the view.

What you'd typically have is a reverse method to the constructor, that can be used e.g. when saving the changes through a Model in a back-end. Here's a demo with your example:

function AppViewModel(model){
    var self = this;

    self.firstName = ko.observable(model.firstName);
    self.lastName = ko.observable(model.lastName);

    self.asModel = ko.computed(function() {
        return {
            firstName: self.firstName(),
            lastName: self.lastName()
        };
    });

    self.saveInBackend = function() {
        // Typically you'd ajax here, instead we log the model:
        console.log(self.asModel());
    };
}
var model = {};
model.firstName = "John";
model.lastName = "Doe";

var viewModel = new AppViewModel(model);

ko.applyBindings(viewModel);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

Firstname: <input data-bind="textInput: firstName"><br>
Lastname: <input data-bind="textInput: lastName"><br>
<button data-bind="click: saveInBackend">saveInBackend</button>
<h4>Debug info, this is the state of your *view model*:</h4>
<pre data-bind="text: ko.toJSON($root, null, 2)">```

Debug info, this is the state of an updated model:

```
<h4>Debug info, this is the state of your *initial model* (which doesn't change):</h4>
<pre data-bind="text: ko.toJSON(window.model, null, 2)">``````

Title: KnockoutJS, Binding View

Body:
I'm struggling with issues from KnockoutJS, I have block code below

var viewModel = function (value){
    this.name = ko.observable(value);
}
var model = {}; model.firstName = "ABC";
var AppViewModel = new viewModel(model.firstName);
ko.applyBindings(AppViewModel);

And in HTML i have a view with binding

data-bind="textInput: name".

It's good work. TextView display with text: "ABC".
I have a question. when I change value in TextView. Whether if that model (special firstName) update new value from textView ?

Body:
Your constructor function AppViewModel takes in the Model upon construction. The resulting ViewModel will be two-way data-bound to the view.

What you'd typically have is a reverse method to the constructor, that can be used e.g. when saving the changes through a Model in a back-end. Here's a demo with your example:

function AppViewModel(model){
    var self = this;

    self.firstName = ko.observable(model.firstName);
    self.lastName = ko.observable(model.lastName);

    self.asModel = ko.computed(function() {
        return {
            firstName: self.firstName(),
            lastName: self.lastName()
        };
    });

    self.saveInBackend = function() {
        // Typically you'd ajax here, instead we log the model:
        console.log(self.asModel());
    };
}
var model = {};
model.firstName = "John";
model.lastName = "Doe";

var viewModel = new AppViewModel(model);

ko.applyBindings(viewModel);

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

Firstname: <input data-bind="textInput: firstName"><br>
Lastname: <input data-bind="textInput: lastName"><br>
<button data-bind="click: saveInBackend">saveInBackend</button>
<h4>Debug info, this is the state of your *view model*:</h4>
<pre data-bind="text: ko.toJSON($root, null, 2)"></pre>
<h4>Debug info, this is the state of an updated model:</h4>
<pre data-bind="text: ko.toJSON($root.asModel(), null, 2)"></pre>
<h4>Debug info, this is the state of your *initial model* (which doesn't change):</h4>
<pre data-bind="text: ko.toJSON(window.model, null, 2)"></pre>


来源: stackexchange

问:
After stopping the thread, can I cancel the listen operation with a variable?
I listen to a port in a thread with the following method. While waiting in WaitOne method, I stop the thread (I am doing IsCancellationRequested true) and I can not close the listener object. Then I get an error when I want to listen to the same port.

Can I bind a listener object to a variable? If that variable is false, it will do an automatic shutdown.

I do not want to check that the thread is stopped with a separate thread and close the listener.

```<code>public void StartListening(Connection connection)
{
    // There are codes here..
    try
    {
        listener.Bind(localEndPoint);
        listener.Listen(2);

        while (connection.CancellationTokenSource.IsCancellationRequested == false)
        {
            allDone.Reset();
            listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
            allDone.WaitOne(); // While I'm waiting here, I'm making the 'IsCancellationRequested' variable true.
        }

        listener.Close();
    }
    catch (Exception e)
    {
        // There are codes here..
    }

    // There are codes here..
}
</code>```

Note: The Connection class is a class I created that contains theSystem.Threading.CancellationTokenSource CancellationTokenSource property.

答:
I don't know the precise structure of the connection, but...

You could try waiting on two handles.   (untested)

```<code>var handles = new EventWaitHandle[]
{
    allDone,
    connection.CancellationTokenSource.Token.WaitHandle
};

int index = EventWaitHandle.WaitAny(handles);
</code>```

WaitAny returns the index of the waithandle whois set. So determine if you want to break your while or not.

Maybee something like:

```<code>public void StartListening(Connection connection)
{
    // There are codes here..
    try
    {
        listener.Bind(localEndPoint);
        listener.Listen(2);

        var handles = new EventWaitHandle[]
        {
            allDone,
            connection.CancellationTokenSource.Token.WaitHandle
        };

        do
        {
            allDone.Reset();
            listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
        }
        while(EventWaitHandle.WaitAny(handles) == 0);

        listener.Close();
    }
    catch (Exception e)
    {
        // There are codes here..
    }

    // There are codes here..
}
</code>```

A way to cancel the listener. Can't make up something nicer at the moment. If someone has a better way... feel free ;-)

```<code>ManualResetEvent _listenerTerminated = new ManualResetEvent(false);

// <snip>

listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);

private void AcceptCallback(IAsyncResult ar)
{
    // before calling EndAccept, check an event.
    if(_listenerTerminated.WaitOne(0))
        return;

    var clientSocket = listener.EndAccept(asyncResult);
}

// <snip>

do
{
    allDone.Reset();
    listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
}
while(EventWaitHandle.WaitAny(handles) == 0);

_listenerTerminated.Set();

listener.Close();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I listen to a port in a thread with the following method. While waiting in WaitOne method, I stop the thread (I am doing IsCancellationRequested true) and I can not close the listener object. Then I get an error when I want to listen to the same port.

Can I bind a listener object to a variable? If that variable is false, it will do an automatic shutdown.

I do not want to check that the thread is stopped with a separate thread and close the listener.

public void StartListening(Connection connection)
{
    // There are codes here..
    try
    {
        listener.Bind(localEndPoint);
        listener.Listen(2);

        while (connection.CancellationTokenSource.IsCancellationRequested == false)
        {
            allDone.Reset();
            listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
            allDone.WaitOne(); // While I'm waiting here, I'm making the 'IsCancellationRequested' variable true.
        }

        listener.Close();
    }
    catch (Exception e)
    {
        // There are codes here..
    }

    // There are codes here..
}

Note: The Connection class is a class I created that contains theSystem.Threading.CancellationTokenSource CancellationTokenSource property.

Body:
I don't know the precise structure of the connection, but...

You could try waiting on two handles.   (untested)

var handles = new EventWaitHandle[]
{
    allDone,
    connection.CancellationTokenSource.Token.WaitHandle
};

int index = EventWaitHandle.WaitAny(handles);

WaitAny returns the index of the waithandle whois set. So determine if you want to break your while or not.

Maybee something like:

public void StartListening(Connection connection)
{
    // There are codes here..
    try
    {
        listener.Bind(localEndPoint);
        listener.Listen(2);

        var handles = new EventWaitHandle[]
        {
            allDone,
            connection.CancellationTokenSource.Token.WaitHandle
        };

        do
        {
            allDone.Reset();
            listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
        }
        while(EventWaitHandle.WaitAny(handles) == 0);

        listener.Close();
    }
    catch (Exception e)
    {
        // There are codes here..
    }

    // There are codes here..
}

A way to cancel the listener. Can't make up something nicer at the moment. If someone has a better way... feel free ;-)

ManualResetEvent _listenerTerminated = new ManualResetEvent(false);

// <snip>

listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);

private void AcceptCallback(IAsyncResult ar)
{
    // before calling EndAccept, check an event.
    if(_listenerTerminated.WaitOne(0))
        return;

    var clientSocket = listener.EndAccept(asyncResult);
}

// <snip>

do
{
    allDone.Reset();
    listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
}
while(EventWaitHandle.WaitAny(handles) == 0);

_listenerTerminated.Set();

listener.Close();


问:
PHP: Previous Month from current month formula is not working
It might be Duplicate Question, but I tried but it doesn't work.
Something confusion is there, which I am not getting it.I tried for all months its working but its not working for "March" Month.I know it sound weird, but I tried everything.

Aim: Show Previous Month from Given Month.

PHP:

```<code>$month='March';
$pre_mth =Date("F", strtotime($month . " last month"));
echo $pre_mth;

Actual Output: March    Expected Output:February
</code>```

Please let me know.Thanks in advance.

答:
Extra space existed before "last month". Also, specify a day to avoid conflicts.

Try this:

```<code>$month = 'March 1';
$pre_mth = Date("F", strtotime($month . "last month"));
echo $pre_mth; // February
</code>```

Body:
It might be Duplicate Question, but I tried but it doesn't work.
Something confusion is there, which I am not getting it.I tried for all months its working but its not working for "March" Month.I know it sound weird, but I tried everything.

Aim: Show Previous Month from Given Month.

PHP:

$month='March';
$pre_mth =Date("F", strtotime($month . " last month"));
echo $pre_mth;

Actual Output: March    Expected Output:February

Please let me know.Thanks in advance.

Body:
Extra space existed before "last month". Also, specify a day to avoid conflicts.

Try this:

$month = 'March 1';
$pre_mth = Date("F", strtotime($month . "last month"));
echo $pre_mth; // February


问:
SpringBoot Multiple Data Source JPA
I have following code

Entity

```<code> @Entity
    public class Employee {

        @Id
        @GeneratedValue
        long id;

        @Column(name="first_name")
        String firstName;

        @Column(name="last_name")
        String lastName;

        @Column(name="salary")
        int salary;

        @ManyToOne
        @JoinColumn(name="address")
        Address address;

    ..... setter & getter

    }
</code>```

Repo

```<code>public interface EmpRepository extends JpaRepository<Employee, Long>{}
</code>```

Service

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

    @Autowired
    private EmpRepository empRepo;

    @Autowired @Qualifier("primaryEntityManagerFactory") EntityManager em;

    public List<Employee> findAll(){
        return empRepo.findAll();
    }

}
</code>```

Controller

```<code>@RestController
@RequestMapping(value = "/demo")
public class DemoController {

    @Autowired
    private EmpService empService;

    @RequestMapping("/abcd")
    public List<Employee> findAll(){
        return empService.findAll();
    }

}
</code>```

Data Source Configuraion (Primary)

```<code>@Configuration
@EnableJpaRepositories(basePackages="com.example",
entityManagerFactoryRef = "primaryEntityManagerFactory")
public class DataSourceConfiguration {

    @Bean(name="primaryDataSource")
    @Primary
    @ConfigurationProperties(prefix = "datasource.primary")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager tm = new JpaTransactionManager();
        tm.setEntityManagerFactory(primaryEntityManagerFactory().getObject());
        return tm;
    }

    @Bean(name="primaryEntityManagerFactory")
    @Primary
    LocalContainerEntityManagerFactoryBean primaryEntityManagerFactory() {

        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
        jpaVendorAdapter.setGenerateDdl(true);

        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();

        factoryBean.setDataSource(primaryDataSource());
        factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
        factoryBean.setPackagesToScan(DataSourceConfiguration.class.getPackage().getName());

        return factoryBean;
    }

}
</code>```

Secondary Data Source Config

```<code> @Configuration
@EnableJpaRepositories(basePackages="com.example",
entityManagerFactoryRef = "secondaryEntityManagerFactory")
public class DS2Configuration {

    @Bean(name="secondaryDataSource")
    @ConfigurationProperties(prefix = "datasource.secondary")

    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager tm = new JpaTransactionManager();
        tm.setEntityManagerFactory(secondaryEntityManagerFactory().getObject());
        return tm;
    }

    @Bean(name="secondaryEntityManagerFactory")
    LocalContainerEntityManagerFactoryBean secondaryEntityManagerFactory() {

        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
        jpaVendorAdapter.setGenerateDdl(true);

        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();

        factoryBean.setDataSource(secondaryDataSource());
        factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
        factoryBean.setPackagesToScan(DataSourceConfiguration.class.getPackage().getName());

        return factoryBean;
    }

}
</code>```

application.properties

```<code>spring.jpa.show-sql = true
spring.jpa.properties.hibernate.show_sql=true
spring.jooq.sql-dialect=MYSQL
logging.level.org.springframework.data=DEBUG

# Primary DataSource configuration
datasource.primary.url=jdbc:mysql://127.0.0.1:3306/jpa
datasource.primary.username=root
datasource.primary.password=root

# Secondary DataSource configuration
datasource.secondary.url=jdbc:mysql://127.0.0.1:3306/jpa2
datasource.secondary.username=root
datasource.secondary.password=root

# Disable Spring DataSource auto-initialization
spring.datasource.initialize=false

server.port=8081
</code>```

When I am actually running function findAll() from EmpService, it is always using primary datasource even when i am specifying  secondary entitymanagefactory as

```<code>@Autowired
    @Qualifier("secondaryEntityManagerFactory")
    EntityManager em;
</code>```

How to resolve this?
P.S. - Please do not share blog links for this.

答:
You need to place your Repository classes in two different directories. And change the

```<code>@EnableJpaRepositories(basePackages="com.example".....)
</code>```

line in both the places where you are configuring the datasource. That should fix your problem of

code runs but uses always primary Data Source

Regards

Title: SpringBoot Multiple Data Source JPA

Body:
I have following code

Entity

 @Entity
    public class Employee {

        @Id
        @GeneratedValue
        long id;

        @Column(name="first_name")
        String firstName;

        @Column(name="last_name")
        String lastName;

        @Column(name="salary")
        int salary;

        @ManyToOne
        @JoinColumn(name="address")
        Address address;

    ..... setter & getter

    }

Repo

public interface EmpRepository extends JpaRepository<Employee, Long>{}

Service

@Service
public class EmpService {

    @Autowired
    private EmpRepository empRepo;

    @Autowired @Qualifier("primaryEntityManagerFactory") EntityManager em;

    public List<Employee> findAll(){
        return empRepo.findAll();
    }

}

Controller

@RestController
@RequestMapping(value = "/demo")
public class DemoController {

    @Autowired
    private EmpService empService;

    @RequestMapping("/abcd")
    public List<Employee> findAll(){
        return empService.findAll();
    }

}

Data Source Configuraion (Primary)

@Configuration
@EnableJpaRepositories(basePackages="com.example",
entityManagerFactoryRef = "primaryEntityManagerFactory")
public class DataSourceConfiguration {

    @Bean(name="primaryDataSource")
    @Primary
    @ConfigurationProperties(prefix = "datasource.primary")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager tm = new JpaTransactionManager();
        tm.setEntityManagerFactory(primaryEntityManagerFactory().getObject());
        return tm;
    }

    @Bean(name="primaryEntityManagerFactory")
    @Primary
    LocalContainerEntityManagerFactoryBean primaryEntityManagerFactory() {

        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
        jpaVendorAdapter.setGenerateDdl(true);

        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();

        factoryBean.setDataSource(primaryDataSource());
        factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
        factoryBean.setPackagesToScan(DataSourceConfiguration.class.getPackage().getName());

        return factoryBean;
    }

}

Secondary Data Source Config

 @Configuration
@EnableJpaRepositories(basePackages="com.example",
entityManagerFactoryRef = "secondaryEntityManagerFactory")
public class DS2Configuration {

    @Bean(name="secondaryDataSource")
    @ConfigurationProperties(prefix = "datasource.secondary")

    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager tm = new JpaTransactionManager();
        tm.setEntityManagerFactory(secondaryEntityManagerFactory().getObject());
        return tm;
    }

    @Bean(name="secondaryEntityManagerFactory")
    LocalContainerEntityManagerFactoryBean secondaryEntityManagerFactory() {

        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
        jpaVendorAdapter.setGenerateDdl(true);

        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();

        factoryBean.setDataSource(secondaryDataSource());
        factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
        factoryBean.setPackagesToScan(DataSourceConfiguration.class.getPackage().getName());

        return factoryBean;
    }

}

application.properties

spring.jpa.show-sql = true
spring.jpa.properties.hibernate.show_sql=true
spring.jooq.sql-dialect=MYSQL
logging.level.org.springframework.data=DEBUG

# Primary DataSource configuration
datasource.primary.url=jdbc:mysql://127.0.0.1:3306/jpa
datasource.primary.username=root
datasource.primary.password=root

# Secondary DataSource configuration
datasource.secondary.url=jdbc:mysql://127.0.0.1:3306/jpa2
datasource.secondary.username=root
datasource.secondary.password=root

# Disable Spring DataSource auto-initialization
spring.datasource.initialize=false

server.port=8081

When I am actually running function findAll() from EmpService, it is always using primary datasource even when i am specifying  secondary entitymanagefactory as

@Autowired
    @Qualifier("secondaryEntityManagerFactory")
    EntityManager em;

How to resolve this?
P.S. - Please do not share blog links for this.

Body:
You need to place your Repository classes in two different directories. And change the

@EnableJpaRepositories(basePackages="com.example".....)

line in both the places where you are configuring the datasource. That should fix your problem of

code runs but uses always primary Data Source

Regards


问:
Is it possible to interact with a Linux Command line interface (CLI) through a Graphical user interface (GUI)?
I am quite a beginner, any advice is much appreciated.

I have a linux application OpenBTS used to simulate and run a GSM network on a software defined radio device e.g USRP.

I want to build an application that interfaces with the OpenBTS command line on Linux. I want to give the user an easier way to configure and to display the current configurations of the application. The user would have an interface in which he could play with the configurations without the need to use the  terminal.

I don't know if this is possible ?
Is it possible to interact with a Linux CLI through a GUI ? If yes what is the most efficient programming language, coding technique or approach to do that ?

Thanks a lot

答: In C++, you can take inputs from user through GUI then run appropriate openBTS commands using system()/popen(). Based on the return values of system()/popen(), can provide status of the operation back to the user. </p>


问:
check how many arrays have length greater than 0 in javascript and angularjs
I am trying to create a validation in my app.

What I have, is multiple lists with a toggle (true/false).

If the item is selected, it populates an array.

And I have a different array for each group.

Pretty much something like this:

```<code>$scope.selected = {
  group1: {
    values: []
  },
  group2: {
    values: []
  },
  group3: {
    values: []
  }
}
</code>```

When I select something, let's say, from the list in group 1, $scope.selected changes to this:

```<code>$scope.selected = {
   group1: {
     values: [{cat: 1, id: 1},{cat:1, id:3}]
   }
}
</code>```

The problem I've got is that I am trying to validate this.

What I need is to be able to display a message if multiple values arrays are greater than 0.

For instance if:

```<code>$scope.selected = {
   group1: {
     values: [{cat: 1, id: 1},{cat:1, id:3}]
   },
   group2: {
     values: [{cat: 2, id: 5},{cat:2, id:2}]
   }
}
</code>```

a message should appear as I can't allow to submit multiple groups at once.

I know that I can have some sort of function that checks on the specific name for the groups, but I need something a bit more dynamic, as groups may (and will) increase at some point (ie. I will have more groups that the ones I have now).

Is there any way I can check that only one out of all my group arrays is not empty, and if multiple are not empty, I show something?

thanks and I hope it's clear enough

答:
You can iterate through the object:</p>

```<code>var count = 0;
for (var group in $scope.selected) {
   if ($scope.selected.hasOwnProperty(group) && group.values.length > 0)
      count++;
}

if (count > 1)
   console.log("More than one group with values");
</code>```

Body:
I am trying to create a validation in my app.

What I have, is multiple lists with a toggle (true/false).

If the item is selected, it populates an array.

And I have a different array for each group.

Pretty much something like this:

$scope.selected = {
  group1: {
    values: []
  },
  group2: {
    values: []
  },
  group3: {
    values: []
  }
}

When I select something, let's say, from the list in group 1, $scope.selected changes to this:

$scope.selected = {
   group1: {
     values: [{cat: 1, id: 1},{cat:1, id:3}]
   }
}

The problem I've got is that I am trying to validate this.

What I need is to be able to display a message if multiple values arrays are greater than 0.

For instance if:

$scope.selected = {
   group1: {
     values: [{cat: 1, id: 1},{cat:1, id:3}]
   },
   group2: {
     values: [{cat: 2, id: 5},{cat:2, id:2}]
   }
}

a message should appear as I can't allow to submit multiple groups at once.

I know that I can have some sort of function that checks on the specific name for the groups, but I need something a bit more dynamic, as groups may (and will) increase at some point (ie. I will have more groups that the ones I have now).

Is there any way I can check that only one out of all my group arrays is not empty, and if multiple are not empty, I show something?

thanks and I hope it's clear enough

Body:
You can iterate through the object:

var count = 0;
for (var group in $scope.selected) {
   if ($scope.selected.hasOwnProperty(group) && group.values.length > 0)
      count++;
}

if (count > 1)
   console.log("More than one group with values");


问:
Keycloak and spring boot rest api - user specific data strategy
Keycloak is a user federated identity solution running seperately (standalone) from other systems referencing to it (for authorization for example) having its own database.

Question:
How would I reference / create user specific data in my rest api database?
How would I reference the user in the rest api database to have user specific data?

Think of an table like Post

title,
date,
content,
author (here would be the reference to the user)

答:
We have a similar requirement in a Java EE application, where a user can create data via a JSF website. Data is stored to postrgesql with audit information (username, userid, timestamps,...) so exactly what you want to achieve I suppose.

We have implemented by simply retrieving the information via the access token that is currently available in the session. We also introduced a new user attribute in keycloak itself, which is a custom account id. The user sets it on keycloak GUI and we retrieve it via accessToken.getOtherClaims().get("ACCOUNT_ID") to query user specific data.

The token itself is handled in a filter and used in another bean to retrieve the data which looks like

```<code>@WebFilter(value = "/*")
public class RefreshTokenFilter implements Filter {

  @Inject
  private ServletOAuthClient oauthClient;

  @Inject
  private UserData userData;
  @Context
  KeycloakSecurityContext  sc;

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
  }

  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    if (request.getUserPrincipal() != null) {
      KeycloakSecurityContext keycloakSecurityContext = ((KeycloakPrincipal) request.getUserPrincipal()).getKeycloakSecurityContext();
      userData.setAccessToken(keycloakSecurityContext.getToken());
      userData.setIdToken(keycloakSecurityContext.getIdToken());
    }
    filterChain.doFilter(request, response);
  }

  @Override
  public void destroy() {
  }
}
</code>```

and here I have the bean that handles the data access

```<code>@SessionScoped
@Named("userData")
public class UserData implements Serializable {

  private static final String ACCOUNT_ID = "accountId";
  private AccessToken accessToken;
  private IDToken idToken;

  public String getUserFullName() {
    return isHasAccessToken() ? accessToken.getName() : null;
  }

  public String getUserName() {
    return isHasAccessToken() ? accessToken.getPreferredUsername() : null;
  }

  public String getUserId() {
    return isHasAccessToken() ? accessToken.getSubject() : null;
  }

  public String getRoles() {
    StringBuilder roles = new StringBuilder();
    if (isHasAccessToken()) {
      accessToken.getRealmAccess().getRoles().stream().forEach(s -> roles.append(s).append(" "));
    }
    return roles.toString();
  }

  public boolean hasApplicationRole(String role) {
    return accessToken.getRealmAccess().isUserInRole(role);
  }

  public boolean isHasAccessToken() {
    return accessToken != null;
  }

  public List<String> getAccountIds() {
    return isHasAccessToken() && accessToken.getOtherClaims().get(ACCOUNT_ID)!=null ? (List<String>) accessToken.getOtherClaims().get(ACCOUNT_ID) : new ArrayList<>();
  }

  public void setAccessToken(AccessToken accessToken) {
    this.accessToken = accessToken;
  }

  public void setIdToken(IDToken idToken) {
    this.idToken = idToken;
  }
}
</code>```

I would assume spring boot will give you similar options to deal with the KeycloakSecurityContext.

ContentLicense: CC BY-SA 4.0

Body:
We have a similar requirement in a Java EE application, where a user can create data via a JSF website. Data is stored to postrgesql with audit information (username, userid, timestamps,...) so exactly what you want to achieve I suppose.

We have implemented by simply retrieving the information via the access token that is currently available in the session. We also introduced a new user attribute in keycloak itself, which is a custom account id. The user sets it on keycloak GUI and we retrieve it via accessToken.getOtherClaims().get("ACCOUNT_ID") to query user specific data.

The token itself is handled in a filter and used in another bean to retrieve the data which looks like

@WebFilter(value = "/*")
public class RefreshTokenFilter implements Filter {

  @Inject
  private ServletOAuthClient oauthClient;

  @Inject
  private UserData userData;
  @Context
  KeycloakSecurityContext  sc;

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
  }

  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    if (request.getUserPrincipal() != null) {
      KeycloakSecurityContext keycloakSecurityContext = ((KeycloakPrincipal) request.getUserPrincipal()).getKeycloakSecurityContext();
      userData.setAccessToken(keycloakSecurityContext.getToken());
      userData.setIdToken(keycloakSecurityContext.getIdToken());
    }
    filterChain.doFilter(request, response);
  }

  @Override
  public void destroy() {
  }
}

and here I have the bean that handles the data access

@SessionScoped
@Named("userData")
public class UserData implements Serializable {

  private static final String ACCOUNT_ID = "accountId";
  private AccessToken accessToken;
  private IDToken idToken;

  public String getUserFullName() {
    return isHasAccessToken() ? accessToken.getName() : null;
  }

  public String getUserName() {
    return isHasAccessToken() ? accessToken.getPreferredUsername() : null;
  }

  public String getUserId() {
    return isHasAccessToken() ? accessToken.getSubject() : null;
  }

  public String getRoles() {
    StringBuilder roles = new StringBuilder();
    if (isHasAccessToken()) {
      accessToken.getRealmAccess().getRoles().stream().forEach(s -> roles.append(s).append(" "));
    }
    return roles.toString();
  }

  public boolean hasApplicationRole(String role) {
    return accessToken.getRealmAccess().isUserInRole(role);
  }

  public boolean isHasAccessToken() {
    return accessToken != null;
  }

  public List<String> getAccountIds() {
    return isHasAccessToken() && accessToken.getOtherClaims().get(ACCOUNT_ID)!=null ? (List<String>) accessToken.getOtherClaims().get(ACCOUNT_ID) : new ArrayList<>();
  }

  public void setAccessToken(AccessToken accessToken) {
    this.accessToken = accessToken;
  }

  public void setIdToken(IDToken idToken) {
    this.idToken = idToken;
  }
}

I would assume spring boot will give you similar options to deal with the KeycloakSecurityContext.


问:
Merge two list (java 7)
I have two lists of Personne:  listOne and listTwo.

Personne is:

```<code>public class Personne{
    private String name;
    private Favorite favorite;
    private Collection<Number>  numbers;
}

public class Favorite{
    private String id;
    private String name;
    ...
}
</code>```

For each item, I want to merge the two lists if the favorite name and id of the first list equals the favorite name and id of the second list, and then merge the second list to first.

This is a part of my treatement and what i means by merge (its not create an other list ) :

if my condition is true i want to take item of my first list :

```<code>item.setNumbers(item2.getnumbers);
</code>```

What is the best way to do this with Java 7?

答:
As far as I have understood, we want to get a list containing all unique elements of both lists without duplicates.

First let's create an equals() method for the classes which is needed for ArrayList.contains() method to function properly:

```<code>class Favorite {
    ...
    private boolean equals(Favorite other) {
        int i = id.compareTo(other.id);
        if (i != 0) return false;

        return (name.compareTo(other.name) == 0);
    }

class Personnel {
    ...
    private boolean equals(Personnel other) {
        int i = name.compareTo(other.name);
        if (i != 0) return false;

        return favorite.equals(other.favorite);
    }
</code>```

Since there is no guarantee that input lists are sorted, we can write merging method like this:

```<code>    public List<Personnel> merge(List<Personnel> listOne, List<Personnel> listTwo) {
        List<Personnel> result = new ArrayList<>(listOne);

        for (Personnel p : listTwo) {
            if (!result.contains(p)) {
                result.add(p);
            }
        }

        return result;
    }
</code>```

Title: Merge two list (java 7)

Body:
I have two lists of Personne:  listOne and listTwo.

Personne is:

public class Personne{
    private String name;
    private Favorite favorite;
    private Collection<Number>  numbers;
}

public class Favorite{
    private String id;
    private String name;
    ...
}

For each item, I want to merge the two lists if the favorite name and id of the first list equals the favorite name and id of the second list, and then merge the second list to first.

This is a part of my treatement and what i means by merge (its not create an other list ) :

if my condition is true i want to take item of my first list :

item.setNumbers(item2.getnumbers);

What is the best way to do this with Java 7?

Body:
As far as I have understood, we want to get a list containing all unique elements of both lists without duplicates.

First let's create an equals() method for the classes which is needed for ArrayList.contains() method to function properly:

class Favorite {
    ...
    private boolean equals(Favorite other) {
        int i = id.compareTo(other.id);
        if (i != 0) return false;

        return (name.compareTo(other.name) == 0);
    }

class Personnel {
    ...
    private boolean equals(Personnel other) {
        int i = name.compareTo(other.name);
        if (i != 0) return false;

        return favorite.equals(other.favorite);
    }

Since there is no guarantee that input lists are sorted, we can write merging method like this:

    public List<Personnel> merge(List<Personnel> listOne, List<Personnel> listTwo) {
        List<Personnel> result = new ArrayList<>(listOne);

        for (Personnel p : listTwo) {
            if (!result.contains(p)) {
                result.add(p);
            }
        }

        return result;
    }


问:
Exceptions with Unicode what()
Or, "how do Russians throw exceptions?"

The definition of std::exception is:

```<code>namespace std {
  class exception {
  public:
    exception() throw();
    exception(const exception&) throw();
    exception& operator=(const exception&) throw();
    virtual ~exception() throw();
    virtual const char* what() const throw();
  };
}
</code>```

A popular school of thought for designing exception hierarchies is to derive from std::exception:

Generally, it's best to throw objects,
not built-ins. If possible, you should
throw instances of classes that derive
(ultimately) from the std::exception
class. By making your exception class
inherit (ultimately) from the standard
exception base-class, you are making
life easier for your users (they have
the option of catching most things via
std::exception), plus you are probably
providing them with more information
(such as the fact that your particular
exception might be a refinement of
std::runtime_error or whatever).

But in the face of Unicode, it seems to be impossible to design an exception hierarchy that achieves both of the following:

Derives ultimately from std::exception for ease of use at the catch site

Provides Unicode compatibility so that diagnostics are not sliced or gibberish

Coming up with an exception class that can be constructed with Unicode strings is simple enough.  But the standard dictates that what() must return a const char*, so at some point the input strings must be converted to ASCII.  Whether that is done at construction time or when what() is called (if the source string uses characters not representable by 7-bit ASCII), it might be impossible to format the message without loss of fidelity.

How do you design an exception hierarchy that combines the seamless integration of a std::exception-derived class with lossless Unicode diagnostics?

答:
It is better way to add unicode in error processing:

```<code>try
{
   // some code
}
catch (std::exception & ex)
{
    report_problem(ex.what())
}
</code>```

And :

```<code>void report_problem(char const * const)
{
   // here we can convert char to wchar_t or do some more else
   // log it, save to file or message to user
}
</code>```

Title: Exceptions with Unicode what()

Body:
Or, "how do Russians throw exceptions?"

The definition of std::exception is:

namespace std {
  class exception {
  public:
    exception() throw();
    exception(const exception&) throw();
    exception& operator=(const exception&) throw();
    virtual ~exception() throw();
    virtual const char* what() const throw();
  };
}

A popular school of thought for designing exception hierarchies is to derive from std::exception:

Generally, it's best to throw objects,
not built-ins. If possible, you should
throw instances of classes that derive
(ultimately) from the std::exception
class. By making your exception class
inherit (ultimately) from the standard
exception base-class, you are making
life easier for your users (they have
the option of catching most things via
std::exception), plus you are probably
providing them with more information
(such as the fact that your particular
exception might be a refinement of
std::runtime_error or whatever).

But in the face of Unicode, it seems to be impossible to design an exception hierarchy that achieves both of the following:

Derives ultimately from std::exception for ease of use at the catch site

Provides Unicode compatibility so that diagnostics are not sliced or gibberish

Coming up with an exception class that can be constructed with Unicode strings is simple enough.  But the standard dictates that what() must return a const char*, so at some point the input strings must be converted to ASCII.  Whether that is done at construction time or when what() is called (if the source string uses characters not representable by 7-bit ASCII), it might be impossible to format the message without loss of fidelity.

How do you design an exception hierarchy that combines the seamless integration of a std::exception-derived class with lossless Unicode diagnostics?

LastEditorDisplayName: Roger Pate

Body:
It is better way to add unicode in error processing:

try
{
   // some code
}
catch (std::exception & ex)
{
    report_problem(ex.what())
}

And :

void report_problem(char const * const)
{
   // here we can convert char to wchar_t or do some more else
   // log it, save to file or message to user
}

ContentLicense: CC BY-SA 2.5


问:
Getting Unknown Command error on IF-THEN-ELSE
I have the following query that I am using in Oracle 11g

```<code>IF EXISTS (SELECT * FROM EMPLOYEE_MASTER WHERE EMPID='ABCD32643')
THEN
update EMPLOYEE_MASTER set EMPID='A62352',EMPNAME='JOHN DOE',EMPTYPE='1' where EMPID='ABCD32643' ;
ELSE
insert into EMPLOYEE_MASTER(EMPID,EMPNAME,EMPTYPE) values('A62352','JOHN DOE','1') ;
END IF;
</code>```

On running the statement I get the following output:

```<code>Error starting at line : 4 in command -
ELSE
Error report -
Unknown Command

1 row inserted.

Error starting at line : 6 in command -
END IF
Error report -
Unknown Command
</code>```

The values get inserted with error when I run it directly. But when I try to execute this query through my application I get an oracle exception because of the error generated :

```<code>ORA-00900: invalid SQL statement
</code>```

And hence the values are not inserted.

I am relatively new to Oracle. Please advise on what's wrong with the above query so that I could run this query error free.

答:
If MERGE doesn't work for you, try the following:

```<code>begin
  update EMPLOYEE_MASTER set EMPID='A62352',EMPNAME='JOHN DOE',EMPTYPE='1'
    where EMPID='ABCD32643' ;
  if SQL%ROWCOUNT=0 then
    insert into EMPLOYEE_MASTER(EMPID,EMPNAME,EMPTYPE)
      values('A62352','JOHN DOE','1') ;
  end if;
end;
</code>```

Here you you the update on spec, then check whether or not you found a matching row, and insert in case you didn't.

Body:
I have the following query that I am using in Oracle 11g

IF EXISTS (SELECT * FROM EMPLOYEE_MASTER WHERE EMPID='ABCD32643')
THEN
update EMPLOYEE_MASTER set EMPID='A62352',EMPNAME='JOHN DOE',EMPTYPE='1' where EMPID='ABCD32643' ;
ELSE
insert into EMPLOYEE_MASTER(EMPID,EMPNAME,EMPTYPE) values('A62352','JOHN DOE','1') ;
END IF;

On running the statement I get the following output:

Error starting at line : 4 in command -
ELSE
Error report -
Unknown Command

1 row inserted.

Error starting at line : 6 in command -
END IF
Error report -
Unknown Command

The values get inserted with error when I run it directly. But when I try to execute this query through my application I get an oracle exception because of the error generated :

ORA-00900: invalid SQL statement

And hence the values are not inserted.

I am relatively new to Oracle. Please advise on what's wrong with the above query so that I could run this query error free.

Body:
If MERGE doesn't work for you, try the following:

begin
  update EMPLOYEE_MASTER set EMPID='A62352',EMPNAME='JOHN DOE',EMPTYPE='1'
    where EMPID='ABCD32643' ;
  if SQL%ROWCOUNT=0 then
    insert into EMPLOYEE_MASTER(EMPID,EMPNAME,EMPTYPE)
      values('A62352','JOHN DOE','1') ;
  end if;
end;

Here you you the update on spec, then check whether or not you found a matching row, and insert in case you didn't.


问:
python split by "\t" is not showing all elements in it
I am trying to split by "\t" but it is not printing all the elements in it

```<code>import sys
reload(sys)
sys.setdefaultencoding('utf8')

s = ['A\t"Ravi"\t"Tirupur"\t"India"\t"641652"\t"arunachalamravi@gmail.com"\t"17379602"\t"+ 2"\t"Government Higher Secondary School', ' Tiruppur"\t\t"1989"\t"Maths',' Science"\t"No"\t"Encotec Energy 2 X 600 MW ITPCL"\t"Associate Vice President- Head Maintenance"\t"2015"\t"2016"\t"No"\t"27-Mar-2017"\t"9937297878"\t\t"2874875"\t"Submitted"\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t']
print s[0].split("\t")
</code>```

Results

```<code>['A', '"Ravi"', '"Tirupur"', '"India"', '"641652"', '"arunachalamravi@gmail.com"', '"17379602"', '"+ 2"', '"Government Higher Secondary School']
</code>```

But i want results upto this

```<code>2874875, Submitted
</code>```

How to fix the code and where is the change?

答:
You could use Python's chain() function to create a single list from the multiple elements:

```<code>from itertools import chain

s = ['A\t"Ravi"\t"Tirupur"\t"India"\t"641652"\t"arunachalamravi@gmail.com"\t"17379602"\t"+ 2"\t"Government Higher Secondary School', ' Tiruppur"\t\t"1989"\t"Maths',' Science"\t"No"\t"Encotec Energy 2 X 600 MW ITPCL"\t"Associate Vice President- Head Maintenance"\t"2015"\t"2016"\t"No"\t"27-Mar-2017"\t"9937297878"\t\t"2874875"\t"Submitted"\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t']

result = list(chain.from_iterable(x.rstrip('\t').split('\t') for x in s))
print result
</code>```

This would give you all of the split entries, and remove the trailing tabs from the end:

```<code>['A', '"Ravi"', '"Tirupur"', '"India"', '"641652"', '"arunachalamravi@gmail.com"', '"17379602"', '"+ 2"', '"Government Higher Secondary School', ' Tiruppur"', '', '"1989"', '"Maths', ' Science"', '"No"', '"Encotec Energy 2 X 600 MW ITPCL"', '"Associate Vice President- Head Maintenance"', '"2015"', '"2016"', '"No"', '"27-Mar-2017"', '"9937297878"', '', '"2874875"', '"Submitted"']
</code>```

If you also want to get rid of the quotes, then use this instead:

```<code>result = [v.strip('"') for v in chain.from_iterable(x.rstrip('\t').split('\t') for x in s)]
</code>```

Giving you:

```<code>['A', 'Ravi', 'Tirupur', 'India', '641652', 'arunachalamravi@gmail.com', '17379602', '+ 2', 'Government Higher Secondary School', ' Tiruppur', '', '1989', 'Maths', ' Science', 'No', 'Encotec Energy 2 X 600 MW ITPCL', 'Associate Vice President- Head Maintenance', '2015', '2016', 'No', '27-Mar-2017', '9937297878', '', '2874875', 'Submitted']
</code>```

Body:
I am trying to split by "\t" but it is not printing all the elements in it

import sys
reload(sys)
sys.setdefaultencoding('utf8')

s = ['A\t"Ravi"\t"Tirupur"\t"India"\t"641652"\t"arunachalamravi@gmail.com"\t"17379602"\t"+ 2"\t"Government Higher Secondary School', ' Tiruppur"\t\t"1989"\t"Maths',' Science"\t"No"\t"Encotec Energy 2 X 600 MW ITPCL"\t"Associate Vice President- Head Maintenance"\t"2015"\t"2016"\t"No"\t"27-Mar-2017"\t"9937297878"\t\t"2874875"\t"Submitted"\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t']
print s[0].split("\t")

Results

['A', '"Ravi"', '"Tirupur"', '"India"', '"641652"', '"arunachalamravi@gmail.com"', '"17379602"', '"+ 2"', '"Government Higher Secondary School']

But i want results upto this

2874875, Submitted

How to fix the code and where is the change?

Body:
You could use Python's chain() function to create a single list from the multiple elements:

from itertools import chain

s = ['A\t"Ravi"\t"Tirupur"\t"India"\t"641652"\t"arunachalamravi@gmail.com"\t"17379602"\t"+ 2"\t"Government Higher Secondary School', ' Tiruppur"\t\t"1989"\t"Maths',' Science"\t"No"\t"Encotec Energy 2 X 600 MW ITPCL"\t"Associate Vice President- Head Maintenance"\t"2015"\t"2016"\t"No"\t"27-Mar-2017"\t"9937297878"\t\t"2874875"\t"Submitted"\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t']

result = list(chain.from_iterable(x.rstrip('\t').split('\t') for x in s))
print result

This would give you all of the split entries, and remove the trailing tabs from the end:

['A', '"Ravi"', '"Tirupur"', '"India"', '"641652"', '"arunachalamravi@gmail.com"', '"17379602"', '"+ 2"', '"Government Higher Secondary School', ' Tiruppur"', '', '"1989"', '"Maths', ' Science"', '"No"', '"Encotec Energy 2 X 600 MW ITPCL"', '"Associate Vice President- Head Maintenance"', '"2015"', '"2016"', '"No"', '"27-Mar-2017"', '"9937297878"', '', '"2874875"', '"Submitted"']

If you also want to get rid of the quotes, then use this instead:

result = [v.strip('"') for v in chain.from_iterable(x.rstrip('\t').split('\t') for x in s)]

Giving you:

['A', 'Ravi', 'Tirupur', 'India', '641652', 'arunachalamravi@gmail.com', '17379602', '+ 2', 'Government Higher Secondary School', ' Tiruppur', '', '1989', 'Maths', ' Science', 'No', 'Encotec Energy 2 X 600 MW ITPCL', 'Associate Vice President- Head Maintenance', '2015', '2016', 'No', '27-Mar-2017', '9937297878', '', '2874875', 'Submitted']


问:
I can't connect using an api
I'm quite new to API's so I don't know if this should be more straight forward.

I write the following perl script

```<code>use strict;
use  LWP::UserAgent;
require HTTP::Request;

my $request = HTTP::Request->new(GET => 'http://api.elsevier.com/content/ev/results?apiKey=1234&query=stress&database=c&updateNumber=1&pageSize=1');

my $ua = LWP::UserAgent->new;
my  $response = $ua->request($request);
</code>```

then when I get my response and print it in the debugger I get the following

```<code>HTTP::Response=HASH(0x9aedff8)
   '_content' => '{"service-error":{"status":{"statusCode":"AUTHENTICATION_ERROR","statusText":"Requestor configuration settings insufficient for access to this resource."}}}'
   '_headers' => HTTP::Headers=HASH(0x9aedfe8)
      'allow' => 'GET'
      'client-date' => 'Wed, 29 Mar 2017 08:08:25 GMT'
      'client-peer' => '198.185.19.118:80'
      'client-response-num' => 1
      'content-length' => 156
      'content-type' => 'application/json;charset=UTF-8'
      'date' => 'Wed, 29 Mar 2017 08:08:24 GMT'
      'p3p' => 'CP="IDC DSP LAW ADM DEV TAI PSA PSD IVA IVD CON HIS TEL OUR DEL SAM OTR IND OTC"'
      'server' => 'api.elsevier.com  9999'
      'vary' => 'Origin'
      'x-cnection' => 'close'
      'x-els-apikey' => 'e688c9db4db0386581dbe4c4dda46164'
      'x-els-reqid' => '0000015b190d89fe-a0d0'
      'x-els-status' => 'AUTHENTICATION_ERROR(Requestor configuration settings insufficient for access to this resource.)'
      'x-els-transid' => 'cbf787b4-d171-4e35-8237-8cab3c931205'
      'x-re-ref' => '1 1490774904423414'
   '_msg' => 'Forbidden'
   '_protocol' => 'HTTP/1.1'
   '_rc' => 403
   '_request' => HTTP::Request=HASH(0x9fc3000)
      '_content' => ''
      '_headers' => HTTP::Headers=HASH(0x9ae73e0)
         'user-agent' => 'libwww-perl/5.831'
      '_method' => 'GET'
      '_uri' => URI::http=SCALAR(0x9e25188)
         -> 'http://api.elsevier.com/content/ev/results?apiKey=e688c9db4db0386581dbe4c4dda46164&query=stress&database=c&updateNumber=1&pageSize=1'
      '_uri_canonical' => URI::http=SCALAR(0x9e25188)
         -> REUSED_ADDRESS
</code>```

one of the notable lines is

```<code>x-els-status' => 'AUTHENTICATION_ERROR(Requestor configuration settings     insufficient for access to this resource.)'
</code>```

I don't know how to get a proper response text. I tried searching their websites for examples, but I can't seem to get it. as well I'm not sure if the key is only for scopus but not engineering village which I'm trying to use.

There website is here. https://dev.elsevier.com/index.html?utm_expid=89327795-0.AtRZzToKQ2u1mZEyQ3n7OQ.0&utm_referrer=https%3A%2F%2Fdev.elsevier.com%2Ftecdoc_ev_retrieval_request.html

any help would be appreciated

答:
To get the text out of your response, you need to call the $response->decoded_content method. That will give you the JSON string that you can see in _content in your debug output. I've indented it to make it easier to read.

```<code>{
   "service-error" : {
      "status" : {
         "statusCode" : "AUTHENTICATION_ERROR",
         "statusText" : "Requestor configuration settings insufficient for access to this resource."
      }
   }
}
</code>```

You can use the JSON module to decode this into a Perl data structure.

```<code>use JSON 'from_json';

my $res = $ua->request($req);
my $json = from_json( $res->decoded_content );
</code>```

The error message you get back clearly states that you are not authenticated properly. I've looked at this guide from the documentation you mentioned. It seems that the apiKey URL param works, if you have the right type of account. You should check with whoever made that account for you, or if that was you and you're not sure, the account manager at that service that is working with you. They'll tell you if you are using the right API key, and if this method of authentication works for you.

Since this API also offers to use a custom header X-ELS-APIKey: [apikey] for the authentication I would suggest using that. Your API key is a secret, and you shouldn't share it with anyone. It's like a password. If you put it into the URL, it might show up in log files. But as a header, it does usually not.

This is how you add a custom header to an HTTP request. Make sure you don't have the apiKey URL param any more if you do this.

```<code>my $req = HTTP::Request->new( GET => $url ); # no apiKey=123 here!
$req->header( 'X-ELS-APIKey' => 123 );
</code>```

Now as a last step, you should check the HTTP response code of the response. A 200 (or most other codes that start with 2) means the request was successful. The 403 that you are getting back means unauthorized, which also hints at that you are not authenticated correctly.

Since it seems that this API returns JSON in both success and failure cases, you might need to decode it for both. If you care to examine the failure response, that makes sense. If not, you can skip that part. To do this, use $res->is_success, which is also used in the synopsis of the LWP::UserAgent documentation.

```<code>use strict;
use warnings;
use LWP::UserAgent;
use HTTP::Request;
use JSON 'from_json';

my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new( GET => 'http://api.elsevier.com/content/ev/results?query=stress&database=c&updateNumber=1&pageSize=1' );
$req->header( 'X-ELS-APIKey' => 123 );

if ($req->is_success) {
    my $json = from_json( $res->decoded_content );
    # ... do stuff with the response
} else {
    # something went wrong
}
</code>```

Title: I can't connect using an api

Body:
I'm quite new to API's so I don't know if this should be more straight forward.

I write the following perl script

use strict;
use  LWP::UserAgent;
require HTTP::Request;

my $request = HTTP::Request->new(GET => 'http://api.elsevier.com/content/ev/results?apiKey=1234&query=stress&database=c&updateNumber=1&pageSize=1');

my $ua = LWP::UserAgent->new;
my  $response = $ua->request($request);

then when I get my response and print it in the debugger I get the following

HTTP::Response=HASH(0x9aedff8)
   '_content' => '{"service-error":{"status":{"statusCode":"AUTHENTICATION_ERROR","statusText":"Requestor configuration settings insufficient for access to this resource."}}}'
   '_headers' => HTTP::Headers=HASH(0x9aedfe8)
      'allow' => 'GET'
      'client-date' => 'Wed, 29 Mar 2017 08:08:25 GMT'
      'client-peer' => '198.185.19.118:80'
      'client-response-num' => 1
      'content-length' => 156
      'content-type' => 'application/json;charset=UTF-8'
      'date' => 'Wed, 29 Mar 2017 08:08:24 GMT'
      'p3p' => 'CP="IDC DSP LAW ADM DEV TAI PSA PSD IVA IVD CON HIS TEL OUR DEL SAM OTR IND OTC"'
      'server' => 'api.elsevier.com  9999'
      'vary' => 'Origin'
      'x-cnection' => 'close'
      'x-els-apikey' => 'e688c9db4db0386581dbe4c4dda46164'
      'x-els-reqid' => '0000015b190d89fe-a0d0'
      'x-els-status' => 'AUTHENTICATION_ERROR(Requestor configuration settings insufficient for access to this resource.)'
      'x-els-transid' => 'cbf787b4-d171-4e35-8237-8cab3c931205'
      'x-re-ref' => '1 1490774904423414'
   '_msg' => 'Forbidden'
   '_protocol' => 'HTTP/1.1'
   '_rc' => 403
   '_request' => HTTP::Request=HASH(0x9fc3000)
      '_content' => ''
      '_headers' => HTTP::Headers=HASH(0x9ae73e0)
         'user-agent' => 'libwww-perl/5.831'
      '_method' => 'GET'
      '_uri' => URI::http=SCALAR(0x9e25188)
         -> 'http://api.elsevier.com/content/ev/results?apiKey=e688c9db4db0386581dbe4c4dda46164&query=stress&database=c&updateNumber=1&pageSize=1'
      '_uri_canonical' => URI::http=SCALAR(0x9e25188)
         -> REUSED_ADDRESS

one of the notable lines is

x-els-status' => 'AUTHENTICATION_ERROR(Requestor configuration settings     insufficient for access to this resource.)'

I don't know how to get a proper response text. I tried searching their websites for examples, but I can't seem to get it. as well I'm not sure if the key is only for scopus but not engineering village which I'm trying to use.

There website is here. https://dev.elsevier.com/index.html?utm_expid=89327795-0.AtRZzToKQ2u1mZEyQ3n7OQ.0&utm_referrer=https%3A%2F%2Fdev.elsevier.com%2Ftecdoc_ev_retrieval_request.html

any help would be appreciated

Body:
To get the text out of your response, you need to call the $response->decoded_content method. That will give you the JSON string that you can see in _content in your debug output. I've indented it to make it easier to read.

{
   "service-error" : {
      "status" : {
         "statusCode" : "AUTHENTICATION_ERROR",
         "statusText" : "Requestor configuration settings insufficient for access to this resource."
      }
   }
}

You can use the JSON module to decode this into a Perl data structure.

use JSON 'from_json';

my $res = $ua->request($req);
my $json = from_json( $res->decoded_content );

The error message you get back clearly states that you are not authenticated properly. I've looked at this guide from the documentation you mentioned. It seems that the apiKey URL param works, if you have the right type of account. You should check with whoever made that account for you, or if that was you and you're not sure, the account manager at that service that is working with you. They'll tell you if you are using the right API key, and if this method of authentication works for you.

Since this API also offers to use a custom header X-ELS-APIKey: [apikey] for the authentication I would suggest using that. Your API key is a secret, and you shouldn't share it with anyone. It's like a password. If you put it into the URL, it might show up in log files. But as a header, it does usually not.

This is how you add a custom header to an HTTP request. Make sure you don't have the apiKey URL param any more if you do this.

my $req = HTTP::Request->new( GET => $url ); # no apiKey=123 here!
$req->header( 'X-ELS-APIKey' => 123 );

Now as a last step, you should check the HTTP response code of the response. A 200 (or most other codes that start with 2) means the request was successful. The 403 that you are getting back means unauthorized, which also hints at that you are not authenticated correctly.

Since it seems that this API returns JSON in both success and failure cases, you might need to decode it for both. If you care to examine the failure response, that makes sense. If not, you can skip that part. To do this, use $res->is_success, which is also used in the synopsis of the LWP::UserAgent documentation.

use strict;
use warnings;
use LWP::UserAgent;
use HTTP::Request;
use JSON 'from_json';

my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new( GET => 'http://api.elsevier.com/content/ev/results?query=stress&database=c&updateNumber=1&pageSize=1' );
$req->header( 'X-ELS-APIKey' => 123 );

if ($req->is_success) {
    my $json = from_json( $res->decoded_content );
    # ... do stuff with the response
} else {
    # something went wrong
}


问:
A Stranger Error of database in Intellij IDEA
I got a error called java.lang.AbstractMethodError: com.mysql.jdbc.Connection.isValid(I)Z when I connected IDEA with mysql database.
I think my configuration is correct as below.In addition, the test is successful.
The configuration pic

And then the something stranger happened. I cannot get the any schemes from my database on the database tool window,but I can get them with Navicat. When I type SELECT * FROM message into console, that error appeared as below.

```<code>[2017-03-29 17:51:28] java.lang.AbstractMethodError: com.mysql.jdbc.Connection.isValid(I)Z
[2017-03-29 17:51:28]   at com.intellij.database.remote.jdbc.impl.RemoteConnectionImpl.isValid(RemoteConnectionImpl.java:108)
[2017-03-29 17:51:28]   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[2017-03-29 17:51:28]   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[2017-03-29 17:51:28]   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[2017-03-29 17:51:28]   at java.lang.reflect.Method.invoke(Method.java:497)
[2017-03-29 17:51:28]   at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:323)
[2017-03-29 17:51:28]   at sun.rmi.transport.Transport$1.run(Transport.java:200)
[2017-03-29 17:51:28]   at sun.rmi.transport.Transport$1.run(Transport.java:197)
[2017-03-29 17:51:28]   at java.security.AccessController.doPrivileged(Native Method)
[2017-03-29 17:51:28]   at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
[2017-03-29 17:51:28]   at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
[2017-03-29 17:51:28]   at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
[2017-03-29 17:51:28]   at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$256(TCPTransport.java:683)
[2017-03-29 17:51:28]   at java.security.AccessController.doPrivileged(Native Method)
[2017-03-29 17:51:28]   at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
[2017-03-29 17:51:28]   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
[2017-03-29 17:51:28]   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
[2017-03-29 17:51:28]   at java.lang.Thread.run(Thread.java:745)
</code>```

I search Internet for this question via google, then I upgrade mysql driver  to even ver.5.1.40.But it doesn't work as well.
The driver pic

So, How to deal with this error? It stuck me two days.
Thanks in advance.

答:
java.lang.AbstractMethodError: com.mysql.jdbc.Connection.isValid(I)Z

This will help you.

I think you have to remove the previous MySQL driver.

Body:
I got a error called java.lang.AbstractMethodError: com.mysql.jdbc.Connection.isValid(I)Z when I connected IDEA with mysql database.
I think my configuration is correct as below.In addition, the test is successful.
The configuration pic

And then the something stranger happened. I cannot get the any schemes from my database on the database tool window,but I can get them with Navicat. When I type SELECT * FROM message into console, that error appeared as below.

[2017-03-29 17:51:28] java.lang.AbstractMethodError: com.mysql.jdbc.Connection.isValid(I)Z
[2017-03-29 17:51:28]   at com.intellij.database.remote.jdbc.impl.RemoteConnectionImpl.isValid(RemoteConnectionImpl.java:108)
[2017-03-29 17:51:28]   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[2017-03-29 17:51:28]   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[2017-03-29 17:51:28]   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[2017-03-29 17:51:28]   at java.lang.reflect.Method.invoke(Method.java:497)
[2017-03-29 17:51:28]   at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:323)
[2017-03-29 17:51:28]   at sun.rmi.transport.Transport$1.run(Transport.java:200)
[2017-03-29 17:51:28]   at sun.rmi.transport.Transport$1.run(Transport.java:197)
[2017-03-29 17:51:28]   at java.security.AccessController.doPrivileged(Native Method)
[2017-03-29 17:51:28]   at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
[2017-03-29 17:51:28]   at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
[2017-03-29 17:51:28]   at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
[2017-03-29 17:51:28]   at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$256(TCPTransport.java:683)
[2017-03-29 17:51:28]   at java.security.AccessController.doPrivileged(Native Method)
[2017-03-29 17:51:28]   at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
[2017-03-29 17:51:28]   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
[2017-03-29 17:51:28]   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
[2017-03-29 17:51:28]   at java.lang.Thread.run(Thread.java:745)

I search Internet for this question via google, then I upgrade mysql driver  to even ver.5.1.40.But it doesn't work as well.
The driver pic

So, How to deal with this error? It stuck me two days.
Thanks in advance.


问:
To draw some points by using QImage, QWidget.update() is too slow, Is there more faster way?
I'm trying to draw a point on the window by using QImage, and update the position of this point as fast as possible(less than 1ms every update). I've wrote the code below and run it, but the result is it's too slow(about 50ms every update). I searched the bottleneck and found the cause of this slowness is calling QWidget.update() takes too long. So I figured out as long as using Widget.update() it won't be faster. So I think I need another way. Is there any faster way to do this? All of the codes and the result are the following.

result:

qimageBehaviorForStackOverflowQuestion.pro

```<code>######################################################################
# Automatically generated by qmake (3.1) Wed Mar 29 15:18:09 2017
######################################################################

TEMPLATE = app
TARGET = qimageBehaviorForStackOverflowQuestion
INCLUDEPATH += .
QT += widgets

# Input
HEADERS += qimageBehaviorForStackOverflowQuestion.h
SOURCES += qimageBehaviorForStackOverflowQuestion.cpp
</code>```

qimageBehaviorForStackOverflowQuestion.h

```<code>#include <iostream>
#include <QApplication>
#include <QWidget>
#include <QTimer>
#include <QPainter>
#include <QPushButton>
#include <QImage>
#include <QTime>

class MyWidget : public QWidget {
  Q_OBJECT
 private:
  QImage *image;
  int px, py;
  uchar d[100*100*4];
  QTimer *timer;
  QTime time;
public:
  MyWidget();
  void paintEvent(QPaintEvent * event);
public slots:
  void doPaint();
};
</code>```

qimageBehaviorForStackOverflowQuestion.cpp

```<code>#include "qimageBehaviorForStackOverflowQuestion.h"

int my_counter = 0;

MyWidget::MyWidget() : QWidget(0), px(0), py(0){
  image = new QImage(d, 100, 100, QImage::Format_ARGB32);
  for(int cnt = 0, a, r, g, b; cnt < 100*100*4;){
    a = 255; //alpha
    r = 0;   //red
    g = 0;   //green
    b = 0;   //blue

    d[cnt] = b; cnt++;
    d[cnt] = g; cnt++;
    d[cnt] = r; cnt++;
    d[cnt] = a; cnt++;
  }
  // connect QTimer.timeout to my doPaint method
  timer = new QTimer();
  connect(timer, SIGNAL(timeout()), this, SLOT(doPaint()));
  timer->start(1);
};

void MyWidget::doPaint(){
  // manipulate the positions of the points
  if(px < 100){
    int cnt = 0, b = 255, g = 255, r = 255, a = 255;
    d[4 * px + cnt] = b; cnt++;
    d[4 * px + cnt] = g; cnt++;
    d[4 * px + cnt] = r; cnt++;
    d[4 * px + cnt] = a; cnt++;
    px++;
  }
  // update the window
  update();
};

void MyWidget::paintEvent(QPaintEvent * event){
    QPainter painter(this);
    painter.drawImage(0, 0, *image);
}

int main(int argc, char *argv[]){
  QApplication app(argc, argv);
  MyWidget *widget = new MyWidget();
  widget->show();
  return app.exec();
}
</code>```

答:
Consider changing the incrementation of Px to more than +1, +5 for example. that will reduce the calls of doPaint() function by 5 times. and will speed up the drawing.  Because your problem is that you are updating the drawing a lot, 100 times.

P.S : you should also stop the timer to stop calling doPaint() function when the drawing is finished. because it is called every 1ms. since timer.start(1) will emit timeout() signal every 1ms.

Edit:
Consider also changing the timeout that is very light (an update every 1ms <=> 1000 FPS).

Body:
I'm trying to draw a point on the window by using QImage, and update the position of this point as fast as possible(less than 1ms every update). I've wrote the code below and run it, but the result is it's too slow(about 50ms every update). I searched the bottleneck and found the cause of this slowness is calling QWidget.update() takes too long. So I figured out as long as using Widget.update() it won't be faster. So I think I need another way. Is there any faster way to do this? All of the codes and the result are the following.

result:

qimageBehaviorForStackOverflowQuestion.pro

######################################################################
# Automatically generated by qmake (3.1) Wed Mar 29 15:18:09 2017
######################################################################

TEMPLATE = app
TARGET = qimageBehaviorForStackOverflowQuestion
INCLUDEPATH += .
QT += widgets

# Input
HEADERS += qimageBehaviorForStackOverflowQuestion.h
SOURCES += qimageBehaviorForStackOverflowQuestion.cpp

qimageBehaviorForStackOverflowQuestion.h

#include <iostream>
#include <QApplication>
#include <QWidget>
#include <QTimer>
#include <QPainter>
#include <QPushButton>
#include <QImage>
#include <QTime>

class MyWidget : public QWidget {
  Q_OBJECT
 private:
  QImage *image;
  int px, py;
  uchar d[100*100*4];
  QTimer *timer;
  QTime time;
public:
  MyWidget();
  void paintEvent(QPaintEvent * event);
public slots:
  void doPaint();
};

qimageBehaviorForStackOverflowQuestion.cpp

#include "qimageBehaviorForStackOverflowQuestion.h"

int my_counter = 0;

MyWidget::MyWidget() : QWidget(0), px(0), py(0){
  image = new QImage(d, 100, 100, QImage::Format_ARGB32);
  for(int cnt = 0, a, r, g, b; cnt < 100*100*4;){
    a = 255; //alpha
    r = 0;   //red
    g = 0;   //green
    b = 0;   //blue

    d[cnt] = b; cnt++;
    d[cnt] = g; cnt++;
    d[cnt] = r; cnt++;
    d[cnt] = a; cnt++;
  }
  // connect QTimer.timeout to my doPaint method
  timer = new QTimer();
  connect(timer, SIGNAL(timeout()), this, SLOT(doPaint()));
  timer->start(1);
};

void MyWidget::doPaint(){
  // manipulate the positions of the points
  if(px < 100){
    int cnt = 0, b = 255, g = 255, r = 255, a = 255;
    d[4 * px + cnt] = b; cnt++;
    d[4 * px + cnt] = g; cnt++;
    d[4 * px + cnt] = r; cnt++;
    d[4 * px + cnt] = a; cnt++;
    px++;
  }
  // update the window
  update();
};

void MyWidget::paintEvent(QPaintEvent * event){
    QPainter painter(this);
    painter.drawImage(0, 0, *image);
}

int main(int argc, char *argv[]){
  QApplication app(argc, argv);
  MyWidget *widget = new MyWidget();
  widget->show();
  return app.exec();
}


问:
Maven run issue in spring tool suite for spring boot application
I am getting the below error on executing springboot:run in Spring tool suite for a spring boot application.

```<code>[INFO] BUILD FAILURE

[INFO] ------------------------------------------------------------------------

[INFO] Total time: 9.020 s
[INFO] Final Memory: 27M/262M

[INFO] ------------------------------------------------------------------------

[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.4.2.RELEASE:run (default-cli) on project documentupload-svc: Could not exec java: Application finished with exit code: 1 -> [Help 1]

[ERROR]

[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.

[ERROR] Re-run Maven using the -X switch to enable full debug logging.

[ERROR]

[ERROR] For more information about the errors and possible solutions, please read the following articles:

[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
</code>```

Please suggest how to resolve the issue in Spring tool suite.

答:
Assuming you're on a windows machine:

1) set JAVA_HOME environment variable to the folder where your java is.

2) set M2_HOME environment variable to the folder where maven is.

3) add %JAVA_HOME%/bin:%M2_HOME%/bin to the start of your PATH environment variable.

4) make sure your STS has a JDK set.

Body:
I am getting the below error on executing springboot:run in Spring tool suite for a spring boot application.

[INFO] BUILD FAILURE

[INFO] ------------------------------------------------------------------------

[INFO] Total time: 9.020 s
[INFO] Final Memory: 27M/262M

[INFO] ------------------------------------------------------------------------

[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.4.2.RELEASE:run (default-cli) on project documentupload-svc: Could not exec java: Application finished with exit code: 1 -> [Help 1]

[ERROR]

[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.

[ERROR] Re-run Maven using the -X switch to enable full debug logging.

[ERROR]

[ERROR] For more information about the errors and possible solutions, please read the following articles:

[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

Please suggest how to resolve the issue in Spring tool suite.


问:
Python.Selenium. Can't find existing element. How switch frame
I wand to get feedbacks from page
url = 'https://ru.aliexpress.com/store/product/Gillette-Fusion-blade-4-pc/2671035_1000003578539.html?spm=2114.12010612.0.0.xL0ySy'

I wait until page loaded. And I can find elements using Google Chrome inspector. But selenium can't find elements. And I alse can't find elements at the source page.

How can i get feedbacks using selenium or other instruments?

Here is my code:

```<code>from selenium import webdriver
import time
import csv
import requests

url = 'https://ru.aliexpress.com/store/product/Gillette-Fusion-blade-4-pc/2671035_1000003578539.html?spm=2114.12010612.0.0.xL0ySy'
driver = webdriver.Chrome()
driver.get(url)

try:
    close_popup = driver.find_element_by_class_name('close-layer')
    close_popup.click()
except:
    print("no alert")

tab_feedback = driver.find_element_by_xpath('//*[@id="j-product-tabbed-pane"]/ul/li[2]')
tab_feedback.click()
time.sleep(8)
try:
    text_feedback = driver.find_element_by_xpath('//*[@id="transction-feedback"]/div[4]/div[1]/div[2]/div[3]/dl')
    print(text_feedback.text)
except:
    print("cant find by xpath")

try:
    text_feedback = driver.find_element_by_class_name('buyer-feedback')
    print(text_feedback.text)
except:
    print("cant find by class_name")

try:
    text_feedback = driver.find_element_by_css_selector('div.f-content.dl.dt.span')
    print(text_feedback.text)
except:
    print("cant find by css_selector")
</code>```

it returns:

```<code>cant find by xpath
cant find by class_name
cant find by css_selector
</code>```

答:
You can try to add ExcplicitWait as below to wait for presence of required element:

```<code>from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as wait

text_feedback = wait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "buyer-feedback"))).text
</code>```

Also note that element located inside an iframe, so you should switch to it first before handling embedded elements:

```<code>driver.switch_to.frame(driver.find_element_by_xpath('//iframe[starts-with(@src, "//feedback.aliexpress.com/display/productEvaluation.htm")]'))
</code>```

To switch back from iframe:

```<code>driver.switch_to.default_content()
</code>```

As for your selectors:

You should avoid using XPath expressions like //*[@id="transction-feedback"]/div[4]/div[1]/div[2]/div[3]/dl, but use more verbose relative XPath, like //dl[@class="buyer-feedback"] instead

CSS selector div.f-content.dl.dt.span should match element
. Note that you should use space to point on descendant element (div dt) and ">" to point on direct child (div>dl). Your CSS selector might looks like div.f-content>dl>dt>span or div.f-content dt>span...

Body:
I wand to get feedbacks from page
url = 'https://ru.aliexpress.com/store/product/Gillette-Fusion-blade-4-pc/2671035_1000003578539.html?spm=2114.12010612.0.0.xL0ySy'

I wait until page loaded. And I can find elements using Google Chrome inspector. But selenium can't find elements. And I alse can't find elements at the source page.

How can i get feedbacks using selenium or other instruments?

Here is my code:

from selenium import webdriver
import time
import csv
import requests

url = 'https://ru.aliexpress.com/store/product/Gillette-Fusion-blade-4-pc/2671035_1000003578539.html?spm=2114.12010612.0.0.xL0ySy'
driver = webdriver.Chrome()
driver.get(url)

try:
    close_popup = driver.find_element_by_class_name('close-layer')
    close_popup.click()
except:
    print("no alert")

tab_feedback = driver.find_element_by_xpath('//*[@id="j-product-tabbed-pane"]/ul/li[2]')
tab_feedback.click()
time.sleep(8)
try:
    text_feedback = driver.find_element_by_xpath('//*[@id="transction-feedback"]/div[4]/div[1]/div[2]/div[3]/dl')
    print(text_feedback.text)
except:
    print("cant find by xpath")

try:
    text_feedback = driver.find_element_by_class_name('buyer-feedback')
    print(text_feedback.text)
except:
    print("cant find by class_name")

try:
    text_feedback = driver.find_element_by_css_selector('div.f-content.dl.dt.span')
    print(text_feedback.text)
except:
    print("cant find by css_selector")

it returns:

cant find by xpath
cant find by class_name
cant find by css_selector

Body:
You can try to add ExcplicitWait as below to wait for presence of required element:

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as wait

text_feedback = wait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "buyer-feedback"))).text

Also note that element located inside an iframe, so you should switch to it first before handling embedded elements:

driver.switch_to.frame(driver.find_element_by_xpath('//iframe[starts-with(@src, "//feedback.aliexpress.com/display/productEvaluation.htm")]'))

To switch back from iframe:

driver.switch_to.default_content()

As for your selectors:

You should avoid using XPath expressions like //*[@id="transction-feedback"]/div[4]/div[1]/div[2]/div[3]/dl, but use more verbose relative XPath, like //dl[@class="buyer-feedback"] instead

CSS selector div.f-content.dl.dt.span should match element <div class="f-content dl dt span">. Note that you should use space to point on descendant element (div dt) and ">" to point on direct child (div>dl). Your CSS selector might looks like div.f-content>dl>dt>span or div.f-content dt>span...


问:
Button inside Nested Repeater
Please help me to fire the command of ItemCommand for child Repeater.

Here is my aspx code.

```<code><asp:Repeater ID="rpCompany" runat="server">
    <HeaderTemplate>
        <div id="accordion" class="details-accordion">
    </HeaderTemplate>
    <ItemTemplate>
        <h3 class="details-header clr">
            Company Name
        </h3>
        <div class="col-sm-12 details-content">
            <asp:Repeater ID="rpSO" runat="server">
                <HeaderTemplate>
                    <div id="SO">
                        <div id="accordion2" class="details-accordion">
                </HeaderTemplate>
                <ItemTemplate>
                    <h3 class="details-header clr">
                        SO Number
                    </h3>
                    <div class="col-xs-12 details-content">
                        <div class="col-xs-12 btn-center">
                            <asp:Button ID="btnSave" runat="server" Text="SAVE" CssClass="btn btn-primary btn-blue-save" CommandName="SAVE" />
                        </div>
                        <div class="clr"></div>
                        <div class="col-xs-12">
                            <asp:Label ID="lblErrorSave" runat="server" Text=""></asp:Label>
                        </div>
                    </div>
                </ItemTemplate>
                <FooterTemplate>
                    </div>
                </div>
                </FooterTemplate>
            </asp:Repeater>
        </div>
    </ItemTemplate>
    <FooterTemplate>
        </div>
    </FooterTemplate>
</asp:Repeater>
</code>```

And my aspx.vb code is

```<code>Private Sub rpSO_ItemCommand(sender As Object, e As RepeaterCommandEventArgs)
    If e.CommandName = "SAVE" Then

    End If
End Sub
</code>```

But it's not firing.

I already added OnItemCommand on my child repeater but it gives me an error.

I also added AddHandler rptSO.ItemCommand, AddressOf rpSO_ItemCommand in the Parent Repeater but still no luck.

Thanks in advance for the help.

答:
Just adding a CommandName to a button will not make things happen in code behind spontaneously. You need to add a OnCommand to the Button or an OnItemCommand to the Repeater.

```<code><asp:Button ID="btnSave" runat="server" OnCommand="btnSave_Command" Text="SAVE" CommandName="SAVE" />

Protected Sub btnSave_Command(ByVal sender As Object, ByVal e As CommandEventArgs)
    //code
End Sub

<asp:Repeater ID="rpSO" runat="server" OnItemCommand="rpSO_ItemCommand">

Protected Sub rpSO_ItemCommand(ByVal source As Object, ByVal e As RepeaterCommandEventArgs)
    //code
End Sub
</code>```

Title: Button inside Nested Repeater

Body:
Please help me to fire the command of ItemCommand for child Repeater.

Here is my aspx code.

<asp:Repeater ID="rpCompany" runat="server">
    <HeaderTemplate>

    </HeaderTemplate>
    <ItemTemplate>

            Company Name

            <asp:Repeater ID="rpSO" runat="server">
                <HeaderTemplate>

                </HeaderTemplate>
                <ItemTemplate>

                        SO Number

                            <asp:Button ID="btnSave" runat="server" Text="SAVE" CssClass="btn btn-primary btn-blue-save" CommandName="SAVE" />

                            <asp:Label ID="lblErrorSave" runat="server" Text=""></asp:Label>

                </ItemTemplate>
                <FooterTemplate>

                </FooterTemplate>
            </asp:Repeater>

    </ItemTemplate>
    <FooterTemplate>

    </FooterTemplate>
</asp:Repeater>

And my aspx.vb code is

Private Sub rpSO_ItemCommand(sender As Object, e As RepeaterCommandEventArgs)
    If e.CommandName = "SAVE" Then

    End If
End Sub

But it's not firing.

I already added OnItemCommand on my child repeater but it gives me an error.

I also added AddHandler rptSO.ItemCommand, AddressOf rpSO_ItemCommand in the Parent Repeater but still no luck.

Thanks in advance for the help.

Body:
Just adding a CommandName to a button will not make things happen in code behind spontaneously. You need to add a OnCommand to the Button or an OnItemCommand to the Repeater.

<asp:Button ID="btnSave" runat="server" OnCommand="btnSave_Command" Text="SAVE" CommandName="SAVE" />

Protected Sub btnSave_Command(ByVal sender As Object, ByVal e As CommandEventArgs)
    //code
End Sub

<asp:Repeater ID="rpSO" runat="server" OnItemCommand="rpSO_ItemCommand">

Protected Sub rpSO_ItemCommand(ByVal source As Object, ByVal e As RepeaterCommandEventArgs)
    //code
End Sub


问:
Read and Split(Parse) data in java
I am trying to split some simple data from a .txt file. I have found some useful structures on the internet but it was not enough to split the data the way I wanted. I get a string like this:

```<code>{X:0.8940594 Y:0.6853521 Z:1.470214}
</code>```

And I want to transform it to like this;

```<code>0.8940594
0.6853521
1.470214
</code>```

And then put them in a matrix in order X=[], Y=[], Z=[]; (the data is the coordinate of an object)

Here is my code:

```<code>BufferedReader in = null; {
        try {
            in = new BufferedReader(new FileReader("file.txt"));
            String read = null;
            while ((read = in.readLine()) != null) {
                String[] splited = read.split("\\s+");
                for (String part : splited) {
                    System.out.println(part);
                }
            }
        } catch (IOException e) {
            System.out.println("There was a problem: " + e);
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (Exception e) {
            }
        }
    }
</code>```

What do I need to add to my code to get the data the way I want?

Right now with this code I receive data like this:

```<code>{X:0.8940594
Y:0.6853521
Z:1.470214}
</code>```

答:
You can use this regex -?\d+\.\d+ for example :

```<code>String input = "{X:0.8940594 Y:0.6853521 Z:1.470214}";

Pattern pattern = Pattern.compile("-?\\d+\\.\\d+");
Matcher matcher = pattern.matcher(input);

List<String> result = new ArrayList<>();
while (matcher.find()) {
    result.add(matcher.group());
}
System.out.println(result);
</code>```

In your case you want to match the real number, you can check the Regex .

Title: Read and Split(Parse) data in java

Body:
I am trying to split some simple data from a .txt file. I have found some useful structures on the internet but it was not enough to split the data the way I wanted. I get a string like this:

{X:0.8940594 Y:0.6853521 Z:1.470214}

And I want to transform it to like this;

0.8940594
0.6853521
1.470214

And then put them in a matrix in order X=[], Y=[], Z=[]; (the data is the coordinate of an object)

Here is my code:

BufferedReader in = null; {
        try {
            in = new BufferedReader(new FileReader("file.txt"));
            String read = null;
            while ((read = in.readLine()) != null) {
                String[] splited = read.split("\\s+");
                for (String part : splited) {
                    System.out.println(part);
                }
            }
        } catch (IOException e) {
            System.out.println("There was a problem: " + e);
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (Exception e) {
            }
        }
    }

What do I need to add to my code to get the data the way I want?

Right now with this code I receive data like this:

{X:0.8940594
Y:0.6853521
Z:1.470214}

Body:
You can use this regex -?\d+\.\d+ for example :

String input = "{X:0.8940594 Y:0.6853521 Z:1.470214}";

Pattern pattern = Pattern.compile("-?\\d+\\.\\d+");
Matcher matcher = pattern.matcher(input);

List<String> result = new ArrayList<>();
while (matcher.find()) {
    result.add(matcher.group());
}
System.out.println(result);

In your case you want to match the real number, you can check the Regex .


问:
Django dropped table still exists
Having problems with a model in one of my django apps.

I can make an instance of the model, but when I go to access it, I get an error:

```<code># create and save model instance
user_form = UserSearchForm(user=user)
user_form.save()

# Then later
first_user_form = UserSearchForm.objects.all()[0]

(1146, "Table 'project.app_tablename' doesn't exist")
Request Method: GET
Request URL:    http://10.0.75.1:8000/search/
Django Version: 1.9.5
Exception Type: ProgrammingError
Exception Value:
(1146, "Table 'project.app_tablename' doesn't exist")
Exception Location: /opt/project-venv/lib/python3.4/site-packages/MySQLdb/connections.py in query, line 280
Python Executable:  /opt/project-venv/bin/python
Python Version: 3.4.3
Python Path:
['/opt/project/project',
 '/opt/project-venv/lib64/python34.zip',
 '/opt/project-venv/lib64/python3.4',
 '/opt/project-venv/lib64/python3.4/plat-linux',
 '/opt/project-venv/lib64/python3.4/lib-dynload',
 '/usr/lib64/python3.4',
 '/usr/lib/python3.4',
 '/opt/project-venv/lib/python3.4/site-packages']
Server time:    Tue, 28 Mar 2017 22:50:16 +0000
</code>```

I'm using Django 1.95 and I tried the following from the linked answer (https://stackoverflow.com/a/36565161/2516846):

Delete app migrations folder

Drop all app tables, e.g. DROP TABLE search_usersearchform

Delete all migrations from db: DELETE FROM django_migrations WHERE app = 'search'.

python manage.py makemigrations search

python manage.py migrate

But when I run migrate, it gives error:

```<code>django.db.utils.ProgrammingError: relation "search_usersearchform" already exists
</code>```

Summary: Cannot create model again as relation already exists, yet cannot access model in my app as it says table doesn't exist

Is there a reference to this table/model stored else where which I need to remove? I don't know how the relation can already exist if I dropped the table, deleted migrations folder and removed migrations from db

EDIT

Okay finally got this sorted.

My project had two databases, the 'default' db, using postgres, and the 'secondary' db, using mysql.

When I created a new model in my app, and ran the migration, the table was added to the default db.

This allowed me to create an instance of the new model.

However when I went to access a previously saved instance, I got the error saying the table does not exist.

Turns out it was caused by my apps router.py, which redirected any queries to the 'secondary' db, which of course did not have the table.

To fix this, I added conditionals to the db_for_write and db_for_read methods in  router.py, to route those models to the 'default' db.

答: Try deleting or changing migration files that have that model in them, care with the dependencies. Then run again python manage.py makemigrations and python manage.py migrate it should create the model again. (We are talking about your test DB right?)

Title: Django dropped table still exists

Body:
Having problems with a model in one of my django apps.

I can make an instance of the model, but when I go to access it, I get an error:

# create and save model instance
user_form = UserSearchForm(user=user)
user_form.save()

# Then later
first_user_form = UserSearchForm.objects.all()[0]

(1146, "Table 'project.app_tablename' doesn't exist")
Request Method: GET
Request URL:    http://10.0.75.1:8000/search/
Django Version: 1.9.5
Exception Type: ProgrammingError
Exception Value:
(1146, "Table 'project.app_tablename' doesn't exist")
Exception Location: /opt/project-venv/lib/python3.4/site-packages/MySQLdb/connections.py in query, line 280
Python Executable:  /opt/project-venv/bin/python
Python Version: 3.4.3
Python Path:
['/opt/project/project',
 '/opt/project-venv/lib64/python34.zip',
 '/opt/project-venv/lib64/python3.4',
 '/opt/project-venv/lib64/python3.4/plat-linux',
 '/opt/project-venv/lib64/python3.4/lib-dynload',
 '/usr/lib64/python3.4',
 '/usr/lib/python3.4',
 '/opt/project-venv/lib/python3.4/site-packages']
Server time:    Tue, 28 Mar 2017 22:50:16 +0000

I'm using Django 1.95 and I tried the following from the linked answer (https://stackoverflow.com/a/36565161/2516846):

Delete app migrations folder

Drop all app tables, e.g. DROP TABLE search_usersearchform

Delete all migrations from db: DELETE FROM django_migrations WHERE app = 'search'.

python manage.py makemigrations search

python manage.py migrate

But when I run migrate, it gives error:

django.db.utils.ProgrammingError: relation "search_usersearchform" already exists

Summary: Cannot create model again as relation already exists, yet cannot access model in my app as it says table doesn't exist

Is there a reference to this table/model stored else where which I need to remove? I don't know how the relation can already exist if I dropped the table, deleted migrations folder and removed migrations from db

EDIT

Okay finally got this sorted.

My project had two databases, the 'default' db, using postgres, and the 'secondary' db, using mysql.

When I created a new model in my app, and ran the migration, the table was added to the default db.

This allowed me to create an instance of the new model.

However when I went to access a previously saved instance, I got the error saying the table does not exist.

Turns out it was caused by my apps router.py, which redirected any queries to the 'secondary' db, which of course did not have the table.

To fix this, I added conditionals to the db_for_write and db_for_read methods in  router.py, to route those models to the 'default' db.


问:
Specify ClientCertEnabled for a virtual application
For an Azure Web App, the only setting available for client certificates is "ClientCertEnabled". The problem is that it requires the certificate for the whole site. I can't find another way. I thought about creating a virtual App under the site, is it possible to enable this setting for a virtual App inside Azure? Any config in the ARM Template?

答:
According to your description, I followed this official tutorial about enable client certificate authentication when the request is over TLS/SSL for your Azure Web App.

Note:

If you access your site over HTTP and not HTTPS, you will not receive any client certificate. So if your application requires client certificates you should not allow requests to your application over HTTP.

The client certificate that is sent to the application does not go through any validation by the Azure Web Apps platform. Validating this certificate is the responsibility of the web app.

The problem is that it requires the certificate for the whole site. I can't find another way. I thought about creating a virtual App under the site, is it possible to enable this setting for a virtual App inside Azure?

I followed this official blog for deploying a virtual directory to a single Azure Website to test this scenario, and found it did not work at all.

I also followed this issue to configure SSL Settings in my config file and followed this official tutorial for remoting to my Azure Website via IIS Manager to change some settings, in order to achieve this purpose instead of using ClientCertEnabled. But all the above trials could not work at all, I assumed that you need to create a new web app which is used to handle requests based on client certificate authentication.

Additionally, here are some useful tutorials you could refer to them:

Web API with client certificate

Code sample AzureWebApiClientCertAuthSample

Azure App Service and Client Certificate Authentication


问:
Facebook JS SDK - restoring FB session
I'm working on a site which allows users to link their "native" accounts with their FB accounts - this is accomplished by using FB JS API which plants FB cookie in the browser, which cookie is then parsed by my code etc.

Now, when user logs out of the site (FB session is then closed with FB.logout(); call) and logs in again using his credentials (and not using FB Connect), I would like to restore FB session automatically (without showing FB popup), if possible, to allow posting comments to FB wall.

I'm aware that I could post comments from the backend, using OAuth access_token I have, but I'd like to do it with JS SDK. With the backend version things are relatively simple, but I cannot wrap my head around client-side solution - e.g. how to handle situation in which some other user is logged into FB, and the FB session of returning user of my site clashes with the existing FB session of that other user.

Can anyone advise me something on this ?

答:
Rather than instigating a Facebook session each time the user logs in, you could change your extended permissions scope to include offline_access. This would give you an access token that is long lived and allows you to perform authorised requests on behalf of the user at any time.

It will only require them to authorise your application once, which presumably will be when the "link" their account.

There is some information on extended permissions here for you to reference:

http://developers.facebook.com/docs/authentication/permissions

Title: Facebook JS SDK - restoring FB session


问:
Align Buttons Side by Side Bootstrap
I am trying to align my two bootstrap buttons side by side (horizontally), right now they are aligned one on top of another (vertically). I have found a few questions on here, but still can't seem to get it right...

I will post my code below:

```<code><div class="row">
    <div class="col-sm-12">
         <asp:Button ID="btnSearch" runat="server" Text="Search" CssClass="btn btn-primary btn-md center-block" Style="width: 100px; margin-bottom: 10px;" OnClick="btnSearch_Click" />
         <asp:Button ID="btnClear" runat="server" Text="Clear" CssClass="btn btn-danger btn-md center-block" Style="width: 100px;" OnClick="btnClear_Click" />
     </div>
</div>
</code>```

答:
You can use an out div with a class btn-group. This helps to align the buttons horizontally. Using col-md-6 for each button div can make the buttons missaligned with unwanted space in between.

```<code><div class="btn-group">
<a href="#" class="btn btn-warning">Talent-signup to find jobs</a>
<a href="#" class="btn btn-success">Talent-signup to find jobs</a>
</div>
</code>```

Title: Align Buttons Side by Side Bootstrap

Body:
I am trying to align my two bootstrap buttons side by side (horizontally), right now they are aligned one on top of another (vertically). I have found a few questions on here, but still can't seem to get it right...

I will post my code below:

         <asp:Button ID="btnSearch" runat="server" Text="Search" CssClass="btn btn-primary btn-md center-block" Style="width: 100px; margin-bottom: 10px;" OnClick="btnSearch_Click" />
         <asp:Button ID="btnClear" runat="server" Text="Clear" CssClass="btn btn-danger btn-md center-block" Style="width: 100px;" OnClick="btnClear_Click" />

Body:
You can use an out div with a class btn-group. This helps to align the buttons horizontally. Using col-md-6 for each button div can make the buttons missaligned with unwanted space in between.

<div class="btn-group">
<a href="#" class="btn btn-warning">Talent-signup to find jobs</a>
<a href="#" class="btn btn-success">Talent-signup to find jobs</a>
</div>