问:
How to load Spring Boot Application Context while using Cucumber at runtime, not via tests?
I am working on a Spring Boot application using 1.5.8.RELEASE, which is configured and run via CLI. The parameters are used to configure the application to run in one or more different ways. One of the commands is to run all cucumber features and is called by using:

```<code>cucumber.api.cli.Main.main(cucumberArguments);
</code>```

The current arguments passed include: featureFolder, -g, stepsPackage, and a couple of cucumber-report configuration parameters.

I would like to be able to configure a few properties in my CucumberSteps*.java files via my application.properties file, or via profile-specific application.properties files, but the way I am running the features at the moment means that the Spring Boot context is not loaded.

My first attempt was:

```<code>@ConfigurationProperties
public class CucumberStepsFeature1 {

    @Value("${my.property}")
    private String myProperty;

    @Given("...")
    public void given() {
        // fails below
        assertNotNull(this.myProperty);
    }
}
</code>```

My second attempt at working around this issue was:

```<code>@ContextConfiguration(classes = MyMainApp.class)
@ConfigurationProperties
public class CucumberStepsFeature1 {

    @Value("${my.property}")
    private String myProperty;

    @Given("...")
    public void given() {
        // fails below
        assertNotNull(this.myProperty);
    }
}
</code>```

but I get an error message of

```<code>Caused by: javax.management.InstanceAlreadyExistsException: org.springframework.boot:type=Admin,name=SpringApplication
</code>```

I tried following the steps listed here, but to no avail.

I'd appreciate any attempts to help, but I'll note now that due to company policy, what I share here will be very limited. I won't be able to copy or paste any real code snippets or logs.

答:
Below is the cleanest way I could find to accomplish what I wanted:

Create a Config class to load in the Spring application properties that you need (application.properties and/or application-${PROFILE}.properties), such as below:

```<code>import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties
public class PropsConfig {

    @Value("${my.property}")
    private String myProperty;

    //any other properties...

    public String getMyProperty() {
        return this.myProperty;
    }
</code>```

Create another class to act as a container for the Spring ApplicationContext. Make sure that this class is scanned by Spring by putting it in a subpackage of your main application class. See code below:

```<code>import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SpringApplicationContextContainer implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Autowired
    public SpringApplicationContextContainer(ApplicationContext applicationContext) {
        SpringApplicationContextContainer.applicationContext = applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringApplicationContextContainer.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return SpringApplicationContextContainer.applicationContext;
    }
}
</code>```

Finally, in your CucumberSteps class, or in any other non-Spring class, you can simply make a call to SpringApplicationContextContainer.getApplicationContext(); as below:

```<code>public class CucumberStepsFeature1 {

    private final PropsConfig propsConfig;

    public CucumberStepsFeature1() {
        this.propsConfig = SpringApplicationContextContainer.getApplicationContext().getBean(PropsConfig.class);
    }

    @Given("...")
    public void given() {
        // passes below
        assertNotNull(this.propsConfig);
    }
</code>```

Body:
I am working on a Spring Boot application using 1.5.8.RELEASE, which is configured and run via CLI. The parameters are used to configure the application to run in one or more different ways. One of the commands is to run all cucumber features and is called by using:

cucumber.api.cli.Main.main(cucumberArguments);

The current arguments passed include: featureFolder, -g, stepsPackage, and a couple of cucumber-report configuration parameters.

I would like to be able to configure a few properties in my CucumberSteps*.java files via my application.properties file, or via profile-specific application.properties files, but the way I am running the features at the moment means that the Spring Boot context is not loaded.

My first attempt was:

@ConfigurationProperties
public class CucumberStepsFeature1 {

    @Value("${my.property}")
    private String myProperty;

    @Given("...")
    public void given() {
        // fails below
        assertNotNull(this.myProperty);
    }
}

My second attempt at working around this issue was:

@ContextConfiguration(classes = MyMainApp.class)
@ConfigurationProperties
public class CucumberStepsFeature1 {

    @Value("${my.property}")
    private String myProperty;

    @Given("...")
    public void given() {
        // fails below
        assertNotNull(this.myProperty);
    }
}

but I get an error message of

Caused by: javax.management.InstanceAlreadyExistsException: org.springframework.boot:type=Admin,name=SpringApplication

I tried following the steps listed here, but to no avail.

I'd appreciate any attempts to help, but I'll note now that due to company policy, what I share here will be very limited. I won't be able to copy or paste any real code snippets or logs.

Body:
Below is the cleanest way I could find to accomplish what I wanted:

Create a Config class to load in the Spring application properties that you need (application.properties and/or application-${PROFILE}.properties), such as below:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties
public class PropsConfig {

    @Value("${my.property}")
    private String myProperty;

    //any other properties...

    public String getMyProperty() {
        return this.myProperty;
    }

Create another class to act as a container for the Spring ApplicationContext. Make sure that this class is scanned by Spring by putting it in a subpackage of your main application class. See code below:

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SpringApplicationContextContainer implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Autowired
    public SpringApplicationContextContainer(ApplicationContext applicationContext) {
        SpringApplicationContextContainer.applicationContext = applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringApplicationContextContainer.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return SpringApplicationContextContainer.applicationContext;
    }
}

Finally, in your CucumberSteps class, or in any other non-Spring class, you can simply make a call to SpringApplicationContextContainer.getApplicationContext(); as below:

public class CucumberStepsFeature1 {

    private final PropsConfig propsConfig;

    public CucumberStepsFeature1() {
        this.propsConfig = SpringApplicationContextContainer.getApplicationContext().getBean(PropsConfig.class);
    }

    @Given("...")
    public void given() {
        // passes below
        assertNotNull(this.propsConfig);
    }


来源: stackexchange

问:
Swift 4: Dismiss closure code not executing
First let me say ive tried just about everything out there to fix this problem and I cant for the life of me figure it out.

The code:

```<code> self.messagesControl?.showChatController()
</code>```

is not running , it is inside a dismiss() closure why is that the print line following this runs , and not the line of code above? please help!

messagesControl method call

```<code> var messagesControl : MessagesViewController?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        self.dismiss(animated: true, completion: {
            self.messagesControl?.showChatController()
            print("dismiss closure finished running")
        })

}
</code>```

showChatController()

```<code> func showChatController()
{
    performSegue(withIdentifier: "goToChatLogControllerPlz", sender: self)
}
</code>```

Expected Result:
segue is run print line executes

Observed Result:

print line executes. no segue :(

EDIT

i have replaced :

```<code>self.messagesControl?.showChatController()
</code>```

With:

```<code>      self.performSegue(withIdentifier: "showChatController", sender: self)
</code>```

Still getting same result tho :(

答:
The way apple does dismiss is wierd.  You can call it on the presented VC or on the presenter.  Which are you doing here?  If you are calling it on the presented view controller then it leaves memory after dismiss, and in any case it shouldn't be showing the next view controller; the parent should.

There are three ways you can deal with this:

Use an unwind segue.  When the parent gets the unwind it will call
dismiss and perform the segue in the compeletion handler as you have
it now.

Use a delegate and tell the parent when the modal showu;d be dismissed.  the parent then calls dismiss and initiates the segue.

Before dismiss reach up the UIResponder chain to find your parent VC.  In the completetion for dismiss call performSegue on your parent VC.

Method 1 is preferred if only the final state of the modal is relavant (ie you don't need a delegate for anything else).  Method 2 is preferred if you are already using a delegate for something else.  Method 3 is the least code but is generally poor style unless your parent VC conforms to some standard protocol that you can invoke.

ContentLicense: CC BY-SA 3.0

Body:
First let me say ive tried just about everything out there to fix this problem and I cant for the life of me figure it out.

The code:

 self.messagesControl?.showChatController()

is not running , it is inside a dismiss() closure why is that the print line following this runs , and not the line of code above? please help!

messagesControl method call

 var messagesControl : MessagesViewController?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        self.dismiss(animated: true, completion: {
            self.messagesControl?.showChatController()
            print("dismiss closure finished running")
        })

}

showChatController()

 func showChatController()
{
    performSegue(withIdentifier: "goToChatLogControllerPlz", sender: self)
}

Expected Result:
segue is run print line executes

Observed Result:

print line executes. no segue :(

EDIT

i have replaced :

self.messagesControl?.showChatController()

With:

      self.performSegue(withIdentifier: "showChatController", sender: self)

Still getting same result tho :(


问:
Remove file extension in apache 2.4
I want to refer to a page without the .php extension and not to use the .htaccess file, as a documentation says:

You should avoid using .htaccess files completely if you have access
  to httpd main server config file. Using .htaccess files slows down your Apache http server.

答: You can write the configuration you want (a "rewrite rule" in your case I think) in the virtual host of your website to avoid the .htaccess. See the doc here https://httpd.apache.org/docs/2.4/en/vhosts/examples.html</p>

Title: Remove file extension in apache 2.4


问:
PHP how to find the duplicates
I am using php and I want to display list of records from database.
Say for example, the following is the table structure

```<code>sno val1 val2 val3  amt
1    2c   3e   I    500
2    2b   i7   I    1500
3    2w   u9   I    0
4    18   e3   I    50
5    2c   3e   S    70
</code>```

Now I want to display records like below,

```<code>sno val1  val2  value
1    2c    3e    1
2    2b    i7    1
3    2w    u9    1
4    18    e3    1
5    2c    3e    0 //because already listed
</code>```

I'm using normal while loop to show this structure, but I don't know weather the value is already listed or not..

Can anyone help

答:
You can try:</p>

```<code>SELECT a.sno, a.val1, a.val2,
       CASE WHEN COUNT(*) > 1 THEN 0 ELSE 1 END value
FROM table_name a
JOIN table_name b
ON a.val1 = b.val1
   AND a.val2 = b.val2
   AND a.sno >= b.sno
GROUP BY a.sno
</code>```

Title: PHP how to find the duplicates

Body:
I am using php and I want to display list of records from database.
Say for example, the following is the table structure

sno val1 val2 val3  amt
1    2c   3e   I    500
2    2b   i7   I    1500
3    2w   u9   I    0
4    18   e3   I    50
5    2c   3e   S    70

Now I want to display records like below,

sno val1  val2  value
1    2c    3e    1
2    2b    i7    1
3    2w    u9    1
4    18    e3    1
5    2c    3e    0 //because already listed

I'm using normal while loop to show this structure, but I don't know weather the value is already listed or not..

Can anyone help

Body:
You can try:

SELECT a.sno, a.val1, a.val2,
       CASE WHEN COUNT(*) > 1 THEN 0 ELSE 1 END value
FROM table_name a
JOIN table_name b
ON a.val1 = b.val1
   AND a.val2 = b.val2
   AND a.sno >= b.sno
GROUP BY a.sno


问:
array_replace_recursive with custom function like Lodash mergeWith
I need a function to do same as array_replace_recursive but new created value stay an empty string.

```<code>JSON 1
{
    "test1":"test1",
    "test2":"test2"
}

JSON 2 before
{
    "test1":"test1"
}

JSON 2 after
{
    "test1":"test1",
    "test2" : ""
}
</code>```

Do you have any idea ?

I'm testing with a personnal recursive function, to be continued ^^

(like https://lodash.com/docs/#mergeWith)

Thank you in advance.

答:
```<code><?php

$a = [
    'foo' =>
    [
        'bar' => 'Stool',
        'bat' => 'Cricket'
    ]
];

$b = [
    'foo' =>
    [
        'bar' => 'Tat'
    ],
    'qux' =>
    [
        'quux' => 'Cross'
    ]
];

array_walk_recursive($b,
    function(&$v) {
        $v = "";
    }
);
$c = array_replace_recursive($a, $b);

var_export($c);
</code>```

Output:

```<code>array (
    'foo' =>
    array (
    'bar' => '',
    'bat' => 'Cricket',
    ),
    'qux' =>
    array (
    'quux' => '',
    ),
)
</code>```

Body:
I need a function to do same as array_replace_recursive but new created value stay an empty string.

JSON 1
{
    "test1":"test1",
    "test2":"test2"
}

JSON 2 before
{
    "test1":"test1"
}

JSON 2 after
{
    "test1":"test1",
    "test2" : ""
}

Do you have any idea ?

I'm testing with a personnal recursive function, to be continued ^^

(like https://lodash.com/docs/#mergeWith)

Thank you in advance.

Body:
<?php

$a = [
    'foo' =>
    [
        'bar' => 'Stool',
        'bat' => 'Cricket'
    ]
];

$b = [
    'foo' =>
    [
        'bar' => 'Tat'
    ],
    'qux' =>
    [
        'quux' => 'Cross'
    ]
];

array_walk_recursive($b,
    function(&$v) {
        $v = "";
    }
);
$c = array_replace_recursive($a, $b);

var_export($c);

Output:

array (
    'foo' =>
    array (
    'bar' => '',
    'bat' => 'Cricket',
    ),
    'qux' =>
    array (
    'quux' => '',
    ),
)


问:
ruby savon and wsdl namespacing
I have an issue that I believe is in regards to namespaces. The WSDL can be downloaded from here: http://promostandards.org/content/wsdl/Order%20Shipment%20NotificationService/1.0.0/OSN-1-0-0.zip

When the request is generated it looks like this:

```<code><soapenv:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tns="http://www.promostandards.org/WSDL/OrderShipmentNotificationService/1.0.0/" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<tns:GetOrderShipmentNotificationRequest>
  <tns:wsVersion>1.0.0</tns:wsVersion>
  <tns:id>myusername</tns:id>
  <tns:password>mypassword</tns:password>
  <tns:queryType>3</tns:queryType>
  <tns:shipmentDateTimeStamp>2017-07-19</tns:shipmentDateTimeStamp>
</tns:GetOrderShipmentNotificationRequest>
</soapenv:Body>
</soapenv:Envelope>
</code>```

This results in a soap fault.

When SoapUI constructs the request using the same WSDL it looks like this

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://www.promostandards.org/WSDL/OrderShipmentNotificationService/1.0.0/" xmlns:shar="http://www.promostandards.org/WSDL/OrderShipmentNotificationService/1.0.0/SharedObjects/">
<soapenv:Header/>
<soapenv:Body>
  <ns:GetOrderShipmentNotificationRequest>
     <shar:wsVersion>1.0.0</shar:wsVersion>
     <shar:id>myusername</shar:id>
     <shar:password>mypassword</shar:password>
     <ns:queryType>3</ns:queryType>
     <ns:shipmentDateTimeStamp>2017-07-19</ns:shipmentDateTimeStamp>
  </ns:GetOrderShipmentNotificationRequest>
</soapenv:Body>
</soapenv:Envelope>
</code>```

You can see that SoapUI has placed the username and password inside the "shar" namespace. I noticed that this is not directly listed in the WSDL or in any XSD file directly loaded by the WSDL. It gets loaded something like WSDL => XSD file => XSD file containing shar namespace. could that be the issue? How can I add the namespace to just 3 of the keys? I'm using savon 2.11.1 and nori 2.6.0

Here is the solution I ended up using:

```<code>@client = Savon.client(
    wsdl: 'OSN-1-0-0/WSDL/1.0.0/OrderShipmentNotificationService.wsdl',
    endpoint: @endpoint,
    env_namespace: :soapenv,
    namespaces: { "xmlns:shar" => "http://www.promostandards.org/WSDL/OrderShipmentNotificationService/1.0.0/SharedObjects/" },
    element_form_default: :qualified,
    headers: { "accept-encoding" => "identity" }
)

response = @client.call(:get_order_shipment_notification, message: {
    'shar:ws_version': @version,
    'shar:id': @username,
    'shar:password': @password,
    query_type: 3,
    shipment_date_time_stamp: date
})
</code>```

答:
I think Savon doesn't interpret linked XSD files, which are used here to reference the SharedObject. Had a similar problem and the only solution I found was to manually write the definition of the namespaces.

In your case it might look something like this:

```<code>client = Savon.client do
  endpoint "http://localhost/OrderShipmentNotificationService.svc"
  element_form_default :qualified
  namespace "http://www.promostandards.org/WSDL/OrderShipmentNotificationService/1.0.0/"
  namespace_identifier :ns
  namespaces "xmlns:shar"=>"http://www.promostandards.org/WSDL/OrderShipmentNotificationService/1.0.0/SharedObjects/"
end

response = client.call("GetOrderShipmentNotificationRequest") do |locals|
  locals.message "shar:wsVersion"=>"1.0.0","shar:id"=>"myusername",...
end
</code>```

ContentLicense: CC BY-SA 4.0

Title: ruby savon and wsdl namespacing

Body:
I have an issue that I believe is in regards to namespaces. The WSDL can be downloaded from here: http://promostandards.org/content/wsdl/Order%20Shipment%20NotificationService/1.0.0/OSN-1-0-0.zip

When the request is generated it looks like this:

<soapenv:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tns="http://www.promostandards.org/WSDL/OrderShipmentNotificationService/1.0.0/" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<tns:GetOrderShipmentNotificationRequest>
  <tns:wsVersion>1.0.0</tns:wsVersion>
  <tns:id>myusername</tns:id>
  <tns:password>mypassword</tns:password>
  <tns:queryType>3</tns:queryType>
  <tns:shipmentDateTimeStamp>2017-07-19</tns:shipmentDateTimeStamp>
</tns:GetOrderShipmentNotificationRequest>
</soapenv:Body>
</soapenv:Envelope>

This results in a soap fault.

When SoapUI constructs the request using the same WSDL it looks like this

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://www.promostandards.org/WSDL/OrderShipmentNotificationService/1.0.0/" xmlns:shar="http://www.promostandards.org/WSDL/OrderShipmentNotificationService/1.0.0/SharedObjects/">
<soapenv:Header/>
<soapenv:Body>
  <ns:GetOrderShipmentNotificationRequest>
     <shar:wsVersion>1.0.0</shar:wsVersion>
     <shar:id>myusername</shar:id>
     <shar:password>mypassword</shar:password>
     <ns:queryType>3</ns:queryType>
     <ns:shipmentDateTimeStamp>2017-07-19</ns:shipmentDateTimeStamp>
  </ns:GetOrderShipmentNotificationRequest>
</soapenv:Body>
</soapenv:Envelope>

You can see that SoapUI has placed the username and password inside the "shar" namespace. I noticed that this is not directly listed in the WSDL or in any XSD file directly loaded by the WSDL. It gets loaded something like WSDL => XSD file => XSD file containing shar namespace. could that be the issue? How can I add the namespace to just 3 of the keys? I'm using savon 2.11.1 and nori 2.6.0

Here is the solution I ended up using:

@client = Savon.client(
    wsdl: 'OSN-1-0-0/WSDL/1.0.0/OrderShipmentNotificationService.wsdl',
    endpoint: @endpoint,
    env_namespace: :soapenv,
    namespaces: { "xmlns:shar" => "http://www.promostandards.org/WSDL/OrderShipmentNotificationService/1.0.0/SharedObjects/" },
    element_form_default: :qualified,
    headers: { "accept-encoding" => "identity" }
)

response = @client.call(:get_order_shipment_notification, message: {
    'shar:ws_version': @version,
    'shar:id': @username,
    'shar:password': @password,
    query_type: 3,
    shipment_date_time_stamp: date
})

Body:
I think Savon doesn't interpret linked XSD files, which are used here to reference the SharedObject. Had a similar problem and the only solution I found was to manually write the definition of the namespaces.

In your case it might look something like this:

client = Savon.client do
  endpoint "http://localhost/OrderShipmentNotificationService.svc"
  element_form_default :qualified
  namespace "http://www.promostandards.org/WSDL/OrderShipmentNotificationService/1.0.0/"
  namespace_identifier :ns
  namespaces "xmlns:shar"=>"http://www.promostandards.org/WSDL/OrderShipmentNotificationService/1.0.0/SharedObjects/"
end

response = client.call("GetOrderShipmentNotificationRequest") do |locals|
  locals.message "shar:wsVersion"=>"1.0.0","shar:id"=>"myusername",...
end


问:
entity framework does not map more than one list in model C#
I have a class "Project" that hat two lists one for "Employee" and one for "tool", when i build my project with only one of the lists the database updates with corrrect relation, if add the second list to the class entity framework can not figureout how to create the relation.

```<code> public class Project
{
    public Guid Id { get; set; }
    public List<Employee> RequiredEmployees {get;set;}
    public List<Tools> RequiredTools {get;set;}
}

Public class Tool
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public Project Project { get; set; }
    public Guid ProjectId { get; set; }
}
</code>```

I get the error "There are no primary or candidate keys in the referenced table"
i hve tryed to map in ModelBuilder without success

```<code> modelBuilder.Entity<Employee>()
    .HasRequired<Project>(s => s.Project)
    .WithMany(g => g.Employee)
    .HasForeignKey<Guid>(s => s.ProjectId);
</code>```

any ideas ?

答:
You have maneuvered yourself in several problems. The reported error is about the primary key. Furthermore you have problems specifying the one-to-many relations.

One-To-Many relations

Entity framework is easy if you follow the code first conventions For every deviation you need to tell entity framework about your deviations.

You planned to design a one-to-many between a Project and Tool: every Project has zero or more Tools, every Tool belongs to exactly one Project

If you follow the convention for one-to-many, you don't have to inform entity framework about this relation; entity framework will detect the relation by convention:

Use an ICollection instead of a List, after all, what would RequiredTools[4] mean?

Make the ICollection virtual. As long as your Project is a query, it is not a real ICollection, it only contains a class that can produce an ICollection.

Consider using the proper naming conventions.:

```<code>class Project
{
    public Guid Id { get; set; }
    // a project has zero or more Employees:
    public virtual ICollection<Employee> Employees {get;set;}
    // a project has zero or more Tools
    public virtual ICollectioin<Tool> Tools {get;set;}
}
</code>```

Every Tool belongs to exactly one Project, using foreign key:

```<code>class Tool
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public Guid ProjectId {get; set;}
    public virtual Project Project { get; set; }
}
</code>```

Similarly: Every Employee belongs to one Project

```<code>class Employee
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public Guid ProjectId {get; set;}
    public virtual Project Project { get; set; }
}
</code>```

Or use many-to-many if an Employee can participate in several Projects:

```<code>class Employee
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    // an Employee works in zero or more Projects
    public virtual ICollection<Project> Projects { get; set; }
}
</code>```

And your Dbcontext:

```<code>class MyDbContext : DbContext
{
    public DbSet<Employee> Employees {get; set;}
    public DbSet<Project> Projects {get; set;}
    public DbSet<Tool> Tools {get; set;}
}
</code>```

This would be enough for entity framework to detect your relations and table names. I'd advice you to reconsider your decision to deviate from the code-first conventions.

However, if you really need to deviate your names you'll have to tell entity framework about your relations and table names:

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    // a Project has zero or more Tools via property RequiredTools and table TableName:
    var entityProject = modelBuilder.Entity<Project>();
    entityProject.ToTable(... /* table name */);
    // a project has zero or more tools via property RequiredTools
    // every tool belongs to one required Project
    // using foreign key ProjectId
    entityproject.HasMany(project => project.RequiredTools)
        .WithRequired(tool => tool.Project)
        .HasFreignKey(tool => tool.ProjectId);
}
</code>```

Primary Keys

You chose not to use the conventional type for your primary Keys. The problem is that entity framework does not know how to fill your Id. You'll have to tell entity framework that you'll fill the values for the primary keys.

This is done by overriding DbContext.SaveChanges

There are also two SaveChangesAsync; we will override them to. Both procedures will call the same function that will generate your Id:

```<code>public override int SaveChanges()
{
    GenerateIds();
    return base.SaveChanges();
}
public override Task<int> SaveChangesAsync()
{
    GenerateIds();
    return base.SaveChangesAsync();
}
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken)
    {
        this.GenerateIds();
        return base.SaveChangesAsync(cancellationToken);
    }
</code>```

Function GenerateIds will get all items that need an Id and give it an Id. The objects that need an Id are all objects with state Added.

However, the object in the DbContext that remembered all changes that need to be saved, only knows that these objects are DbEntityEntries. It does not know which property in your DbEntityEntry represents the primary key.

You could solve this using KeyAttribute. Get the added entry, ask for its type, ask the type for the property that has the KeyAttribute and set the value of this property.

This method has several disadvantages. Reflection is a fairly slow process, it depends on you giving all classes that need a GUID to add the KeyAttribute, it is not type safe, and you will only detect that your made mistakes at run-time.

It is much better to define that all your entity classes should implement an interface that defines the primary key:

```<code>public interface IPrimaryKey
{
     GUID Id {get; set;}
}

class Tool : IPrimaryKey {...}
class Project : IPrimaryKey {...}
</code>```

If you forgot to implement your Id, your compiler will warn you. GenerateIds is now fairly simple:

```<code>private void GenerateIds()
{
    foreach (DbEntityEntry addedEntry in this.ChangeTracker.Entries()
       .Where(entry => entry.State == EntityState.Added))
    {
        // every entry implements IPrimaryKey. Fill the Id
        (IPrimaryKey)entry.Id = this.CreateId
    }
}

private GUID CreateId()
{
    return Guid.NewGuid(); // or use your own Guid creator
}
</code>```

Body:
I have a class "Project" that hat two lists one for "Employee" and one for "tool", when i build my project with only one of the lists the database updates with corrrect relation, if add the second list to the class entity framework can not figureout how to create the relation.

 public class Project
{
    public Guid Id { get; set; }
    public List<Employee> RequiredEmployees {get;set;}
    public List<Tools> RequiredTools {get;set;}
}

Public class Tool
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public Project Project { get; set; }
    public Guid ProjectId { get; set; }
}

I get the error "There are no primary or candidate keys in the referenced table"
i hve tryed to map in ModelBuilder without success

 modelBuilder.Entity<Employee>()
    .HasRequired<Project>(s => s.Project)
    .WithMany(g => g.Employee)
    .HasForeignKey<Guid>(s => s.ProjectId);

any ideas ?

Body:
You have maneuvered yourself in several problems. The reported error is about the primary key. Furthermore you have problems specifying the one-to-many relations.

One-To-Many relations

Entity framework is easy if you follow the code first conventions For every deviation you need to tell entity framework about your deviations.

You planned to design a one-to-many between a Project and Tool: every Project has zero or more Tools, every Tool belongs to exactly one Project

If you follow the convention for one-to-many, you don't have to inform entity framework about this relation; entity framework will detect the relation by convention:

Use an ICollection instead of a List, after all, what would RequiredTools[4] mean?

Make the ICollection virtual. As long as your Project is a query, it is not a real ICollection, it only contains a class that can produce an ICollection.

Consider using the proper naming conventions.:

class Project
{
    public Guid Id { get; set; }
    // a project has zero or more Employees:
    public virtual ICollection<Employee> Employees {get;set;}
    // a project has zero or more Tools
    public virtual ICollectioin<Tool> Tools {get;set;}
}

Every Tool belongs to exactly one Project, using foreign key:

class Tool
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public Guid ProjectId {get; set;}
    public virtual Project Project { get; set; }
}

Similarly: Every Employee belongs to one Project

class Employee
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public Guid ProjectId {get; set;}
    public virtual Project Project { get; set; }
}

Or use many-to-many if an Employee can participate in several Projects:

class Employee
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    // an Employee works in zero or more Projects
    public virtual ICollection<Project> Projects { get; set; }
}

And your Dbcontext:

class MyDbContext : DbContext
{
    public DbSet<Employee> Employees {get; set;}
    public DbSet<Project> Projects {get; set;}
    public DbSet<Tool> Tools {get; set;}
}

This would be enough for entity framework to detect your relations and table names. I'd advice you to reconsider your decision to deviate from the code-first conventions.

However, if you really need to deviate your names you'll have to tell entity framework about your relations and table names:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    // a Project has zero or more Tools via property RequiredTools and table TableName:
    var entityProject = modelBuilder.Entity<Project>();
    entityProject.ToTable(... /* table name */);
    // a project has zero or more tools via property RequiredTools
    // every tool belongs to one required Project
    // using foreign key ProjectId
    entityproject.HasMany(project => project.RequiredTools)
        .WithRequired(tool => tool.Project)
        .HasFreignKey(tool => tool.ProjectId);
}

Primary Keys

You chose not to use the conventional type for your primary Keys. The problem is that entity framework does not know how to fill your Id. You'll have to tell entity framework that you'll fill the values for the primary keys.

This is done by overriding DbContext.SaveChanges

There are also two SaveChangesAsync; we will override them to. Both procedures will call the same function that will generate your Id:

public override int SaveChanges()
{
    GenerateIds();
    return base.SaveChanges();
}
public override Task<int> SaveChangesAsync()
{
    GenerateIds();
    return base.SaveChangesAsync();
}
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken)
    {
        this.GenerateIds();
        return base.SaveChangesAsync(cancellationToken);
    }

Function GenerateIds will get all items that need an Id and give it an Id. The objects that need an Id are all objects with state Added.

However, the object in the DbContext that remembered all changes that need to be saved, only knows that these objects are DbEntityEntries. It does not know which property in your DbEntityEntry represents the primary key.

You could solve this using KeyAttribute. Get the added entry, ask for its type, ask the type for the property that has the KeyAttribute and set the value of this property.

This method has several disadvantages. Reflection is a fairly slow process, it depends on you giving all classes that need a GUID to add the KeyAttribute, it is not type safe, and you will only detect that your made mistakes at run-time.

It is much better to define that all your entity classes should implement an interface that defines the primary key:

public interface IPrimaryKey
{
     GUID Id {get; set;}
}

class Tool : IPrimaryKey {...}
class Project : IPrimaryKey {...}

If you forgot to implement your Id, your compiler will warn you. GenerateIds is now fairly simple:

private void GenerateIds()
{
    foreach (DbEntityEntry addedEntry in this.ChangeTracker.Entries()
       .Where(entry => entry.State == EntityState.Added))
    {
        // every entry implements IPrimaryKey. Fill the Id
        (IPrimaryKey)entry.Id = this.CreateId
    }
}

private GUID CreateId()
{
    return Guid.NewGuid(); // or use your own Guid creator
}


问:
JSP Parameters not accessible using ${param.xxx} using HTML form
I'm following a tutorial on Udemy that explains JSPs and Servlets:
https://www.udemy.com/jsp-tutorial

The tutorial uses Eclipse + Tomcat server.

Since I'm an IntelliJ and Maven user I wanted to set up my environment using these two. So I created a Maven project from the following archetype: "org.apache.maven.archetypes:maven-archetype-webapp" and configured my POM as folllows:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>SomeGroupId</groupId>
  <artifactId>HelloWorldJavaServerPages</artifactId>
  <packaging>war</packaging>
  <version>1.0</version>
  <name>HelloWorldJavaServerPages Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.1</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>HelloWorldJavaServerPages</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
        <configuration>
          <url>http://localhost:8080/manager/text</url>
          <server>Tomcat85Localhost</server>
          <username>admin</username>
          <password>admin</password>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
</code>```

Set up my other properties as described here:
Tomcat 8 Maven Plugin for Java 8

I am able to build my project and use the tomcat plugin to deploy to the tomcat server (or manually drag the war file in the webapps folder).

Problem is that when I have the following two files:

student-form.html

```<code><html>
<head><title>Student Registration Form</title></head>
<body>
<form action="student-response.jsp">
    First name: <input type="text" name="firstName" />
    <br/>
    Last name: <input type="text" name="lastName" />
    <input type="submit" value="Submit" />
</form>
</body>
</html>
</code>```

student-response.jsp

```<code><html>
<head><title>Student Confirmation Title</title></head>
<body>
    The student is confirmed: <%= request.getParameter("firstName")%> ${param.lastName}
</body>
</html>
</code>```

The request.getParameter method works, but the ${param.lastName} does not and it simply shows up as plain text in the browser: ${param.lastName}.

Using Eclipse (without Maven) it does work for both, so I'm wondering what I'm doing actually different/wrong here and why it is not working.

Thanks in advance for your help.

答:
Once I found out that the references between the braces are called the "Expression Language", I decided to do another search on stackoverflow and found this:
Expression Language in JSP not working

Changing the web.xml as described in the link above made it work.

Thank you all for reading my question, the answer was quite simple actually.

Body:
I'm following a tutorial on Udemy that explains JSPs and Servlets:
https://www.udemy.com/jsp-tutorial

The tutorial uses Eclipse + Tomcat server.

Since I'm an IntelliJ and Maven user I wanted to set up my environment using these two. So I created a Maven project from the following archetype: "org.apache.maven.archetypes:maven-archetype-webapp" and configured my POM as folllows:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>SomeGroupId</groupId>
  <artifactId>HelloWorldJavaServerPages</artifactId>
  <packaging>war</packaging>
  <version>1.0</version>
  <name>HelloWorldJavaServerPages Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.1</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>HelloWorldJavaServerPages</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
        <configuration>
          <url>http://localhost:8080/manager/text</url>
          <server>Tomcat85Localhost</server>
          <username>admin</username>
          <password>admin</password>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

Set up my other properties as described here:
Tomcat 8 Maven Plugin for Java 8

I am able to build my project and use the tomcat plugin to deploy to the tomcat server (or manually drag the war file in the webapps folder).

Problem is that when I have the following two files:

student-form.html

<title>Student Registration Form</title>

<form action="student-response.jsp">
    First name: <input type="text" name="firstName" />

    Last name: <input type="text" name="lastName" />
    <input type="submit" value="Submit" />
</form>

student-response.jsp

<title>Student Confirmation Title</title>

    The student is confirmed: <%= request.getParameter("firstName")%> ${param.lastName}

The request.getParameter method works, but the ${param.lastName} does not and it simply shows up as plain text in the browser: ${param.lastName}.

Using Eclipse (without Maven) it does work for both, so I'm wondering what I'm doing actually different/wrong here and why it is not working.

Thanks in advance for your help.


问:
Mongoose autoReconnect option
I'm trying to set up the MongoDB auto reconnection feature via Mongoose. Every way that I have tried to pass the option has had no effect, or at least the reconnected event isn't being emitted.

What I've tried:

```<code>mongoose.createConnection("mongodb://localhost:27017/test", { auto_reconnect: true });
mongoose.createConnection("mongodb://localhost:27017/test", { autoReconnect: true });
mongoose.createConnection("mongodb://localhost:27017/test", { server: { auto_reconnect: true } });
mongoose.createConnection("mongodb://localhost:27017/test", { server: { autoReconnect: true } });
</code>```

If one of these is correct, the reconnected event should be triggered and a message should be logged in the console, however this never happens.

If there is a delay before the reconnection, does anyone know how to configure it?

Thanks in advance

For anyone looking into this, take a look at this and this issue in mongoose repository.

答:
To have multiple retries without request blocking while retrying I had to set bufferMaxEntries: 0:

```<code>const dbUri = 'mongodb://localhost/some_db';
const dbOptions = {
    useMongoClient: true,
    autoReconnect: true,
    reconnectTries: Number.MAX_VALUE,
    bufferMaxEntries: 0
};

mongoose.connect(dbUri, dbOptions).catch(err => process.exit(1));
</code>```

Title: Mongoose autoReconnect option

Body:
I'm trying to set up the MongoDB auto reconnection feature via Mongoose. Every way that I have tried to pass the option has had no effect, or at least the reconnected event isn't being emitted.

What I've tried:

mongoose.createConnection("mongodb://localhost:27017/test", { auto_reconnect: true });
mongoose.createConnection("mongodb://localhost:27017/test", { autoReconnect: true });
mongoose.createConnection("mongodb://localhost:27017/test", { server: { auto_reconnect: true } });
mongoose.createConnection("mongodb://localhost:27017/test", { server: { autoReconnect: true } });

If one of these is correct, the reconnected event should be triggered and a message should be logged in the console, however this never happens.

If there is a delay before the reconnection, does anyone know how to configure it?

Thanks in advance

For anyone looking into this, take a look at this and this issue in mongoose repository.

Body:
To have multiple retries without request blocking while retrying I had to set bufferMaxEntries: 0:

const dbUri = 'mongodb://localhost/some_db';
const dbOptions = {
    useMongoClient: true,
    autoReconnect: true,
    reconnectTries: Number.MAX_VALUE,
    bufferMaxEntries: 0
};

mongoose.connect(dbUri, dbOptions).catch(err => process.exit(1));


问:
How to add values/names of checkbox to a variable on form submit?
I have a set of checkboxes in a form that has a submit button.

```<code><form name="form" method="POST">
    <input type="checkbox" name="3" value="3">
    <input type="checkbox" name="7" value="7">
    <input type="checkbox" name="5" value="5">
    <input type="checkbox" name="12" value="12">
    <input type="submit" name="submit-form">
</form>

<?php
if (isset($_REQUEST['submit-form'])) {

}
?>
...
</code>```

The names/values that are currently in the code are dynamically generated and need to be kept (either in name or value will do).

When the form is submitted, I want to add the values or names of the checked checkboxes to a PHP variable, separated by commas, as a string.

Any help with the code that I should put in the if brackets would be much appreciated.

Thanks in advance.

答:
Give proper name to your checkbox with array. Then get value using that name and implode to retrieve string</p>

```<code><form name="form" method="POST">
    <input type="checkbox" name="chk[]" value="3">
    <input type="checkbox" name="chk[]" value="7">
    <input type="checkbox" name="chk[]" value="5">
    <input type="checkbox" name="chk[]" value="12">
    <input type="submit" name="submit-form">
</form>

<?php
if (isset($_REQUEST['submit-form'])) {
    $checkbox_val = $_POST["chk"];
    $checkbox_val = implode(",", $checkbox_val);
    echo $checkbox_val;
}
</code>```

Body:
I have a set of checkboxes in a form that has a submit button.

<form name="form" method="POST">
    <input type="checkbox" name="3" value="3">
    <input type="checkbox" name="7" value="7">
    <input type="checkbox" name="5" value="5">
    <input type="checkbox" name="12" value="12">
    <input type="submit" name="submit-form">
</form>

<?php
if (isset($_REQUEST['submit-form'])) {

}
?>
...

The names/values that are currently in the code are dynamically generated and need to be kept (either in name or value will do).

When the form is submitted, I want to add the values or names of the checked checkboxes to a PHP variable, separated by commas, as a string.

Any help with the code that I should put in the if brackets would be much appreciated.

Thanks in advance.

Body:
Give proper name to your checkbox with array. Then get value using that name and implode to retrieve string

<form name="form" method="POST">
    <input type="checkbox" name="chk[]" value="3">
    <input type="checkbox" name="chk[]" value="7">
    <input type="checkbox" name="chk[]" value="5">
    <input type="checkbox" name="chk[]" value="12">
    <input type="submit" name="submit-form">
</form>

<?php
if (isset($_REQUEST['submit-form'])) {
    $checkbox_val = $_POST["chk"];
    $checkbox_val = implode(",", $checkbox_val);
    echo $checkbox_val;
}


问:
Making bubble sort pure and efficient

Background

I am re-writing a series of algorithms together with a colleague that we are going to later on publish in a packet for the community.

To start, I picked the typical buble sort algorithm.

Objectives

the function must be pure

it must be efficient

it must obey the complexities listed in https://en.wikipedia.org/wiki/Bubble_sort

Please note that by "being pure" it doesn't mean that it's inside code cannot have impurity. It merely means that the PUBLIC API of the function must be pure and it must not affect anything outside of its scope.

Code

```<code>const isFunction = require("lodash.isfunction");
const cloneDeep = require("lodash.clonedeep");

const defaultCompare = require("./defaultCompare");

const bubble = ( array, fnCompare = defaultCompare ) => {

    if( !isFunction(fnCompare) )
        throw new Error("fnCompare must be a function");

    if(!Array.isArray(array))
        throw new Error("array must be an Array");

    if (array.length === 0)
        return [];

    const clonedArray = cloneDeep(array);

    return recursiveSort( clonedArray, clonedArray.length, fnCompare );
};

const recursiveSort = ( array, unsortedLength, fnCompare ) => {
    if( unsortedLength === 1 )
        return array;

    let swapped = false;
    for( let i = 0; i < unsortedLength - 1; i++ ){

        if( fnCompare( array[i], array[i + 1] ) > 0 ){
            const temp = array[i];
            array[i] = array[i + 1];
            array[i + 1] = temp;
            swapped = true;
        }
    }

    //Ensure O(n) if array is already ordered
    if(!swapped)
        return array;

    return recursiveSort( array, unsortedLength - 1, fnCompare );
};

module.exports = bubble;
</code>```

What do I want?

I am looking for any flaws in the code that could compromise objectives 1 and 3.

I am also looking to ways of improving its efficiency, since I am sure if the garbage collector likes recursivity that much (tail call optimisation is not implemented in most browers yet ...).

答:
Regarding objective 1, your code does fine at being pure - it just clones everything.

This does not go well with objective 3 though. While the complexity of recursiveSort is the expected O(n²), cloning the entire contents of the array puts an additional burden on the complexity, which now depends not only on the length of the input array but also on the size and depth of the elements. Since a sort does not mutate the elements anyway, this is pointless - you can and should just return a new array with the original objects. A major goal of purity is to allow for sharing!

So use

```<code>function bubbleSorted(array, fnCompare = defaultCompare) {
    if (typeof fnCompare != "function")
        throw new Error("fnCompare must be a function");
    if (!Array.isArray(array))
        throw new Error("array must be an Array");

    return recursiveSort(array.slice(), array.length, fnCompare);
}
</code>```

Notice also that you have unnecessary many base cases. Your algorithm should only need to stop when swapped is false. You do not need to do extra tests on the array length being 0 or 1.

Title: Making bubble sort pure and efficient

Body:
Background

I am re-writing a series of algorithms together with a colleague that we are going to later on publish in a packet for the community.

To start, I picked the typical buble sort algorithm.

Objectives

the function must be pure

it must be efficient

it must obey the complexities listed in https://en.wikipedia.org/wiki/Bubble_sort

Please note that by "being pure" it doesn't mean that it's inside code cannot have impurity. It merely means that the PUBLIC API of the function must be pure and it must not affect anything outside of its scope.

Code

const isFunction = require("lodash.isfunction");
const cloneDeep = require("lodash.clonedeep");

const defaultCompare = require("./defaultCompare");

const bubble = ( array, fnCompare = defaultCompare ) => {

    if( !isFunction(fnCompare) )
        throw new Error("fnCompare must be a function");

    if(!Array.isArray(array))
        throw new Error("array must be an Array");

    if (array.length === 0)
        return [];

    const clonedArray = cloneDeep(array);

    return recursiveSort( clonedArray, clonedArray.length, fnCompare );
};

const recursiveSort = ( array, unsortedLength, fnCompare ) => {
    if( unsortedLength === 1 )
        return array;

    let swapped = false;
    for( let i = 0; i < unsortedLength - 1; i++ ){

        if( fnCompare( array[i], array[i + 1] ) > 0 ){
            const temp = array[i];
            array[i] = array[i + 1];
            array[i + 1] = temp;
            swapped = true;
        }
    }

    //Ensure O(n) if array is already ordered
    if(!swapped)
        return array;

    return recursiveSort( array, unsortedLength - 1, fnCompare );
};

module.exports = bubble;

What do I want?

I am looking for any flaws in the code that could compromise objectives 1 and 3.

I am also looking to ways of improving its efficiency, since I am sure if the garbage collector likes recursivity that much (tail call optimisation is not implemented in most browers yet ...).

Body:
Regarding objective 1, your code does fine at being pure - it just clones everything.

This does not go well with objective 3 though. While the complexity of recursiveSort is the expected O(n²), cloning the entire contents of the array puts an additional burden on the complexity, which now depends not only on the length of the input array but also on the size and depth of the elements. Since a sort does not mutate the elements anyway, this is pointless - you can and should just return a new array with the original objects. A major goal of purity is to allow for sharing!

So use

function bubbleSorted(array, fnCompare = defaultCompare) {
    if (typeof fnCompare != "function")
        throw new Error("fnCompare must be a function");
    if (!Array.isArray(array))
        throw new Error("array must be an Array");

    return recursiveSort(array.slice(), array.length, fnCompare);
}

Notice also that you have unnecessary many base cases. Your algorithm should only need to stop when swapped is false. You do not need to do extra tests on the array length being 0 or 1.


问:
apk running on AVD but not on phone
My compileSdkVersion is 26

minSdkVersion is 15

and TargetSdkVersion is 26

App runs fine on AVD of API level 22 but when installed on phone and opened it shows "Unfortunately APP has stopped". My phone is running in jellybean.

答: There was a memory error when tested on debugging mode. I reduced the dimensions of the image and that solved the problem. </p>

Title: apk running on AVD but not on phone


问:
Wpf app taskbar icon not showing when launched from scheduled task at login in W10
I have a wpf app with the main form hidden, only a taskbar icon to interact with.
It works fine, i mean, exe double-click icon appears, interact, close...
On Windows 7 also works without any issue.

Here the weird thing... If i create a scheduled task to launch it on user login, it works only in W7, in Windows 10 the icon is hidden.

I know that the app is running and doing stuff because of the implemented log.

By the way, i'm using Harcodet taskbar declared in xaml this way:

```<code><tb:TaskbarIcon x:Name="TBIcon"
    IconSource="{Binding ViewModel.Status, Converter={StaticResource TaskBarIconConverter}}"
    ToolTipText="{Binding ViewModel.TbIconToolTip, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
...
</code>```

Windows version is 10.0.16299.64

Any help?

UPDATE:

You have to change the scheduled task option to "Run only when user is logged on" (makes sense...)

答: You have to change the scheduled task option to "Run only when user is logged on" (for W7 and W10) in the general tab of the task:

Body:
I have a wpf app with the main form hidden, only a taskbar icon to interact with.
It works fine, i mean, exe double-click icon appears, interact, close...
On Windows 7 also works without any issue.

Here the weird thing... If i create a scheduled task to launch it on user login, it works only in W7, in Windows 10 the icon is hidden.

I know that the app is running and doing stuff because of the implemented log.

By the way, i'm using Harcodet taskbar declared in xaml this way:

<tb:TaskbarIcon x:Name="TBIcon"
    IconSource="{Binding ViewModel.Status, Converter={StaticResource TaskBarIconConverter}}"
    ToolTipText="{Binding ViewModel.TbIconToolTip, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
...

Windows version is 10.0.16299.64

Any help?

UPDATE:

You have to change the scheduled task option to "Run only when user is logged on" (makes sense...)


问:
How to calculate multiplication of numbers in a html table below specific headings - IONIC
Explanation: I have a html table with 3 columns namely Price , Quantity and Total. Numers are written below them.

Requirement: I need to multiply price with Quantity and bring that value in Total. I want to do this while leaving the quantity field or on a key press [as i am typing].

Image and code of my form are shared below

Image:

code of invoice.html

```<code><div style="margin-top:15px">
    <table>
       <tr>
         <th></th>
         <th>Price</th>
         <th>Quantity</th>
         <th>Total</th>

         <th></th>
       </tr>
       <tr *ngFor="let items of inVoiceItems2;let i=index;">
         <td>{{i+1}}</td>
         <td style="width:198px"><input type="text" name="price" [(ngModel)]="inVoiceItems2[i].price" style="width:198px;border:0px"/></td>
         <td><input type="text" name="quantity" [(ngModel)]="inVoiceItems2[i].quantity" style="width:198px;border:0px"/></td>
         <td><input type="text" name="total" [(ngModel)]="inVoiceItems2[i].total" style="width:198px;border:0px"/></td>
       </tr>
   </table>

   <br>
   <input type="button" value="Add New Row" (click)="addRow2()" style="margin-top:5px"/>
   <br>
   <input type="button" value="Calculate Bill" (click)="calculate_bill()" style="margin-top:5px"/>

 </div>
</code>```

code of invoice.ts

```<code>  addRow2(){
    this.inVoiceItems2.push({'debit':'','credit':''});
  }

  calculate_bill(){

  }
</code>```

答:
Here is a basic way, starting from your current setup.

Change the template for the total input to:

```<code><input type="text" name="total" [ngModel]="getRowSum(inVoiceItems2[i].quantity, inVoiceItems2[i].price)" style="width:198px;border:0px"/>
</code>```

Create the getRowSum method in invoice.ts:

```<code>getRowSum(qty, price) {
    const sum = qty * price;
    return isNaN(sum) ? '' : sum;
}
</code>```

Body:
Explanation: I have a html table with 3 columns namely Price , Quantity and Total. Numers are written below them.

Requirement: I need to multiply price with Quantity and bring that value in Total. I want to do this while leaving the quantity field or on a key press [as i am typing].

Image and code of my form are shared below

Image:

code of invoice.html

         Price
         Quantity
         Total

         {{i+1}}
         <input type="text" name="price" [(ngModel)]="inVoiceItems2[i].price" style="width:198px;border:0px"/>
         <input type="text" name="quantity" [(ngModel)]="inVoiceItems2[i].quantity" style="width:198px;border:0px"/>
         <input type="text" name="total" [(ngModel)]="inVoiceItems2[i].total" style="width:198px;border:0px"/>

   <input type="button" value="Add New Row" (click)="addRow2()" style="margin-top:5px"/>

   <input type="button" value="Calculate Bill" (click)="calculate_bill()" style="margin-top:5px"/>

code of invoice.ts

  addRow2(){
    this.inVoiceItems2.push({'debit':'','credit':''});
  }

  calculate_bill(){

  }

Body:
Here is a basic way, starting from your current setup.

Change the template for the total input to:

<input type="text" name="total" [ngModel]="getRowSum(inVoiceItems2[i].quantity, inVoiceItems2[i].price)" style="width:198px;border:0px"/>

Create the getRowSum method in invoice.ts:

getRowSum(qty, price) {
    const sum = qty * price;
    return isNaN(sum) ? '' : sum;
}


问:
How to use ng-bind-html but disable tag
, ... AngularJS
I used ng-bind-html and show success data, but I want to show only text, not show data with style ,  because it ruined my layout:

Data is content's notes:
some text....

My filter:

```<code>var myApp = angular.module("myModule", []);
myApp.filter('to_trusted', ['$sce', function ($sce) {
    return function (text) {
        return $sce.trustAsHtml(text);
    };
}]);
</code>```

My view:

```<code><p ng-bind-html="note.content.substr(0, 130) + '...' | to_trusted"></p>
</code>```

答:
Short answer: You can apply a css class to the div, resetting html tag formatting behavior overriding it. For example:

```<code><p class="ignore-html-tags" ng-bind-html="note.content.substr(0, 130) + '...' | to_trusted"></p
</code>```

And in your css:

```<code>.ignore-html-tags * {
  font-size: 10px !important;
  font-weight: normal !important;
  /* any other style overwrite */
}
</code>```

Title: How to use ng-bind-html but disable tag <h1>, <b>... AngularJS

Body:
I used ng-bind-html and show success data, but I want to show only text, not show data with style ,  because it ruined my layout:

Data is content's notes:
some text....

My filter:

var myApp = angular.module("myModule", []);
myApp.filter('to_trusted', ['$sce', function ($sce) {
    return function (text) {
        return $sce.trustAsHtml(text);
    };
}]);

My view:

Body:
Short answer: You can apply a css class to the div, resetting html tag formatting behavior overriding it. For example:

<p class="ignore-html-tags" ng-bind-html="note.content.substr(0, 130) + '...' | to_trusted"></p

And in your css:

.ignore-html-tags * {
  font-size: 10px !important;
  font-weight: normal !important;
  /* any other style overwrite */
}


问:
Casting, unboxing, conversion..?
Recently I am learning value types and I am bit confused. Also both casting and unboxing uses the same syntax - (expected type)(object), right?
And what about simple conversion between types, that is casting or just conversion?</p>

```<code>int x = (int)2.5; //casting?

object a=x;
int Y=(int)a;  //unboxing I think

Random r=new Random();
object X=r;
Random R=(Random)X;  // casting
</code>```

答:
One important restriction on unboxing is that you can only unbox to the exact value-type(or its nullable equivalent) and not to another value-type the original value-type is convertible to.

```<code>int myInt = 1;
object x = myInt; // box
int  unbox1 = (int)x;  // successful unbox
int? unbox2 = (int?)x; // successful unbox
long unbox3 = (long)x; // error. Can't unbox int to long
long unbox4 = (long)(int)x; // works. First it unboxes to int, and then converts to long
</code>```

Another interesting bit is that a nullable value-type gets boxed as its non nullable type, and can be unboxed as both the nullable and the non nullable type. Since a nullable that has the value null boxes to the reference null the information about its type is lost during the boxing.

ContentLicense: CC BY-SA 2.5

Title: Casting, unboxing, conversion..?

Body:
Recently I am learning value types and I am bit confused. Also both casting and unboxing uses the same syntax - (expected type)(object), right?
And what about simple conversion between types, that is casting or just conversion?

int x = (int)2.5; //casting?

object a=x;
int Y=(int)a;  //unboxing I think

Random r=new Random();
object X=r;
Random R=(Random)X;  // casting

Body:
One important restriction on unboxing is that you can only unbox to the exact value-type(or its nullable equivalent) and not to another value-type the original value-type is convertible to.

int myInt = 1;
object x = myInt; // box
int  unbox1 = (int)x;  // successful unbox
int? unbox2 = (int?)x; // successful unbox
long unbox3 = (long)x; // error. Can't unbox int to long
long unbox4 = (long)(int)x; // works. First it unboxes to int, and then converts to long

Another interesting bit is that a nullable value-type gets boxed as its non nullable type, and can be unboxed as both the nullable and the non nullable type. Since a nullable that has the value null boxes to the reference null the information about its type is lost during the boxing.


问:
Cannot restore SQL Server snapshot
For some reason I cannot restore my SQL Server snapshot.

I have the a database DB01 with a snapshot DB01_SS.

When trying to restore the snapshot with the following query:

```<code>USE master
GO

ALTER DATABASE DB01 SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

RESTORE DATABASE DB01 FROM DATABASE_SNAPSHOT = 'DB01_SS';
GO

ALTER DATABASE DB01 SET MULTI_USER
GO
</code>```

I get this error message:

Msg 3137, Level 16, State 1, Line 5

  Database cannot be reverted. Either the primary or the snapshot names are improperly specified, all other snapshots have not been dropped, or there are missing files.

  Msg 3013, Level 16, State 1, Line 5

  RESTORE DATABASE is terminating abnormally.

I have checked, the name is properly specified. There are no other snapshots available on the server. The only strange thing I came across was when I logged on the SQL Server to look up the snapshot file. And it had a different name then in the SSMS gui. It was named DB_SS_2017.SS. When trying to restore with that name, I get the following error:

Msg 911, Level 16, State 4, Line 5

  Database DB_SS_2017.SS does not exist. Make sure that the name is entered correctly.

  Msg 3013, Level 16, State 1, Line 5

  RESTORE DATABASE is terminating abnormally.

And last but not least, when trying to check the properties of the snapshot, again in SSMS. The properties button is greyed out! How can I restore the SQL Server snapshot?

答:
You are may be in one of the following cases:

You have multiple snapshots defined, try refreshing the snapshots folder in ssms or run
select * from sys.databases where source_database_id IS NOT NULLto see if you have more snapshots. Because snapshots are 'copy on write', you cannot restore if you have multiple snapshots for a single database.

You are not specifying correctly the logical name of the snapshot. Run
select * from sys.databases where source_database_id IS NOT NULL to check the the logical name of the snapshot. Then rerun the restore using that name.

Your snapshot file is not linked anymore with the snapshot (snapshot got somehow corrupted). The statement below queries the pages in the snapshot file. Run it and see if you have any errors.
select db_name(database_id) [<database name>], database_id, count(*) from sys.dm_os_buffer_descriptors where database_id= (select top 1 database_id from sys.databases where source_database_id IS NOT NULL) group by database_id

Title: Cannot restore SQL Server snapshot

Body:
For some reason I cannot restore my SQL Server snapshot.

I have the a database DB01 with a snapshot DB01_SS.

When trying to restore the snapshot with the following query:

USE master
GO

ALTER DATABASE DB01 SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

RESTORE DATABASE DB01 FROM DATABASE_SNAPSHOT = 'DB01_SS';
GO

ALTER DATABASE DB01 SET MULTI_USER
GO

I get this error message:

Msg 3137, Level 16, State 1, Line 5

  Database cannot be reverted. Either the primary or the snapshot names are improperly specified, all other snapshots have not been dropped, or there are missing files.

  Msg 3013, Level 16, State 1, Line 5

  RESTORE DATABASE is terminating abnormally.

I have checked, the name is properly specified. There are no other snapshots available on the server. The only strange thing I came across was when I logged on the SQL Server to look up the snapshot file. And it had a different name then in the SSMS gui. It was named DB_SS_2017.SS. When trying to restore with that name, I get the following error:

Msg 911, Level 16, State 4, Line 5

  Database DB_SS_2017.SS does not exist. Make sure that the name is entered correctly.

  Msg 3013, Level 16, State 1, Line 5

  RESTORE DATABASE is terminating abnormally.

And last but not least, when trying to check the properties of the snapshot, again in SSMS. The properties button is greyed out! How can I restore the SQL Server snapshot?


问:
Laravel: Eloquent 'more than' and 'lesser than'
I want a Database Query like this in query builder:

SELECT * FROM posts WHERE active = 1 AND published <= '{$now}' LIMIT 5

What I made:

```<code>$now = new Carbon;
$feed = Post::where([
        ['active' => 1],
        ['published' => $now]
    ])
    -> take(5)
    -> get()
    -> toArray();
</code>```

But it's like:

SELECT * FROM posts WHERE active = 1 AND published = '{$now}' LIMIT 5

How to make <, <=, >, >=, <> and LIKE statements with ::where method?

答:
Eloquent</p>

```<code>  $feed = Post::where('active','=',1)->where('published','<=',$now)->get();
</code>```

Body:
I want a Database Query like this in query builder:

SELECT * FROM posts WHERE active = 1 AND published <= '{$now}' LIMIT 5

What I made:

$now = new Carbon;
$feed = Post::where([
        ['active' => 1],
        ['published' => $now]
    ])
    -> take(5)
    -> get()
    -> toArray();

But it's like:

SELECT * FROM posts WHERE active = 1 AND published = '{$now}' LIMIT 5

How to make <, <=, >, >=, <> and LIKE statements with ::where method?

Body:
Eloquent

  $feed = Post::where('active','=',1)->where('published','<=',$now)->get();


答:
You can use the same name for the checkboxes as shown in below code:

```<code><form name="form" method="POST">
    <input type="checkbox" name="numbers[]" value="3">
    <input type="checkbox" name="numbers[]" value="7">
    <input type="checkbox" name="numbers[]" value="5">
    <input type="checkbox" name="numbers[]" value="12">
    <input type="submit" name="submit-form">
</form>
</code>```

And in process you can glue all the selected checkboxes using following code:

```<code>if (isset($_REQUEST['submit-form'])) {
     $allSelectedNumbers = implode(",", $_REQUEST['numbers']);
}
</code>```

Title: How to add values/names of checkbox to a variable on form submit?

Body:
You can use the same name for the checkboxes as shown in below code:

<form name="form" method="POST">
    <input type="checkbox" name="numbers[]" value="3">
    <input type="checkbox" name="numbers[]" value="7">
    <input type="checkbox" name="numbers[]" value="5">
    <input type="checkbox" name="numbers[]" value="12">
    <input type="submit" name="submit-form">
</form>

And in process you can glue all the selected checkboxes using following code:

if (isset($_REQUEST['submit-form'])) {
     $allSelectedNumbers = implode(",", $_REQUEST['numbers']);
}


问:
Socat exclusive lock to PTY
I would like only one process to open the PTY device created by socat.
I used the following to create my_ser device, but it can be read / written by multiple processes.

socat -t 0 INTERFACE:my_nw,type=2 PTY,mode=0777,rawer,link=/dev/my_ser

I tried to used
socat -t 0 INTERFACE:my_nw,type=2 PTY,mode=0777,rawer,link=/dev/my_ser,ioctl-void=0x540c to use the PTY exclusive lock (TIOCEXCL), but it does not work.
I can see the IOCTL being executed, but with no effect.

I am running on Ubuntu machine

答:
I understood now the TIOCEXCL flag in more detail. The application opening the PTY terminal should use this flag to obtain the exclusive lock. If we use it during PTY creation in socat command, it has no effect. But it does not give any error as well.

Thus the application should call the ioctl flag and it should be removed from here.

Title: Socat exclusive lock to PTY


问:
ActivityGroup Example
Can anybody please give me an example of ActivityGroup. I have heard that by making use of ActivityGroup we can change the nested activities maintaining the TabHost as it is.

Any help would be greatly appreciated.

Thanks,
david brown

答:
david here is a an example I found useful:

http://ericharlow.blogspot.com/2010/09/experience-multiple-android-activities.html

Title: ActivityGroup Example


问:
In Kotlin Programming language importance of varargs in terms of uses
Let me know what is the importance of varargs in Kotlin, if there is any document or some useful links. Please share.</p>

答:
The vararg parameters allow for functions that accept variable number of arguments in a natural way, i.e. without creating an array or a collection first, filling it with the items, and only then passing it, compare:

If there were no vararg parameters:

```<code>val items = ArrayList<String>().apply { add("foo"); add("bar"); add("baz") }
qux(items)
</code>```

With vararg:

```<code>qux("foo", "bar", "baz")
</code>```

This is particularly useful for initializing collections and other containers, and there are numerous functions for that in kotlin-stdlib, such as arrayOf(...), listOf(...), setOf(...), mapOf(...), sequenceOf(...) and more.

To see the usages in kotlin-stdlib, search for the word 'vararg' in the API reference pages (there's a lot in packages kotlin.collections, kotlin.text).

Basically, if there is a function accepting a collection that a user might frequently call with only a few items (and choose the items right before the call), it makes sense to provide a vararg overload for that function.

Body:
The vararg parameters allow for functions that accept variable number of arguments in a natural way, i.e. without creating an array or a collection first, filling it with the items, and only then passing it, compare:

If there were no vararg parameters:

val items = ArrayList<String>().apply { add("foo"); add("bar"); add("baz") }
qux(items)

With vararg:

qux("foo", "bar", "baz")

This is particularly useful for initializing collections and other containers, and there are numerous functions for that in kotlin-stdlib, such as arrayOf(...), listOf(...), setOf(...), mapOf(...), sequenceOf(...) and more.

To see the usages in kotlin-stdlib, search for the word 'vararg' in the API reference pages (there's a lot in packages kotlin.collections, kotlin.text).

Basically, if there is a function accepting a collection that a user might frequently call with only a few items (and choose the items right before the call), it makes sense to provide a vararg overload for that function.


问:
Measure the execution time of a function call in Perl
Is it possible to execute staff only if the previous function is not over yet and the time is over
Something like:</p>

```<code>my $timeout = 10; # seconds
sub get_entities {
    # do staff ...
}
get_entities();

if (time == $timeout and get_entities is not over yet) {
    # do staff...
}
</code>```

答:
Your edit made the question considerably more complicated.

As I'm sure you'll know - as a standard, perl runs sequentially - if a command takes 25s, then the rest of the code just waits until it's ready.

But sometimes, you want to build in a timeout yourself for various reasons. There's a number of ways you can do this:

alarm and a signal handler

```<code>#!/usr/bin/env perl

use strict;
use warnings;

$SIG{'ALRM'} = \&handle_alarm;

my $we_are_snoozing = 1;

sub handle_alarm {

   print "Caught SIGALRM\n";
   $we_are_snoozing = 0;
}

sub have_a_snooze {
   while ( $we_are_snoozing ) {
       print "Zzzz\n";
       sleep 10;
   }
}

alarm 25;
have_a_snooze;
print "Done\n";
</code>```

You're limited in what you can do inside your handler - keep it minimal. But alarm generates a SIGALRM (which can also be generated by kill) and the process can trap and handle it.

threads

Threads allow you to spin off part of your code to run in parallel or asynchronously. This is handy for both resource usage, but also when you're faced with a thing that's not worth waiting indefinitely for.

```<code>#!/usr/bin/env perl

use strict;
use warnings;

use threads;
use threads::shared;

my $we_are_snoozing : shared;
$we_are_snoozing = 1;

sub have_a_snooze {
   while ( $we_are_snoozing ) {
       print "Zzzz\n";
       sleep 10;
   }
}

my $thr = threads -> create (\&have_a_snooze);

sleep 5;

if ($thr -> is_joinable) {
   print "Thread exited normally\n";
   $thr -> join;
 }
 else {
    print "Thread still running, detaching it\n";
    $we_are_snoozing = 0;
    $thr -> detach;
}
</code>```

IO::Socket and can_read

One of the more common reasons for wanting a timeout, is simply waiting for IO.

This is quite easy to handle with IO::Socket and a timeout:

```<code>#!/usr/bin/env perl
use strict;
use warnings;

my $pid = open ( my $input, '-|', "some_command" );
my $select = IO::Select -> new ( $input );
while ( $select -> can_read(10) ) {
  my $line = <$input>;
  print $line;
}
</code>```

This will timeout 10s after the last result, not the first. But that may be useful too.

Body:
Is it possible to execute staff only if the previous function is not over yet and the time is over
Something like:

my $timeout = 10; # seconds
sub get_entities {
    # do staff ...
}
get_entities();

if (time == $timeout and get_entities is not over yet) {
    # do staff...
}

Body:
Your edit made the question considerably more complicated.

As I'm sure you'll know - as a standard, perl runs sequentially - if a command takes 25s, then the rest of the code just waits until it's ready.

But sometimes, you want to build in a timeout yourself for various reasons. There's a number of ways you can do this:

alarm and a signal handler

#!/usr/bin/env perl

use strict;
use warnings;

$SIG{'ALRM'} = \&handle_alarm;

my $we_are_snoozing = 1;

sub handle_alarm {

   print "Caught SIGALRM\n";
   $we_are_snoozing = 0;
}

sub have_a_snooze {
   while ( $we_are_snoozing ) {
       print "Zzzz\n";
       sleep 10;
   }
}

alarm 25;
have_a_snooze;
print "Done\n";

You're limited in what you can do inside your handler - keep it minimal. But alarm generates a SIGALRM (which can also be generated by kill) and the process can trap and handle it.

threads

Threads allow you to spin off part of your code to run in parallel or asynchronously. This is handy for both resource usage, but also when you're faced with a thing that's not worth waiting indefinitely for.

#!/usr/bin/env perl

use strict;
use warnings;

use threads;
use threads::shared;

my $we_are_snoozing : shared;
$we_are_snoozing = 1;

sub have_a_snooze {
   while ( $we_are_snoozing ) {
       print "Zzzz\n";
       sleep 10;
   }
}

my $thr = threads -> create (\&have_a_snooze);

sleep 5;

if ($thr -> is_joinable) {
   print "Thread exited normally\n";
   $thr -> join;
 }
 else {
    print "Thread still running, detaching it\n";
    $we_are_snoozing = 0;
    $thr -> detach;
}

IO::Socket and can_read

One of the more common reasons for wanting a timeout, is simply waiting for IO.

This is quite easy to handle with IO::Socket and a timeout:

#!/usr/bin/env perl
use strict;
use warnings;

my $pid = open ( my $input, '-|', "some_command" );
my $select = IO::Select -> new ( $input );
while ( $select -> can_read(10) ) {
  my $line = <$input>;
  print $line;
}

This will timeout 10s after the last result, not the first. But that may be useful too.


问:
Display alert Disabled when click outside in xamarin forms
I have Implemented the Display alert for get confirmation from user. But it is disappeared when clicking outside of the alert box. Please suggest me how to handle the alert when clicking outside. Thanks in advance.</p>

答: You can try with this plugin. In this plugin you can set CloseWhenBackgroundIsClicked = false or true.</p>


问:
How to run method on Job/thread Creation?
I am new to Quartz, and I have been reading the documentation but I couldn't find what I need.

I have several jobs that we schedule/run with Quartz, and I would like to tell it to run a method when it creates a new thread for a Job.

The code I want to run is generic and I need to run it during the thread start.

I understand that I could achieve what I want if I create a JobBase class with my code and have all my Jobs inherit from it; but since this would require several modifications and this code is not really concern of the Jobs I was wondering if there is some feature in Quartz that would allow me to accomplish what I need without modifying them.

Can you tell Quartz to run a method when it creates a Thread/Job during the thread start?

答: Implement IJobListener or extend JobListenerSupport and implement or override the JobToBeExecuted method. As explained here, register your listener each time you application runs.


问:
Why does SBT resolve SNAPSHOT version?
Here are my resolvers:

```<code>resolvers in ThisBuild ++= Seq(
  "Sonatype Nexus Repository Manager" at "https://.../repository/maven-snapshots/",
  "Sonatype Nexus Repository Manager" at "https://.../repository/maven-releases/")
</code>```

Here is how dependency is specified:

```<code>libraryDependencies += a %% b % "1.+"
</code>```

Nexus contains 1.0.0 in maven-releases

Here is the log I get:

```<code>[FAILED     ] a#b_2.11;1.0.0-SNAPSHOT!b_2.11.jar:  (0ms)
[warn] ==== local: tried
[warn]   /Users/me/.ivy2/local/a/b_2.11/1.0.0-SNAPSHOT/jars/b_2.11.jar
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/.../b_2.11/1.0.0-SNAPSHOT/b_2.11-1.0.0-SNAPSHOT.jar
[warn] ==== local-preloaded-ivy: tried
[warn]   /Users/me/.sbt/preloaded/a/b_2.11/1.0.0-SNAPSHOT/jars/b_2.11.jar
[warn] ==== local-preloaded: tried
[warn]   file:////Users/pavelvoronin/.sbt/preloaded/.../b_2.11/1.0.0-SNAPSHOT/b_2.11-1.0.0-SNAPSHOT.jar
[warn] ==== Sonatype Nexus Repository Manager: tried
[warn]   https://.../repository/maven-snapshots/.../b_2.11/1.0.0-SNAPSHOT/b_2.11-1.0.0-SNAPSHOT.jar
[warn] ==== Sonatype Nexus Repository Manager: tried
[warn]   https://.../repository/maven-releases/.../b_2.11/1.0.0-SNAPSHOT/b_2.11-1.0.0-SNAPSHOT.jar
</code>```

Why does it look for SNAPSHOT? And does not notice 1.0.0?

Some lines from Ivy docs:

end the revision with a + selects the latest sub-revision of the
  dependency module. For instance,  if the dependency module exists in
  revision 1.0.3, 1.0.7 and 1.1.2, "1.0.+" will select 1.0.7.

Update

After I cleaned Ivy cache it started just telling me that 1.+ is not found. And here are some logs from Nexus:

```<code>2017-10-18 11:51:07,030+0000 DEBUG [qtp219355933-2530] user org.sonatype.nexus.repository.view.Router - Request: Request{action=‘HEAD’, path=‘/.../b_2.11/maven-metadata.xml’, parameters={}, payload=HttpRequestPayloadAdapter{contentType=‘null’, size=-1}, multipart=false}

2017-10-18 11:51:07,031+0000 DEBUG [qtp219355933-2530] user org.sonatype.nexus.repository.view.handlers.BrowseUnsupportedHandler$MatcherImpl - Matching: HEAD /.../b_2.11/maven-metadata.xml

2017-10-18 11:51:07,034+0000 DEBUG [qtp219355933-2530] user org.sonatype.nexus.repository.view.Router - Response: Response{status=Status{successful=false, code=404, message=‘.../b_2.11/maven-metadata.xml’}, payload=null}
</code>```

答:
The problem is that standard sbt pack does not create maven-metadata.xml file.

With Aether-deploy plugin everything works fine.

Title: Why does SBT resolve SNAPSHOT version?

Body:
Here are my resolvers:

resolvers in ThisBuild ++= Seq(
  "Sonatype Nexus Repository Manager" at "https://.../repository/maven-snapshots/",
  "Sonatype Nexus Repository Manager" at "https://.../repository/maven-releases/")

Here is how dependency is specified:

libraryDependencies += a %% b % "1.+"

Nexus contains 1.0.0 in maven-releases

Here is the log I get:

[FAILED     ] a#b_2.11;1.0.0-SNAPSHOT!b_2.11.jar:  (0ms)
[warn] ==== local: tried
[warn]   /Users/me/.ivy2/local/a/b_2.11/1.0.0-SNAPSHOT/jars/b_2.11.jar
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/.../b_2.11/1.0.0-SNAPSHOT/b_2.11-1.0.0-SNAPSHOT.jar
[warn] ==== local-preloaded-ivy: tried
[warn]   /Users/me/.sbt/preloaded/a/b_2.11/1.0.0-SNAPSHOT/jars/b_2.11.jar
[warn] ==== local-preloaded: tried
[warn]   file:////Users/pavelvoronin/.sbt/preloaded/.../b_2.11/1.0.0-SNAPSHOT/b_2.11-1.0.0-SNAPSHOT.jar
[warn] ==== Sonatype Nexus Repository Manager: tried
[warn]   https://.../repository/maven-snapshots/.../b_2.11/1.0.0-SNAPSHOT/b_2.11-1.0.0-SNAPSHOT.jar
[warn] ==== Sonatype Nexus Repository Manager: tried
[warn]   https://.../repository/maven-releases/.../b_2.11/1.0.0-SNAPSHOT/b_2.11-1.0.0-SNAPSHOT.jar

Why does it look for SNAPSHOT? And does not notice 1.0.0?

Some lines from Ivy docs:

end the revision with a + selects the latest sub-revision of the
  dependency module. For instance,  if the dependency module exists in
  revision 1.0.3, 1.0.7 and 1.1.2, "1.0.+" will select 1.0.7.

Update

After I cleaned Ivy cache it started just telling me that 1.+ is not found. And here are some logs from Nexus:

2017-10-18 11:51:07,030+0000 DEBUG [qtp219355933-2530] user org.sonatype.nexus.repository.view.Router - Request: Request{action=‘HEAD’, path=‘/.../b_2.11/maven-metadata.xml’, parameters={}, payload=HttpRequestPayloadAdapter{contentType=‘null’, size=-1}, multipart=false}

2017-10-18 11:51:07,031+0000 DEBUG [qtp219355933-2530] user org.sonatype.nexus.repository.view.handlers.BrowseUnsupportedHandler$MatcherImpl - Matching: HEAD /.../b_2.11/maven-metadata.xml

2017-10-18 11:51:07,034+0000 DEBUG [qtp219355933-2530] user org.sonatype.nexus.repository.view.Router - Response: Response{status=Status{successful=false, code=404, message=‘.../b_2.11/maven-metadata.xml’}, payload=null}


问:
Flexbox parent fit text content of children
I want to use flexbox to make a column that can scroll as its text content gets longer.
I drew a picture in keynote to make a better explanation.

when texts are small

when texts get big

Here is my current code, just every elements in my code is in flexboxes.
I edited my script to include .app .sidebar

.app {
         display: flex;
         height: 100vh;
         flex-direction: row;
}
.sidebar {
         display:flex;
         flex: 1;
}
.cv {
 display: flex;
        flex:5;
 flex-direction: column;
 margin:20px;
 border: 1px solid lightgrey;
 border-radius: 10px;
 background-color: white;
 overflow: scroll;
}
.header {
 display: flex;
 flex: 0 0 150px;
 justify-content: center;
 align-items: center;
 font-size: 20px;
}
.section {
 display: flex;
 flex-direction: column;
 border: 1px solid lightgrey;
 margin: 10px;
 border-radius: 10px;
}
.sectionHeader{
 display: flex;
 align-items: center;
 font-size: 18px;
 padding-left: 20px;
 padding-top: 15px;
 padding-bottom: 5px;
 flex: 0 0 30px;
 background-color: gray;
 color:white;
 font-weight: 700;
}
.sectionBody{
 display: flex;
 flex: 1;
 padding: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="app">
  <div class="sidebar"></div>
  <div class="cv">
 <div class="header">Header</div>
 <div class="section">
  <div class="sectionHeader">Section Header</div>
  <div class="sectionBody">LONG TEXT</div>
 </div>
 <div class="section">
  <div class="sectionHeader">Section Header</div>
  <div class="sectionBody">LONG TEXT</div>
 </div>
  </div>
</div></code>```

答:
You need to do 2 things:

Give the cv a min-height: 0;  (fix for i.a. Firefox)

Add flex-shrink: 0 to the .section so it won't collapse when not fit

Stack snippet

body {
  margin: 0;
}

.app {
  display: flex;
  height: 100vh;
}

.sidebar {
  display: flex;
  flex: 1;
  background: red;
}

.cv {
  display: flex;
  flex: 5;
  flex-direction: column;
  margin: 20px;
  border: 1px solid lightgrey;
  border-radius: 10px;
  background-color: white;
  overflow: scroll;
  min-height: 0;                    /*  added  */
}

.header {
  display: flex;
  flex: 0 0 150px;
  justify-content: center;
  align-items: center;
  font-size: 20px;
}

.section {
  display: flex;
  flex-direction: column;
  border: 1px solid lightgrey;
  margin: 10px;
  border-radius: 10px;
  flex-shrink: 0;                   /*  added  */
}

.sectionHeader {
  display: flex;
  align-items: center;
  font-size: 18px;
  padding-left: 20px;
  padding-top: 15px;
  padding-bottom: 5px;
  flex: 0 0 30px;
  background-color: gray;
  color: white;
  font-weight: 700;
}

.sectionBody {
  display: flex;
  flex: 1;
  padding: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="app">
  <div class="sidebar">sidebar</div>
  <div class="cv">
    <div class="header">Header</div>
    <div class="section">
      <div class="sectionHeader">Section Header</div>
      <div class="sectionBody">LONG TEXT</div>
    </div>
    <div class="section">
      <div class="sectionHeader">Section Header</div>
      <div class="sectionBody">LONG TEXT</div>
    </div>
  </div>
</div></code>```

Body:
I want to use flexbox to make a column that can scroll as its text content gets longer.
I drew a picture in keynote to make a better explanation.

when texts are small

when texts get big

Here is my current code, just every elements in my code is in flexboxes.
I edited my script to include .app .sidebar

.app {
         display: flex;
         height: 100vh;
         flex-direction: row;
}
.sidebar {
         display:flex;
         flex: 1;
}
.cv {
 display: flex;
        flex:5;
 flex-direction: column;
 margin:20px;
 border: 1px solid lightgrey;
 border-radius: 10px;
 background-color: white;
 overflow: scroll;
}
.header {
 display: flex;
 flex: 0 0 150px;
 justify-content: center;
 align-items: center;
 font-size: 20px;
}
.section {
 display: flex;
 flex-direction: column;
 border: 1px solid lightgrey;
 margin: 10px;
 border-radius: 10px;
}
.sectionHeader{
 display: flex;
 align-items: center;
 font-size: 18px;
 padding-left: 20px;
 padding-top: 15px;
 padding-bottom: 5px;
 flex: 0 0 30px;
 background-color: gray;
 color:white;
 font-weight: 700;
}
.sectionBody{
 display: flex;
 flex: 1;
 padding: 20px;
}

Header

Section Header

LONG TEXT

Section Header

LONG TEXT

Body:
You need to do 2 things:

Give the cv a min-height: 0;  (fix for i.a. Firefox)

Add flex-shrink: 0 to the .section so it won't collapse when not fit

Stack snippet

body {
  margin: 0;
}

.app {
  display: flex;
  height: 100vh;
}

.sidebar {
  display: flex;
  flex: 1;
  background: red;
}

.cv {
  display: flex;
  flex: 5;
  flex-direction: column;
  margin: 20px;
  border: 1px solid lightgrey;
  border-radius: 10px;
  background-color: white;
  overflow: scroll;
  min-height: 0;                    /*  added  */
}

.header {
  display: flex;
  flex: 0 0 150px;
  justify-content: center;
  align-items: center;
  font-size: 20px;
}

.section {
  display: flex;
  flex-direction: column;
  border: 1px solid lightgrey;
  margin: 10px;
  border-radius: 10px;
  flex-shrink: 0;                   /*  added  */
}

.sectionHeader {
  display: flex;
  align-items: center;
  font-size: 18px;
  padding-left: 20px;
  padding-top: 15px;
  padding-bottom: 5px;
  flex: 0 0 30px;
  background-color: gray;
  color: white;
  font-weight: 700;
}

.sectionBody {
  display: flex;
  flex: 1;
  padding: 20px;
}

<div class="app">
  <div class="sidebar">sidebar</div>
  <div class="cv">
    <div class="header">Header</div>
    <div class="section">
      <div class="sectionHeader">Section Header</div>
      <div class="sectionBody">LONG TEXT</div>
    </div>
    <div class="section">
      <div class="sectionHeader">Section Header</div>
      <div class="sectionBody">LONG TEXT</div>
    </div>
  </div>
</div>


问:
Unable to obtain exclusive access when adding a check constraint
I have encountered a problem with in one of my Informix environments, I can't get an exclusive lock on a table to add a check constraint.

Error message

SQL Error (-242): Could not open database table ().

  ISAM error: non-exclusive access.

My first thought was that there was a session using the table so I waited to the end of the day to minimize usage and tried again with the same result.

I then checked for locks on that table but there aren't any locks at all on that table, in fact there are no locks at all in that database right now.

I then turned of replication on the table but the problem is still there.

Now I'm all out of ideas on how to solve this, I'd rather not restart the server or kill all the sessions connected to it.

Body:
Great answer - also worth checking the following

onstat -g stm | grep -E "TABLENAME|^session"

This checks the prepared SQL statement cache and will return all sessions and any mention of your TABLENAME

session 79412526   ----------------------------------------------------------

session 79412418   ----------------------------------------------------------

session 79412200   ----------------------------------------------------------

c00000042e5eeff0 30624       SELECT COUNT(*) FROM TABLENAME

session 79411988   ----------------------------------------------------------

c0000004167b1230 30624       SELECT COUNT(*) FROM TABLENAME

session 79411978   ----------------------------------------------------------

I have of course masked the data from our environment but you should get the drift.


问:
Angularjs POST method returns 404 error in console
I am trying to write the data with the POST method through api on: http://localhost:4567/api/v1/companies. I have tried various things from the stack, This is my code:

```<code><head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
    var app = angular.module("app", []);
    app.controller("HttpGetController", function ($scope, $http) {

        $scope.SendData = function () {
           // use $.param jQuery function to serialize data from JSON
            var data = $.param({
                id: $scope.id,
                name: $scope.name,
                city: $scope.city,
             });

            var config = {
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                }
            }

            $http.post('http://localhost:4567/api/v1/companies', data, config)
            .success(function (data, status, headers, config) {
                $scope.PostDataResponse = data;
            })
            .error(function (data, status, header, config) {
                $scope.ResponseDetails = "Data: " + data +
                    "<hr />status: " + status +
                    "<hr />headers: " + header +
                    "<hr />config: " + config;
            });
        };

    });
</script>
</head>
<div ng-app="app" ng-controller="HttpGetController">
    <p>ID: <input type="number" name="id" ng-model="id" required /></p>
    <p>Name: <input type="text" name="name" ng-model="name" required /></p>
    <p>City: <input type="text" name="city" ng-model="city" required /></p>
    <button ng-click="SendData()">Submit</button>
    <hr />
    {{ PostDataResponse }}
</div>
</code>```

In the console i got 404 error.

答:
The options request you see there is indicative of CORS.  When the client code and server come from different domains or ports it will do an OPTIONS request before sending the POST so you just need to allow any domain to request things from your server side by adding the appropriate headers to accept connections from anywhere.  You said you are using node I believe in another question:

https://enable-cors.org/server_expressjs.html

The 404 response to the OPTIONS request is stopping the browser from doing anything further but this is basically between the browser and the server and the server needs to give the correct response to the OPTIONS request or the browser will give up.

So you either enable that on the server or have the server send the client files on the same domain/port as the server API comes from and then it's also not an issue.

Body:
I am trying to write the data with the POST method through api on: http://localhost:4567/api/v1/companies. I have tried various things from the stack, This is my code:

ID: <input type="number" name="id" ng-model="id" required />

Name: <input type="text" name="name" ng-model="name" required />

City: <input type="text" name="city" ng-model="city" required />

    <button ng-click="SendData()">Submit</button>

    {{ PostDataResponse }}

In the console i got 404 error.


问:
How to read a text file and insert into databse in php?
Basically what i am trying to do is to insert content of a file to my database table.To be more clear ill explain it in details.I have a folder named "filedata" in which text files are uploaded.and the movement the files are uploaded to filedata folder i want to read those file,insert its content to database and delete that file from filedata folder.I am in confusion from where to start.I know php basics not much knowledge of it.So please anyone suggest me where to start. </p>

答:
Okay, I'm not going to write all the code you need to do for this but here's some pointers..

Getting all the files: glob(PATH), you can foreach through that, basename() will return the filename without path.
Deleting file: unlink(FILE)
Inserting data: file_get_contents() will grab the file (memory hog!)

Inserting data into a db.. make sure to have a blob column (binary) or largetext with base64 encoded.. depends what you need it for I guess..


问:
MS ACCESS replacing wildcard and underscore always stopped working
case:
i need to change the barcode if it contains _A, _B, _C into "".
for example.

image_a into image
, build_b into build

everytime I query

```<code>update table set barcode = replace(barcode,"\_*", "")
</code>```

then it crashes.

an update:

the problem more like if the query contains replace function or instr stopped working. no debug option and simply restarting.

Any help would be appreciated.

答:
Try being a bit selective:</p>

```<code>update
    table
set
    barcode = left(barcode, instr(barcode, "_") - 1)
where
    barcode like "*_*"
</code>```

Body:
case:
i need to change the barcode if it contains _A, _B, _C into "".
for example.

image_a into image
, build_b into build

everytime I query

update table set barcode = replace(barcode,"\_*", "")

then it crashes.

an update:

the problem more like if the query contains replace function or instr stopped working. no debug option and simply restarting.

Any help would be appreciated.

Body:
Try being a bit selective:

update
    table
set
    barcode = left(barcode, instr(barcode, "_") - 1)
where
    barcode like "*_*"


问:
Why datetime in MATLAB is giving weird result?
I am trying to convert datenum values from double array. But conversion is leading to weird values in 'year'.

e.g.

     t(1)=23823.1076388889;
      d=datetime(t,'ConvertFrom','datenum');
      d(1) = '22-Mar-0065 02:35:00'

What am I doing wrong?

Thanks for your help.

答:
You have to know which date format (the 'dateType' argument) your t(1) is in. The datenum format gives the number of days since 0-Jan-0000

23,000 days are around 63 years, so that explains your result.

Try the other formats listed here: https://se.mathworks.com/help/matlab/ref/datetime.html#inputarg_dateType