问:
ASP.NET Generic method to mock EF6 DbSet
In my ASP.NET MVC5 web-app I'm using the EF (Model-first) for my database-communication. For unit-testing purposes, I created a generic method to generate Mock database sets. Unfortunately, I am unable to mock all the methods because when .Where(), .Any() and .Find() are used in my tested code, an exception is thrown. Can anyone help me on this? My code is below.
Unittest:

```<code>[TestClass()]
public class MessagingServiceTests
{
    Mock<BoatstersEntitiesContainer> _mockContext;
    MessagingService _service;
    string _connectionId;
    Guid _userId;

    [TestInitialize()]
    public void TestInitialize()
    {
        _userId = Guid.Parse("12345678-1234-1234-1234-123412344142");
        _connectionId = "abc123";

        // Setup entities
        User user = new User { Id = _userId, CustomerId = 1 };
        Customer customer = new Customer { Id = 1, User = user, FirstName = "TestFirstName" };
        user.Customer = customer;
        Customer boatOwnerCustomer = new Customer { Id = 2, FirstName = "BoatOwner" };
        Boat boat = new Boat { Id = 1, Customer = boatOwnerCustomer, CustomerId = boatOwnerCustomer.Id };
        boatOwnerCustomer.Boats.Add(boat);

        // Init mocksets
        var userMockSet = MockDbSet.Build(new List<User> { user });
        var customerMockSet = MockDbSet.Build(new List<Customer> { customer, boatOwnerCustomer });
        var conversationMockSet = MockDbSet.Build(new List<Conversation>());
        var messageMockSet = MockDbSet.Build(new List<Message>());
        var boatMockSet = MockDbSet.Build(new List<Boat> { boat });
        var messagingHubConnectionMockSet = MockDbSet.Build(new List<MessagingHubConnection>());

        // Setup mockcontext
        _mockContext = new Mock<BoatstersEntitiesContainer>();
        _mockContext.Setup(m => m.Users).Returns(userMockSet.Object);
        _mockContext.Setup(m => m.Customers).Returns(customerMockSet.Object);
        _mockContext.Setup(m => m.Conversations).Returns(conversationMockSet.Object);
        _mockContext.Setup(m => m.Messages).Returns(messageMockSet.Object);
        _mockContext.Setup(m => m.Boats).Returns(boatMockSet.Object);
        _mockContext.Setup(m => m.MessagingHubConnections).Returns(messagingHubConnectionMockSet.Object);

        // Start service
        _service = new MessagingService(_mockContext.Object, _userId);
    }

    [TestMethod()]
    public void When_PartnerConnected_IsTrue()
    {
        Conversation conversation = new Conversation {
            Id = 1,
            Boat = _mockContext.Object.Boats.First(b => b.Id.Equals(1)),
            BoatId = _mockContext.Object.Boats.First(b => b.Id.Equals(1)).Id
        };
        conversation.Customers.Add(_mockContext.Object.Customers.First(b => b.Id.Equals(1)));
        conversation.Customers.Add(_mockContext.Object.Customers.First(b => b.Id.Equals(2)));

        MessagingHubConnection connection = new MessagingHubConnection
        {
            Id = 1,
            Connected = true,
            ConnectionId  = "abc123",
            Conversation = conversation,
            ConversationId = 1,
            Customer = _mockContext.Object.Customers.First(b => b.Id.Equals(2)),
            CustomerId = 2
        };
        conversation.MessagingHubConnections.Add(connection);

        _mockContext.Object.MessagingHubConnections.Add(connection);
        _mockContext.Object.Conversations.Add(conversation);

        var result = _service.IsPartnerConnected();
        Assert.IsTrue(result);

        // Clean up
        _mockContext.Object.Conversations.RemoveRange(_mockContext.Object.Conversations);
        _mockContext.Object.MessagingHubConnections.RemoveRange(_mockContext.Object.MessagingHubConnections);
    }
}
</code>```

Generic mockset creator:

```<code>public static class MockDbSet
{
    public static Mock<DbSet<TEntity>> Build<TEntity>(List<TEntity> data) where TEntity : class
    {
        var queryable = data.AsQueryable();
        var mockSet = new Mock<DbSet<TEntity>>();
        mockSet.As<IQueryable<TEntity>>().Setup(m => m.Provider).Returns(queryable.Provider);
        mockSet.As<IQueryable<TEntity>>().Setup(m => m.Expression).Returns(queryable.Expression);
        mockSet.As<IQueryable<TEntity>>().Setup(m => m.ElementType).Returns(queryable.ElementType);
        mockSet.As<IQueryable<TEntity>>().Setup(m => m.GetEnumerator()).Returns(queryable.GetEnumerator());
        mockSet.Setup(m => m.Add(It.IsAny<TEntity>())).Callback<TEntity>(data.Add);

        return mockSet;
    }
}
</code>```

Messagingservice (which is being tested)

```<code>public class MessagingService : BaseRepository<Conversation>
{
    private readonly Customer _customer;
    private MessagingHubConnection _connection;

    public MessagingService(BoatstersEntitiesContainer context, Guid userId) : base(context)
    {
        Context = context;
        _customer = Context.Customers.First(c => c.User.Id == userId);
    }

    public bool IsPartnerConnected()
    {
        // Check if partner is connected
        return Context.MessagingHubConnections.Any(c => c.ConversationId.Equals(_connection.ConversationId) && c.Customer.Id != _customer.Id && c.Connected);
    }
}
</code>```

In MessagingService.IsPartnerConnected(), the following exception is thrown:

Test Name:    When_PartnerConnected_IsTrue
  Test FullName:  Boatsters.Sunshine.UnitTests.MessagingServiceTests.When_PartnerConnected_IsTrue
  Test Source:    C:\Users\Jelle\Source\Repos\Boatsters.Sunshine\Boatsters.Sunshine.UnitTests\MessagingServiceUnitTest.cs : line 94
  Test Outcome:   Failed
  Test Duration:  0:00:00,0289022
  Result StackTrace:

  bij lambda_method(Closure , MessagingHubConnection )
     bij System.Linq.Enumerable.Any[TSource](IEnumerable1 source, Func2 predicate)
     bij lambda_method(Closure )
     bij System.Linq.EnumerableExecutor1.Execute()
     bij System.Linq.EnumerableQuery1.System.Linq.IQueryProvider.Execute[S](Expression expression)
     bij System.Linq.Queryable.Any[TSource](IQueryable1 source, Expression1 predicate)
     bij Boatsters.Services.MessagingService.IsPartnerConnected() in C:\Users\Jelle\Source\Repos\Boatsters.Sunshine\Boatsters.Services\MessagingService.cs:line 156
     bij xxx.MessagingServiceTests.When_PartnerConnected_IsTrue() in C:\xxx\MessagingServiceUnitTest.cs:line 118
  Result Message:
  Test method
  xxx.UnitTests.MessagingServiceTests.When_PartnerConnected_IsTrue threw exception:
  System.NullReferenceException: Object reference not set to an instance of an object

答:
Based on review of MessagingService, it is not immediately apparent where _connection is assigned a value. Looks like that is what is null when the method under test is called based on stack trace lambda_method(Closure , MessagingHubConnection )

Also from past experiences with Moq and DbSet<>, this line needs to updated so that multiple calls can be made to the data source.

```<code>mockSet.As<IQueryable<TEntity>>().Setup(m => m.GetEnumerator()).Returns(queryable.GetEnumerator());
</code>```

Change the .Returns(queryable.GetEnumerator()) to return a Func

```<code>mockSet.As<IQueryable<TEntity>>()
    .Setup(m => m.GetEnumerator())
    .Returns(() => queryable.GetEnumerator()); //<-- Note change here.
</code>```

The original will return the same enumerator for every call which can only be enumerated once and may cause issues. Using the Func will allow a fresh enumerator to be return on every call to allow for multiple passes on the data source.

Body:
In my ASP.NET MVC5 web-app I'm using the EF (Model-first) for my database-communication. For unit-testing purposes, I created a generic method to generate Mock database sets. Unfortunately, I am unable to mock all the methods because when .Where(), .Any() and .Find() are used in my tested code, an exception is thrown. Can anyone help me on this? My code is below.
Unittest:

[TestClass()]
public class MessagingServiceTests
{
    Mock<BoatstersEntitiesContainer> _mockContext;
    MessagingService _service;
    string _connectionId;
    Guid _userId;

    [TestInitialize()]
    public void TestInitialize()
    {
        _userId = Guid.Parse("12345678-1234-1234-1234-123412344142");
        _connectionId = "abc123";

        // Setup entities
        User user = new User { Id = _userId, CustomerId = 1 };
        Customer customer = new Customer { Id = 1, User = user, FirstName = "TestFirstName" };
        user.Customer = customer;
        Customer boatOwnerCustomer = new Customer { Id = 2, FirstName = "BoatOwner" };
        Boat boat = new Boat { Id = 1, Customer = boatOwnerCustomer, CustomerId = boatOwnerCustomer.Id };
        boatOwnerCustomer.Boats.Add(boat);

        // Init mocksets
        var userMockSet = MockDbSet.Build(new List<User> { user });
        var customerMockSet = MockDbSet.Build(new List<Customer> { customer, boatOwnerCustomer });
        var conversationMockSet = MockDbSet.Build(new List<Conversation>());
        var messageMockSet = MockDbSet.Build(new List<Message>());
        var boatMockSet = MockDbSet.Build(new List<Boat> { boat });
        var messagingHubConnectionMockSet = MockDbSet.Build(new List<MessagingHubConnection>());

        // Setup mockcontext
        _mockContext = new Mock<BoatstersEntitiesContainer>();
        _mockContext.Setup(m => m.Users).Returns(userMockSet.Object);
        _mockContext.Setup(m => m.Customers).Returns(customerMockSet.Object);
        _mockContext.Setup(m => m.Conversations).Returns(conversationMockSet.Object);
        _mockContext.Setup(m => m.Messages).Returns(messageMockSet.Object);
        _mockContext.Setup(m => m.Boats).Returns(boatMockSet.Object);
        _mockContext.Setup(m => m.MessagingHubConnections).Returns(messagingHubConnectionMockSet.Object);

        // Start service
        _service = new MessagingService(_mockContext.Object, _userId);
    }

    [TestMethod()]
    public void When_PartnerConnected_IsTrue()
    {
        Conversation conversation = new Conversation {
            Id = 1,
            Boat = _mockContext.Object.Boats.First(b => b.Id.Equals(1)),
            BoatId = _mockContext.Object.Boats.First(b => b.Id.Equals(1)).Id
        };
        conversation.Customers.Add(_mockContext.Object.Customers.First(b => b.Id.Equals(1)));
        conversation.Customers.Add(_mockContext.Object.Customers.First(b => b.Id.Equals(2)));

        MessagingHubConnection connection = new MessagingHubConnection
        {
            Id = 1,
            Connected = true,
            ConnectionId  = "abc123",
            Conversation = conversation,
            ConversationId = 1,
            Customer = _mockContext.Object.Customers.First(b => b.Id.Equals(2)),
            CustomerId = 2
        };
        conversation.MessagingHubConnections.Add(connection);

        _mockContext.Object.MessagingHubConnections.Add(connection);
        _mockContext.Object.Conversations.Add(conversation);

        var result = _service.IsPartnerConnected();
        Assert.IsTrue(result);

        // Clean up
        _mockContext.Object.Conversations.RemoveRange(_mockContext.Object.Conversations);
        _mockContext.Object.MessagingHubConnections.RemoveRange(_mockContext.Object.MessagingHubConnections);
    }
}

Generic mockset creator:

public static class MockDbSet
{
    public static Mock<DbSet<TEntity>> Build<TEntity>(List<TEntity> data) where TEntity : class
    {
        var queryable = data.AsQueryable();
        var mockSet = new Mock<DbSet<TEntity>>();
        mockSet.As<IQueryable<TEntity>>().Setup(m => m.Provider).Returns(queryable.Provider);
        mockSet.As<IQueryable<TEntity>>().Setup(m => m.Expression).Returns(queryable.Expression);
        mockSet.As<IQueryable<TEntity>>().Setup(m => m.ElementType).Returns(queryable.ElementType);
        mockSet.As<IQueryable<TEntity>>().Setup(m => m.GetEnumerator()).Returns(queryable.GetEnumerator());
        mockSet.Setup(m => m.Add(It.IsAny<TEntity>())).Callback<TEntity>(data.Add);

        return mockSet;
    }
}

Messagingservice (which is being tested)

public class MessagingService : BaseRepository<Conversation>
{
    private readonly Customer _customer;
    private MessagingHubConnection _connection;

    public MessagingService(BoatstersEntitiesContainer context, Guid userId) : base(context)
    {
        Context = context;
        _customer = Context.Customers.First(c => c.User.Id == userId);
    }

    public bool IsPartnerConnected()
    {
        // Check if partner is connected
        return Context.MessagingHubConnections.Any(c => c.ConversationId.Equals(_connection.ConversationId) && c.Customer.Id != _customer.Id && c.Connected);
    }
}

In MessagingService.IsPartnerConnected(), the following exception is thrown:

Test Name:    When_PartnerConnected_IsTrue
  Test FullName:  Boatsters.Sunshine.UnitTests.MessagingServiceTests.When_PartnerConnected_IsTrue
  Test Source:    C:\Users\Jelle\Source\Repos\Boatsters.Sunshine\Boatsters.Sunshine.UnitTests\MessagingServiceUnitTest.cs : line 94
  Test Outcome:   Failed
  Test Duration:  0:00:00,0289022
  Result StackTrace:

  bij lambda_method(Closure , MessagingHubConnection )
     bij System.Linq.Enumerable.Any[TSource](IEnumerable1 source, Func2 predicate)
     bij lambda_method(Closure )
     bij System.Linq.EnumerableExecutor1.Execute()
     bij System.Linq.EnumerableQuery1.System.Linq.IQueryProvider.Execute[S](Expression expression)
     bij System.Linq.Queryable.Any[TSource](IQueryable1 source, Expression1 predicate)
     bij Boatsters.Services.MessagingService.IsPartnerConnected() in C:\Users\Jelle\Source\Repos\Boatsters.Sunshine\Boatsters.Services\MessagingService.cs:line 156
     bij xxx.MessagingServiceTests.When_PartnerConnected_IsTrue() in C:\xxx\MessagingServiceUnitTest.cs:line 118
  Result Message:
  Test method
  xxx.UnitTests.MessagingServiceTests.When_PartnerConnected_IsTrue threw exception:
  System.NullReferenceException: Object reference not set to an instance of an object

Body:
Based on review of MessagingService, it is not immediately apparent where _connection is assigned a value. Looks like that is what is null when the method under test is called based on stack trace lambda_method(Closure , MessagingHubConnection )

Also from past experiences with Moq and DbSet<>, this line needs to updated so that multiple calls can be made to the data source.

mockSet.As<IQueryable<TEntity>>().Setup(m => m.GetEnumerator()).Returns(queryable.GetEnumerator());

Change the .Returns(queryable.GetEnumerator()) to return a Func

mockSet.As<IQueryable<TEntity>>()
    .Setup(m => m.GetEnumerator())
    .Returns(() => queryable.GetEnumerator()); //<-- Note change here.

The original will return the same enumerator for every call which can only be enumerated once and may cause issues. Using the Func will allow a fresh enumerator to be return on every call to allow for multiple passes on the data source.


来源: stackexchange

问:
Displaying images with img tag in React.js
Iv'e been trying to load images to a simple  tag, but it simply doesn't work. I wish to use ES6 syntax, and not dynamically injecting the image in this case:

```<code>import React from 'react'
import BackgroundImage from './Sparrow_icon.png';

const Icon = ({icon}) => {

    return (
        <img src={require('./Sparrow_icon.png')} alt=""/>
    )
};

export default Icon;
</code>```

which resulted in:

```<code><img src="data:image/png;base64,bW9kdWxlLmV4cG9ydHMgPSBfX3dlYnBhY2tfcHVibGljX3BhdGhfXyArICJlNTZlYThiOTQ5OWUzZmM2NTkyY2ZhMjgxNjg1YTBkMy5wbmciOw==" />
</code>```

which displays.. nothing.
Also, when i'm converting it with a base64 convertor- the image doesn't exist.

I'm using webpack2 with file-loader and url-loader.

答:
It seems the problem is that this file is being processed by file-loader AND url-loader.

```<code>$ echo 'bW9kdWxlLmV4cG9ydHMgPSBfX3dlYnBhY2tfcHVibGljX3BhdGhfXyArICJlNTZlYThiOTQ5OWUzZmM2NTkyY2ZhMjgxNjg1YTBkMy5wbmciOw==' | base64 -d
module.exports = __webpack_public_path__ + "e56ea8b9499e3fc6592cfa281685a0d3.png";
</code>```

Change your webpack config to only use one or the other for png files.

ContentLicense: CC BY-SA 3.0

Body:
Iv'e been trying to load images to a simple  tag, but it simply doesn't work. I wish to use ES6 syntax, and not dynamically injecting the image in this case:

import React from 'react'
import BackgroundImage from './Sparrow_icon.png';

const Icon = ({icon}) => {

    return (

    )
};

export default Icon;

which resulted in:

which displays.. nothing.
Also, when i'm converting it with a base64 convertor- the image doesn't exist.

I'm using webpack2 with file-loader and url-loader.

Body:
It seems the problem is that this file is being processed by file-loader AND url-loader.

$ echo 'bW9kdWxlLmV4cG9ydHMgPSBfX3dlYnBhY2tfcHVibGljX3BhdGhfXyArICJlNTZlYThiOTQ5OWUzZmM2NTkyY2ZhMjgxNjg1YTBkMy5wbmciOw==' | base64 -d
module.exports = __webpack_public_path__ + "e56ea8b9499e3fc6592cfa281685a0d3.png";

Change your webpack config to only use one or the other for png files.


问:
Javasacript get the timezone name string?
How we can get the timezone strgin name from javascript, for example

```<code>var d = new Date();
document.getElementById("demo").innerHTML =d;
</code>```

this returns

Thu Mar 30 2017 15:13:57 GMT+0500 (Pakistan Standard Time)

Now how we can get the part between the brackets(Pakistan Standard Time) ?

答:
You could try</p>

```<code>var d = new Date();
var n = d.toLocaleString('en', {timeZoneName:'long'}).split(' ');
var index = n.length;
do {
    index--;
    console
} while(n[index] !== "PM" && n[index] !== "AM");
var timezone = n.slice(index+1).join(" ");
console.log(timezone);
</code>```

Body:
How we can get the timezone strgin name from javascript, for example

var d = new Date();
document.getElementById("demo").innerHTML =d;

this returns

Thu Mar 30 2017 15:13:57 GMT+0500 (Pakistan Standard Time)

Now how we can get the part between the brackets(Pakistan Standard Time) ?

Body:
You could try

var d = new Date();
var n = d.toLocaleString('en', {timeZoneName:'long'}).split(' ');
var index = n.length;
do {
    index--;
    console
} while(n[index] !== "PM" && n[index] !== "AM");
var timezone = n.slice(index+1).join(" ");
console.log(timezone);


问:
Getting Current Login in User name using Angular js
I have used Waffle to get the Current Logged in User using Jsp and Tomcat.
But how do i replicate the Same using Angularjs .

I have used the Demo code in Git for waffle https://dblock.github.com/waffle/

Please help as i am confused of how to get the Angular app to Call the jsp and fetch username back to the Angular app .

答:
In my opinion best way to check for user is using AngularJS http interceptor.

```<code>$httpProvider.interceptors.push(function ($q) {
        return {
            'request': function(response) {

            },
            'response': function (response) {

                // TODO Create check for user authentication. With every request send "headers"
                return response;
            },
            'responseError': function (reject) {

                // Forbidden
                if(reject.status == 403) {
                    console.log('This page is forbidden.');
                    window.location = '/';
                // Unauthorized
                } else if(reject.status == 401) {
                    console.log("You're not authorized to view this page.");
                    window.location = '/';
                }

                return $q.reject(reject);
            }
        };
    });
</code>```

Write a function in 'response' to check http headers for user or something similar. Interceptors in AngularJS

This interceptor will run with every call you make to Database and if error is returned you can also handle this there.

Body:
In my opinion best way to check for user is using AngularJS http interceptor.

$httpProvider.interceptors.push(function ($q) {
        return {
            'request': function(response) {

            },
            'response': function (response) {

                // TODO Create check for user authentication. With every request send "headers"
                return response;
            },
            'responseError': function (reject) {

                // Forbidden
                if(reject.status == 403) {
                    console.log('This page is forbidden.');
                    window.location = '/';
                // Unauthorized
                } else if(reject.status == 401) {
                    console.log("You're not authorized to view this page.");
                    window.location = '/';
                }

                return $q.reject(reject);
            }
        };
    });

Write a function in 'response' to check http headers for user or something similar. Interceptors in AngularJS

This interceptor will run with every call you make to Database and if error is returned you can also handle this there.


问:
How to assign an integer value to an ArrayList of String elements?
I have an ArrayList of string elements that the user enters in the MainActivity of my application (Android Studio). It is called ArrayList<String> serviceNames. The service names can be anything like Facebook, Fitness App, Clock App etc. I want to assign an Integer value to each of these user inputs of services as I am working on a fitness function to do with Swarm Particle algorithm.

```<code>public class CustomServiceSelection implements Goodness {

    public static final int numOfServices = MainActivity.servicenames.size();
    public static final int NUM_DIMENSIONS = 2 + numOfServices;
    public static final int DATA = 0;
    public static final int WLAN = 1; //get the names of the services from the arraylist
    //then convert them into an integer for the bits/no_dimensions

    boolean alwaysOn = MainActivity.costUTILITY.contains(100.0);

    ArrayList<String> serviceNames = MainActivity.servicenames;
    ArrayList<Double> costData = MainActivity.costDATA;
    ArrayList<Double> costWlan = MainActivity.costWLAN;
    ArrayList<Double> costUtilities = MainActivity.costUTILITY;
    private double batteryCost;
    //ArrayList<Double> battery = MainActivity.costBattery;

    public CustomServiceSelection(double batteryCost, ArrayList<Double> costData, ArrayList<Double> costWlan,
                                  ArrayList<Double> costUtilities) {
        if (costUtilities == null || costUtilities.size() < 1 || costData.size() < 1 || costWlan.size() < 1) {
            throw new RuntimeException("Please add atleast 1 cost to Data, WLAN and Utility");
        }
        this.batteryCost = batteryCost; //make sure you add battery field to UI, user enters battery level
        this.costData = costData;
        this.costWlan = costWlan;
        this.costUtilities = costUtilities;
        //this.services = services;
    }

    public double getGoodness(boolean[] bits) {
        double utility = 0.0;
        double rcost = 0.0;
        ArrayList<Double> resourceCost = new ArrayList<Double>();

        for(Double i : costData){

        }

        for (int x = 0; x <= NUM_DIMENSIONS; x++) { //for each resource that is a bit
            if (bits[x] == alwaysOn) {  //if a utility cost of a service is 100, return -2000.0
                return -2000;
            }

            if (bits[DATA] && bits[WLAN]) {
                return -500;
            }
            if (!bits[DATA] || bits[WLAN]) {
                return -450; //particle goodness always returns this??
            }
            if (bits[DATA]) {
                resourceCost = costData;
            } else if (bits[WLAN]) {
                resourceCost = costWlan;
            }

            for (int i = 0; i <= NUM_DIMENSIONS; i++) { //for each service the user enters
                if (bits[i]) {
                    utility += costUtilities.get(i);
                    rcost += resourceCost.get(i);
                }
            }
            if (rcost < batteryCost) {
                return utility;
            }

        }
        return utility * 0.50;
    }
    }
</code>```

I want the num_dimensions to be 2 (WLAN and DATA) plus the number of services the user enters in the main activity. So if they enter 4 services, then 6 dimensions altogether.Then I want to assign an 'int' value to these services like this...

```<code>   public static final int Facebook = 2;
   public static final int Twitter = 3;
   public static final int ClockApp = 4;
</code>```

When that is done, I want to pass it onto the getGoodness() function which will take these values as bits in the number of dimensions, so Facebook will be the 3rd bit in the dimensions. Any help or advice would be great, I m a uni student undertaking this as a project.

EDIT: I have now implemented a hashmap in the getGoodness() function. My code now looks like this...

```<code>    public double getGoodness(boolean[] bits) {
    double utility = 0.0;
    double rcost = 0.0;
    ArrayList<Double> resourceCost = new ArrayList<Double>();

    for(int i = 2; i <= NUM_DIMENSIONS; i++) { //hashmap that stores the   service names with an int value
        for(int k = 0; k <= numOfServices; k++) {
            serviceMap.put(i, serviceNames.get(k));
        }
</code>```

I need the first 2 bits of NUM_DIMENSIONS to be WLAN and DATA. So for each service the user enters, the integer value assigned to them goes up by 1 starting at 2. So... (2, Facebook), (3, Twitter), (4, Uber) etc. Now my next problem is, passing these down to the getGoodness() function, I have an arraylist from the main UI activity that takes a utility(priority) cost from 0-100 of each service. This is called costUtilities, I want the bits that contain a utility of 80.0-100.0 (double) to return me a value of -2000 if it isn't on. If you can help with this, that would be great, if not, thank you for the help you've given so far, and wish me luck in my final year individual project on PSO :)

答:
Rajat answer is correct. You can also creat a JSON Object, and insert the labels that you want, and after that include it in the hashMap.

JSON example:

```<code>public static JSONObject constructEHRJSON(int sessionID, String EHR) {
  {
    JSONObject JSONobj = new JSONObject();

    try {

        JSONobj.put("1", sessionID);
        JSONobj.put("2", EHR);
    } catch (JSONException e) {
        /
    }
    return JSONobj;

}
</code>```

Body:
I have an ArrayList of string elements that the user enters in the MainActivity of my application (Android Studio). It is called ArrayList<String> serviceNames. The service names can be anything like Facebook, Fitness App, Clock App etc. I want to assign an Integer value to each of these user inputs of services as I am working on a fitness function to do with Swarm Particle algorithm.

public class CustomServiceSelection implements Goodness {

    public static final int numOfServices = MainActivity.servicenames.size();
    public static final int NUM_DIMENSIONS = 2 + numOfServices;
    public static final int DATA = 0;
    public static final int WLAN = 1; //get the names of the services from the arraylist
    //then convert them into an integer for the bits/no_dimensions

    boolean alwaysOn = MainActivity.costUTILITY.contains(100.0);

    ArrayList<String> serviceNames = MainActivity.servicenames;
    ArrayList<Double> costData = MainActivity.costDATA;
    ArrayList<Double> costWlan = MainActivity.costWLAN;
    ArrayList<Double> costUtilities = MainActivity.costUTILITY;
    private double batteryCost;
    //ArrayList<Double> battery = MainActivity.costBattery;

    public CustomServiceSelection(double batteryCost, ArrayList<Double> costData, ArrayList<Double> costWlan,
                                  ArrayList<Double> costUtilities) {
        if (costUtilities == null || costUtilities.size() < 1 || costData.size() < 1 || costWlan.size() < 1) {
            throw new RuntimeException("Please add atleast 1 cost to Data, WLAN and Utility");
        }
        this.batteryCost = batteryCost; //make sure you add battery field to UI, user enters battery level
        this.costData = costData;
        this.costWlan = costWlan;
        this.costUtilities = costUtilities;
        //this.services = services;
    }

    public double getGoodness(boolean[] bits) {
        double utility = 0.0;
        double rcost = 0.0;
        ArrayList<Double> resourceCost = new ArrayList<Double>();

        for(Double i : costData){

        }

        for (int x = 0; x <= NUM_DIMENSIONS; x++) { //for each resource that is a bit
            if (bits[x] == alwaysOn) {  //if a utility cost of a service is 100, return -2000.0
                return -2000;
            }

            if (bits[DATA] && bits[WLAN]) {
                return -500;
            }
            if (!bits[DATA] || bits[WLAN]) {
                return -450; //particle goodness always returns this??
            }
            if (bits[DATA]) {
                resourceCost = costData;
            } else if (bits[WLAN]) {
                resourceCost = costWlan;
            }

            for (int i = 0; i <= NUM_DIMENSIONS; i++) { //for each service the user enters
                if (bits[i]) {
                    utility += costUtilities.get(i);
                    rcost += resourceCost.get(i);
                }
            }
            if (rcost < batteryCost) {
                return utility;
            }

        }
        return utility * 0.50;
    }
    }

I want the num_dimensions to be 2 (WLAN and DATA) plus the number of services the user enters in the main activity. So if they enter 4 services, then 6 dimensions altogether.Then I want to assign an 'int' value to these services like this...

   public static final int Facebook = 2;
   public static final int Twitter = 3;
   public static final int ClockApp = 4;

When that is done, I want to pass it onto the getGoodness() function which will take these values as bits in the number of dimensions, so Facebook will be the 3rd bit in the dimensions. Any help or advice would be great, I m a uni student undertaking this as a project.

EDIT: I have now implemented a hashmap in the getGoodness() function. My code now looks like this...

    public double getGoodness(boolean[] bits) {
    double utility = 0.0;
    double rcost = 0.0;
    ArrayList<Double> resourceCost = new ArrayList<Double>();

    for(int i = 2; i <= NUM_DIMENSIONS; i++) { //hashmap that stores the   service names with an int value
        for(int k = 0; k <= numOfServices; k++) {
            serviceMap.put(i, serviceNames.get(k));
        }

I need the first 2 bits of NUM_DIMENSIONS to be WLAN and DATA. So for each service the user enters, the integer value assigned to them goes up by 1 starting at 2. So... (2, Facebook), (3, Twitter), (4, Uber) etc. Now my next problem is, passing these down to the getGoodness() function, I have an arraylist from the main UI activity that takes a utility(priority) cost from 0-100 of each service. This is called costUtilities, I want the bits that contain a utility of 80.0-100.0 (double) to return me a value of -2000 if it isn't on. If you can help with this, that would be great, if not, thank you for the help you've given so far, and wish me luck in my final year individual project on PSO :)

Body:
Rajat answer is correct. You can also creat a JSON Object, and insert the labels that you want, and after that include it in the hashMap.

JSON example:

public static JSONObject constructEHRJSON(int sessionID, String EHR) {
  {
    JSONObject JSONobj = new JSONObject();

    try {

        JSONobj.put("1", sessionID);
        JSONobj.put("2", EHR);
    } catch (JSONException e) {
        /
    }
    return JSONobj;

}


问:
Find out if a business is currently open in T-SQL
I am storing business opening hours in this table. Businesses can have multiple opening hours in the same day. The closing time can be after midnight of the current day.

```<code>CREATE TABLE [Process].[OpeningHours](
    [openinghoursid] [int] IDENTITY(1,1) NOT NULL,
    [businessid] [int] NOT NULL,
    [daynumber] [int] NOT NULL,
    [opentime] [time](7) NOT NULL,
    [duration] [int] NOT NULL,
    [closetime]  AS (dateadd(minute,[duration],[opentime])
)
</code>```

Sample data in this table includes:

```<code>INSERT [Process].[OpeningHours]
([openinghoursid], [businessid], [daynumber], [opentime], [duration])
VALUES (79, 18, 2, CAST(N'12:00:00' AS Time), 165),
       (80, 18, 2, CAST(N'18:00:00' AS Time), 240),
       (81, 18, 3, CAST(N'12:00:00' AS Time), 165),
       (82, 18, 3, CAST(N'18:00:00' AS Time), 240),
       (83, 18, 4, CAST(N'12:00:00' AS Time), 165),
       (84, 18, 4, CAST(N'18:00:00' AS Time), 240),
       (85, 18, 5, CAST(N'12:00:00' AS Time), 165),
       (86, 18, 5, CAST(N'18:00:00' AS Time), 240),
       (87, 18, 6, CAST(N'12:00:00' AS Time), 165),
       (88, 18, 6, CAST(N'18:00:00' AS Time), 300),
       (89, 18, 7, CAST(N'12:00:00' AS Time), 165),
       (90, 18, 7, CAST(N'18:00:00' AS Time), 600),
       (91, 18, 1, CAST(N'12:00:00' AS Time), 180);
</code>```

Now I want to create a function which returns if a business is currently open or closed.

```<code>CREATE FUNCTION [Process].[ufnIsSpaceOpen](@businessid int)
RETURNS BIT
AS
BEGIN
    DECLARE @currentdatetime DATETIME = GETDATE();
    DECLARE @dayofweek INT = DATEPART(dw,@currentdatetime);
    DECLARE @currentdate DATETIME = CONVERT(DATE, @currentdatetime);
    DECLARE @isopen BIT;

    SELECT @isopen = COUNT(*)
    FROM Process.OpeningHours
    WHERE
    daynumber = @dayofweek
    AND businessid = @businessid
    AND
    (
        @currentdatetime >= @currentdate + CONVERT(DATETIME, opentime)

        AND

        @currentdatetime <=
            CASE
                WHEN closetime < '00:00:00' THEN @currentdate + CONVERT(DATETIME, closetime)
                ELSE DATEADD(DAY,1,@currentdate) + CONVERT(DATETIME, closetime)
            END
    );

    RETURN @isopen;

END;

GO
</code>```

I am using the COUNT() to see if any of the rows matches the condition, if 0 match it means it is closed, if COUNT() is greater than 0 it is open. This works when the closing time is within the same day, however it does not work when the closing time is after midnight or if the current time is after midnight.

Any idea how I can fix it?

EDIT: Thank you for all the responses. Finally I went ahead with @DenisRubashkin's solution. For anyone interested this is the final function I used:

```<code>CREATE FUNCTION [Process].[ufnIsSpaceOpen](@businessid int)
RETURNS BIT
AS
BEGIN

    DECLARE @isopen BIT;
    DECLARE @Date DATETIME = GETDATE();

    SELECT @isopen = COUNT(*)
    FROM
    (
        SELECT (CAST(CAST(@Date AS DATE) AS DATETIME) + CAST(h.opentime AS DATETIME)) AS Opened,
            DATEADD(mi, h.duration, (CAST(CAST(@Date AS DATE) AS DATETIME) + CAST(h.opentime AS DATETIME))) AS Closed
        FROM Process.OpeningHours h
        WHERE h.daynumber = DATEPART(dw, @Date)
        AND businessid = @businessid

        UNION

        SELECT (CAST(DATEADD(day, -1, CAST(@Date AS DATE)) AS DATETIME) + CAST(h.opentime AS DATETIME)) AS Opened,
            DATEADD(mi, h.duration, (CAST(DATEADD(day, -1, CAST(@Date AS DATE)) AS DATETIME) + CAST(h.opentime AS DATETIME))) AS Closed
        FROM Process.OpeningHours h
        WHERE h.daynumber = CASE WHEN DATEPART(dw, @Date) = 1
                                 THEN 7
                                 ELSE DATEPART(dw, @Date) - 1
                                 END
        AND businessid = @businessid
    ) w
    WHERE @Date BETWEEN Opened AND Closed

    RETURN @isopen;

END;
</code>```

答:
This should do the trick for you

```<code>SELECT  @isopen = COUNT(*)
FROM [Process].[OpeningHours]
WHERE daynumber = @dayofweek
    AND businessid = @businessid
    AND @CheckDateTime BETWEEN CAST(CONCAT('1900-01-01 ',(CAST([opentime] AS TIME))) AS DATETIME2) AND DATEADD(minute,[duration],CAST(CONCAT('1900-01-01 ',(CAST([opentime] AS TIME))) AS DATETIME2))
</code>```

Test Data

```<code>DECLARE @currentdatetime DATETIME = '2017-03-30 13:01:51.550';
DECLARE @dayofweek INT = DATEPART(dw, @currentdatetime);
DECLARE @currentTime VARCHAR(16) = CAST(@currentdatetime AS Time)
DECLARE @CheckDateTime DATETIME2 = CAST(CONCAT('1900-01-01 ',(CAST(@currentTime AS TIME))) AS DATETIME2)
DECLARE @isopen BIT;
DECLARE @businessid INT = 18

DECLARE @BusinessOpeningHours TABLE ([openinghoursid] [int] NOT NULL,[businessid] INT NOT NULL,
    [daynumber] [int] NOT NULL,
    [opentime] [time](7) NOT NULL,
    [duration] [int] NOT NULL,
    [closetime] [time] NOT NULL)

INSERT INTO @BusinessOpeningHours([openinghoursid], [businessid], [daynumber], [opentime], [duration],[closetime])
SELECT 79, 18, 2, CAST(N'12:00:00' AS Time), 165, dateadd(minute,165,CAST(N'12:00:00' AS Time)) UNION ALL
SELECT 80, 18, 2, CAST(N'18:00:00' AS Time), 240, dateadd(minute,240,CAST(N'18:00:00' AS Time)) UNION ALL
SELECT 81, 18, 3, CAST(N'12:00:00' AS Time), 165, dateadd(minute,165,CAST(N'12:00:00' AS Time)) UNION ALL
SELECT 82, 18, 3, CAST(N'18:00:00' AS Time), 240, dateadd(minute,240,CAST(N'18:00:00' AS Time)) UNION ALL
SELECT 83, 18, 4, CAST(N'12:00:00' AS Time), 165, dateadd(minute,165,CAST(N'12:00:00' AS Time)) UNION ALL
SELECT 84, 18, 4, CAST(N'18:00:00' AS Time), 240, dateadd(minute,240,CAST(N'18:00:00' AS Time)) UNION ALL
SELECT 85, 18, 5, CAST(N'12:00:00' AS Time), 165, dateadd(minute,165,CAST(N'12:00:00' AS Time)) UNION ALL
SELECT 86, 18, 5, CAST(N'18:00:00' AS Time), 240, dateadd(minute,240,CAST(N'18:00:00' AS Time)) UNION ALL
SELECT 87, 18, 6, CAST(N'12:00:00' AS Time), 165, dateadd(minute,165,CAST(N'12:00:00' AS Time)) UNION ALL
SELECT 88, 18, 6, CAST(N'18:00:00' AS Time), 300, dateadd(minute,300,CAST(N'18:00:00' AS Time)) UNION ALL
SELECT 89, 18, 7, CAST(N'12:00:00' AS Time), 165, dateadd(minute,165,CAST(N'12:00:00' AS Time)) UNION ALL
SELECT 90, 18, 7, CAST(N'18:00:00' AS Time), 600, dateadd(minute,600,CAST(N'18:00:00' AS Time)) UNION ALL
SELECT 91, 18, 1, CAST(N'12:00:00' AS Time), 180, dateadd(minute,180,CAST(N'12:00:00' AS Time))

SELECT  @isopen = COUNT(*)
FROM @BusinessOpeningHours
WHERE daynumber = @dayofweek
    AND businessid = @businessid
    AND @CheckDateTime BETWEEN CAST(CONCAT('1900-01-01 ',(CAST([opentime] AS TIME))) AS DATETIME2) AND DATEADD(minute,[duration],CAST(CONCAT('1900-01-01 ',(CAST([opentime] AS TIME))) AS DATETIME2))

SELECT @isopen;
</code>```

Body:
I am storing business opening hours in this table. Businesses can have multiple opening hours in the same day. The closing time can be after midnight of the current day.

CREATE TABLE [Process].[OpeningHours](
    [openinghoursid] [int] IDENTITY(1,1) NOT NULL,
    [businessid] [int] NOT NULL,
    [daynumber] [int] NOT NULL,
    [opentime] [time](7) NOT NULL,
    [duration] [int] NOT NULL,
    [closetime]  AS (dateadd(minute,[duration],[opentime])
)

Sample data in this table includes:

INSERT [Process].[OpeningHours]
([openinghoursid], [businessid], [daynumber], [opentime], [duration])
VALUES (79, 18, 2, CAST(N'12:00:00' AS Time), 165),
       (80, 18, 2, CAST(N'18:00:00' AS Time), 240),
       (81, 18, 3, CAST(N'12:00:00' AS Time), 165),
       (82, 18, 3, CAST(N'18:00:00' AS Time), 240),
       (83, 18, 4, CAST(N'12:00:00' AS Time), 165),
       (84, 18, 4, CAST(N'18:00:00' AS Time), 240),
       (85, 18, 5, CAST(N'12:00:00' AS Time), 165),
       (86, 18, 5, CAST(N'18:00:00' AS Time), 240),
       (87, 18, 6, CAST(N'12:00:00' AS Time), 165),
       (88, 18, 6, CAST(N'18:00:00' AS Time), 300),
       (89, 18, 7, CAST(N'12:00:00' AS Time), 165),
       (90, 18, 7, CAST(N'18:00:00' AS Time), 600),
       (91, 18, 1, CAST(N'12:00:00' AS Time), 180);

Now I want to create a function which returns if a business is currently open or closed.

CREATE FUNCTION [Process].[ufnIsSpaceOpen](@businessid int)
RETURNS BIT
AS
BEGIN
    DECLARE @currentdatetime DATETIME = GETDATE();
    DECLARE @dayofweek INT = DATEPART(dw,@currentdatetime);
    DECLARE @currentdate DATETIME = CONVERT(DATE, @currentdatetime);
    DECLARE @isopen BIT;

    SELECT @isopen = COUNT(*)
    FROM Process.OpeningHours
    WHERE
    daynumber = @dayofweek
    AND businessid = @businessid
    AND
    (
        @currentdatetime >= @currentdate + CONVERT(DATETIME, opentime)

        AND

        @currentdatetime <=
            CASE
                WHEN closetime < '00:00:00' THEN @currentdate + CONVERT(DATETIME, closetime)
                ELSE DATEADD(DAY,1,@currentdate) + CONVERT(DATETIME, closetime)
            END
    );

    RETURN @isopen;

END;

GO

I am using the COUNT() to see if any of the rows matches the condition, if 0 match it means it is closed, if COUNT() is greater than 0 it is open. This works when the closing time is within the same day, however it does not work when the closing time is after midnight or if the current time is after midnight.

Any idea how I can fix it?

EDIT: Thank you for all the responses. Finally I went ahead with @DenisRubashkin's solution. For anyone interested this is the final function I used:

CREATE FUNCTION [Process].[ufnIsSpaceOpen](@businessid int)
RETURNS BIT
AS
BEGIN

    DECLARE @isopen BIT;
    DECLARE @Date DATETIME = GETDATE();

    SELECT @isopen = COUNT(*)
    FROM
    (
        SELECT (CAST(CAST(@Date AS DATE) AS DATETIME) + CAST(h.opentime AS DATETIME)) AS Opened,
            DATEADD(mi, h.duration, (CAST(CAST(@Date AS DATE) AS DATETIME) + CAST(h.opentime AS DATETIME))) AS Closed
        FROM Process.OpeningHours h
        WHERE h.daynumber = DATEPART(dw, @Date)
        AND businessid = @businessid

        UNION

        SELECT (CAST(DATEADD(day, -1, CAST(@Date AS DATE)) AS DATETIME) + CAST(h.opentime AS DATETIME)) AS Opened,
            DATEADD(mi, h.duration, (CAST(DATEADD(day, -1, CAST(@Date AS DATE)) AS DATETIME) + CAST(h.opentime AS DATETIME))) AS Closed
        FROM Process.OpeningHours h
        WHERE h.daynumber = CASE WHEN DATEPART(dw, @Date) = 1
                                 THEN 7
                                 ELSE DATEPART(dw, @Date) - 1
                                 END
        AND businessid = @businessid
    ) w
    WHERE @Date BETWEEN Opened AND Closed

    RETURN @isopen;

END;

Body:
This should do the trick for you

SELECT  @isopen = COUNT(*)
FROM [Process].[OpeningHours]
WHERE daynumber = @dayofweek
    AND businessid = @businessid
    AND @CheckDateTime BETWEEN CAST(CONCAT('1900-01-01 ',(CAST([opentime] AS TIME))) AS DATETIME2) AND DATEADD(minute,[duration],CAST(CONCAT('1900-01-01 ',(CAST([opentime] AS TIME))) AS DATETIME2))

Test Data

DECLARE @currentdatetime DATETIME = '2017-03-30 13:01:51.550';
DECLARE @dayofweek INT = DATEPART(dw, @currentdatetime);
DECLARE @currentTime VARCHAR(16) = CAST(@currentdatetime AS Time)
DECLARE @CheckDateTime DATETIME2 = CAST(CONCAT('1900-01-01 ',(CAST(@currentTime AS TIME))) AS DATETIME2)
DECLARE @isopen BIT;
DECLARE @businessid INT = 18

DECLARE @BusinessOpeningHours TABLE ([openinghoursid] [int] NOT NULL,[businessid] INT NOT NULL,
    [daynumber] [int] NOT NULL,
    [opentime] [time](7) NOT NULL,
    [duration] [int] NOT NULL,
    [closetime] [time] NOT NULL)

INSERT INTO @BusinessOpeningHours([openinghoursid], [businessid], [daynumber], [opentime], [duration],[closetime])
SELECT 79, 18, 2, CAST(N'12:00:00' AS Time), 165, dateadd(minute,165,CAST(N'12:00:00' AS Time)) UNION ALL
SELECT 80, 18, 2, CAST(N'18:00:00' AS Time), 240, dateadd(minute,240,CAST(N'18:00:00' AS Time)) UNION ALL
SELECT 81, 18, 3, CAST(N'12:00:00' AS Time), 165, dateadd(minute,165,CAST(N'12:00:00' AS Time)) UNION ALL
SELECT 82, 18, 3, CAST(N'18:00:00' AS Time), 240, dateadd(minute,240,CAST(N'18:00:00' AS Time)) UNION ALL
SELECT 83, 18, 4, CAST(N'12:00:00' AS Time), 165, dateadd(minute,165,CAST(N'12:00:00' AS Time)) UNION ALL
SELECT 84, 18, 4, CAST(N'18:00:00' AS Time), 240, dateadd(minute,240,CAST(N'18:00:00' AS Time)) UNION ALL
SELECT 85, 18, 5, CAST(N'12:00:00' AS Time), 165, dateadd(minute,165,CAST(N'12:00:00' AS Time)) UNION ALL
SELECT 86, 18, 5, CAST(N'18:00:00' AS Time), 240, dateadd(minute,240,CAST(N'18:00:00' AS Time)) UNION ALL
SELECT 87, 18, 6, CAST(N'12:00:00' AS Time), 165, dateadd(minute,165,CAST(N'12:00:00' AS Time)) UNION ALL
SELECT 88, 18, 6, CAST(N'18:00:00' AS Time), 300, dateadd(minute,300,CAST(N'18:00:00' AS Time)) UNION ALL
SELECT 89, 18, 7, CAST(N'12:00:00' AS Time), 165, dateadd(minute,165,CAST(N'12:00:00' AS Time)) UNION ALL
SELECT 90, 18, 7, CAST(N'18:00:00' AS Time), 600, dateadd(minute,600,CAST(N'18:00:00' AS Time)) UNION ALL
SELECT 91, 18, 1, CAST(N'12:00:00' AS Time), 180, dateadd(minute,180,CAST(N'12:00:00' AS Time))

SELECT  @isopen = COUNT(*)
FROM @BusinessOpeningHours
WHERE daynumber = @dayofweek
    AND businessid = @businessid
    AND @CheckDateTime BETWEEN CAST(CONCAT('1900-01-01 ',(CAST([opentime] AS TIME))) AS DATETIME2) AND DATEADD(minute,[duration],CAST(CONCAT('1900-01-01 ',(CAST([opentime] AS TIME))) AS DATETIME2))

SELECT @isopen;


问:
Code browsing: How to find out which function a function pointer is pointing to?
I'm having a huge C code base to browse and understand. I'm doing it using cscope on vim.

But I'm almost clueless when it comes to function pointers as to where they are pointing to. Is there a easy way to find out what callbacks are registered?

Can we find it out using cscope itself ?

答: gd go local declaration and gD go to global declaration. If you want to see the declaration in a new window try: Ctrl-w gD for example.


问:
Has anyone managed to make Asynchronous advantage actor critic work with Mujoco experiments?
I'm using an open source version of a3c implementation in Tensorflow which works reasonably well for atari 2600 experiments. However, when I modify the network for Mujoco, as outlined in the paper, the network refuses to learn anything meaningful. Has anyone managed to make any open source implementations of a3c work with continuous domain problems, for example mujoco?</p>

答:
I have done a continuous action of Pendulum and it works well.

Firstly, you will build your neural network and output mean (mu) and standard deviation (sigma) for selecting an action.

The essential part of the continuous action is to include a normal distribution. I'm using tensorflow, so the code is looks like:

```<code>normal_dist = tf.contrib.distributions.Normal(mu, sigma)
log_prob = normal_dist.log_prob(action)
exp_v = log_prob * td_error
entropy = normal_dist.entropy()  # encourage exploration
exp_v = tf.reduce_sum(0.01 * entropy + exp_v)
actor_loss = -exp_v
</code>```

When you wanna sample an action, use the function tensorflow gives:

```<code>sampled_action = normal_dist.sample(1)
</code>```

The full code of Pendulum can be found in my Github. https://github.com/MorvanZhou/tutorials/blob/master/Reinforcement_learning_TUT/10_A3C/A3C_continuous_action.py

Body:
I have done a continuous action of Pendulum and it works well.

Firstly, you will build your neural network and output mean (mu) and standard deviation (sigma) for selecting an action.

The essential part of the continuous action is to include a normal distribution. I'm using tensorflow, so the code is looks like:

normal_dist = tf.contrib.distributions.Normal(mu, sigma)
log_prob = normal_dist.log_prob(action)
exp_v = log_prob * td_error
entropy = normal_dist.entropy()  # encourage exploration
exp_v = tf.reduce_sum(0.01 * entropy + exp_v)
actor_loss = -exp_v

When you wanna sample an action, use the function tensorflow gives:

sampled_action = normal_dist.sample(1)

The full code of Pendulum can be found in my Github. https://github.com/MorvanZhou/tutorials/blob/master/Reinforcement_learning_TUT/10_A3C/A3C_continuous_action.py


问:
Decrypting a token in NodeJS with a JCEKS keystore
In this scenario I'm getting token encrypted at origin with the one secret key in a JCEKS keystore. The token goes into a NodeJS server, where it should be unencrypted to use the data in there. As far as I understand, the private key to decrypt the token cannot be extracted from that format, so decrypting it simply using the crypto module won't do. I've played around with node-keytool, and gotten as far as listing the keys, based on the example here: https://github.com/FrankGrimm/node-keytool/blob/master/examples/listcontent.js.

However, I'm at a complete loss as how to use that module to decrypt the token. Any suggestions on how to do so, whether using that module or another, would be greatly appreciated.

答:
It seems like it can't be done, or at least not without a lot of work. Easier to write a decrypter in Java and then make a module in Node, like so:

const exec = require('child_process').exec;
const fs = require('fs');

```<code>const start = function (data, resolve, reject) {
    let child = exec('java -jar java/out/artifacts/decrypter_jar/decrypter.jar ' + data,
    function (error, stdout, stderr){
        console.log('Output -> ' + stdout);
        if(stdout){
            resolve(stdout);
        }
        else {
            reject('Empty response from JAR');
            return;
        }
        if(error !== null){
            console.log("Error -> "+error);
            reject(error);
        }
    });

};

module.exports = {start};
</code>```

Body:
It seems like it can't be done, or at least not without a lot of work. Easier to write a decrypter in Java and then make a module in Node, like so:

const exec = require('child_process').exec;
const fs = require('fs');

const start = function (data, resolve, reject) {
    let child = exec('java -jar java/out/artifacts/decrypter_jar/decrypter.jar ' + data,
    function (error, stdout, stderr){
        console.log('Output -> ' + stdout);
        if(stdout){
            resolve(stdout);
        }
        else {
            reject('Empty response from JAR');
            return;
        }
        if(error !== null){
            console.log("Error -> "+error);
            reject(error);
        }
    });

};

module.exports = {start};


问:
Need a Ruby gem for Cucumber test automation for manipulation of the Excel GUI(ribon,side menus,etc)
Am attempting to automate excel , involves manipulation of the Excel GUI(ribbon,side menus,clicking buttons,drop down,etc) to achieve this functionality is one of the more complicated features of the windows desktop application to be automated. Here implementing with Ruby/Cucumber test automation framework.Does anyone know of any ruby gem (or combination of gems) that integrates well with windows desktop applications?

Any and all help is much appreciated.

Thank you

答:
You can use "roo" gem to handle excelsheet. refer link :-
https://github.com/roo-rb/roo

Thanks,
Kapil Chothe


问:
Max value 3D array in Python
We have a 3D array (671, 9066, 2):

671 IdUser (bloc)

For each 671 users we have 9066 (rows) movies and proba associated (2 columns)

Example of two columns for 1 user:

```<code>Proba                Idmovie
[  6.93933334e-02,   1.00000000e+00],
[  8.50563031e-02,   2.00000000e+00],
....
[  2.95071098e-02,   3.00000000e+00]
</code>```

We need the maximum proba (here 8.50563031e-02) and the value of the second column associated (here 2.00000000e+00). This for each 671 users!

Thank you very much

答:
for sure there is a smarter way but my approach would be:</p>

```<code>import numpy as np

x = np.random.random((3,3,2))
print(x)

for user in x:
    maximum = np.max(user[:,0])
    index = np.where(user[:,0]==maximum)

    print(user[index])
</code>```

Title: Max value 3D array in Python

Body:
We have a 3D array (671, 9066, 2):

671 IdUser (bloc)

For each 671 users we have 9066 (rows) movies and proba associated (2 columns)

Example of two columns for 1 user:

Proba                Idmovie
[  6.93933334e-02,   1.00000000e+00],
[  8.50563031e-02,   2.00000000e+00],
....
[  2.95071098e-02,   3.00000000e+00]

We need the maximum proba (here 8.50563031e-02) and the value of the second column associated (here 2.00000000e+00). This for each 671 users!

Thank you very much

Body:
for sure there is a smarter way but my approach would be:

import numpy as np

x = np.random.random((3,3,2))
print(x)

for user in x:
    maximum = np.max(user[:,0])
    index = np.where(user[:,0]==maximum)

    print(user[index])

ContentLicense: CC BY-SA 4.0


问:
Send form data via AJAX to multiple PHP files
So, i have no clue if what i want to do is even possible, but i tried and failed ;P

        ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form method="post" id="submitdata" name="submitdata">
                                <div class="row uniform">
                                    <div class="12u 12u$">
                                        <input type="text" name="datefrom" id="datefrom" value="" placeholder="From" />
                                    </div>
                                    <div class="12u 12u$">
                                        <input type="text" name="dateto" id="dateto" value="" placeholder="To" />
                                    </div>
                                    <div class="12u$">
                                        <div class="select-wrapper">
                                            <select name="dropdown" id="dropdown">
                                                <option value="0">- Choose -</option>
                                                <option value="1">1</option>
                                                <option value="2">2</option>
                                                <option value="3">3</option>
                                                <option value="4">4</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="12u$">
                                        <ul class="actions">
                                            <li><input type="submit" id="btnSubmit" value="Submit" class="special" /></li>
                                            <li><input type="reset" value="Reset" /></li>
                                        </ul>
                                    </div>
                                </div>
                            </form></code>```

I want to send the data to different files, depending on what the user chooses in the form dropdown (if that is possible).
I get the alerts and everything is fine but it just jumps into the other "elseif's" even tho the value of dropdown is "0".

Any idea how to solve this?

答:
I found the solution eventually:

                if(!datumvon.value){
                    alert("Watch out");
                }

                else if(dropdown === "0"){
                    alert("Do Step 1 first");

                }else if(dropdown >= "1") {
                    $.ajax({
                        type: 'post',
                        url: 'showData.php',
                        data: {
                            datumvon: datumvon,
                            datumbis: datumbis,
                            dropdown: dropdown
                        },
                        success: function () {
                            $('#inner').load('#inner');
                        }

                    });

                }else {
                    alert("Error");
                }
                return false;```

The problem was some kind of syntax error in the javascript part. Thanks for the help

Body:
So, i have no clue if what i want to do is even possible, but i tried and failed ;P

<form method="post" id="submitdata" name="submitdata">

                                        <input type="text" name="datefrom" id="datefrom" value="" placeholder="From" />

                                        <input type="text" name="dateto" id="dateto" value="" placeholder="To" />

                                            <select name="dropdown" id="dropdown">
                                                <option value="0">- Choose -</option>
                                                <option value="1">1</option>
                                                <option value="2">2</option>
                                                <option value="3">3</option>
                                                <option value="4">4</option>
                                            </select>

<input type="submit" id="btnSubmit" value="Submit" class="special" />

<input type="reset" value="Reset" />

                            </form>

I want to send the data to different files, depending on what the user chooses in the form dropdown (if that is possible).
I get the alerts and everything is fine but it just jumps into the other "elseif's" even tho the value of dropdown is "0".

Any idea how to solve this?

Body:
I found the solution eventually:

                if(!datumvon.value){
                    alert("Watch out");
                }

                else if(dropdown === "0"){
                    alert("Do Step 1 first");

                }else if(dropdown >= "1") {
                    $.ajax({
                        type: 'post',
                        url: 'showData.php',
                        data: {
                            datumvon: datumvon,
                            datumbis: datumbis,
                            dropdown: dropdown
                        },
                        success: function () {
                            $('#inner').load('#inner');
                        }

                    });

                }else {
                    alert("Error");
                }
                return false;

The problem was some kind of syntax error in the javascript part. Thanks for the help


问:
Override template in django admin
I'm using Django 1.11

I was able to extend/override one template called change_form.html

I placed this file under /templates/admin/my_app/my_model/

For this one I extended and changed one block, like in the example in django docs

I was not able to override one template called submit_line.html

I tried placing it under /templates/admin/, /templates/admin/my_app/, and /templates/admin/my_app/my_model/. None worked.

I edited the file under django/contrib and it worked, but I don't want to change that file. It was just to see if the content was showing.

I just want to add one button to the template, so the user can download one XML file.

答:
After some tests and research here is the solution.

First, underneath /templates/admin/my_app/my_model/ copy-paste the submit_line.html from django/contrib/admin/templates/admin/.

Change submit_line.html and add any urls you like. Say:

```<code><!-- submit_line.html -->

{% load i18n admin_urls %}
<div class="submit-row">
{% if show_save %}<input type="submit" value="{% trans 'Save' %}" class="default" name="_save" />{% endif %}
{% if show_delete_link %}
    {% url opts|admin_urlname:'delete' original.pk|admin_urlquote as delete_url %}
    <p class="deletelink-box"><a href="{% add_preserved_filters delete_url %}" class="deletelink">{% trans "Delete" %}</a></p>
{% endif %}

<!-- NEW SUBMIT INPUTS -->
<input type="submit" value="TEST" name="_saveasnewss" />
<input type="submit" value="TEST 2" name="_saveasnews" />
<!-- END NEW SUBMIT INPUTS -->

{% if show_save_as_new %}<input type="submit" value="{% trans 'Save as new' %}" name="_saveasnew" />{% endif %}
{% if show_save_and_add_another %}<input type="submit" value="{% trans 'Save and add another' %}" name="_addanother" />{% endif %}
{% if show_save_and_continue %}<input type="submit" value="{% trans 'Save and continue editing' %}" name="_continue" />{% endif %}
</div>
</code>```

We're copy-pasting it because there aren't any {% block %} tags inside the change_form.html to override.

Further on, inside the change_form.html, add these:

```<code><!-- change_form.html -->

{% extends "admin/change_form.html" %}

{% load my_app_tags %} /* Change "my_app" to your app name that will contain the 'submit_row' template tag */

OTHER OVERRIDES HERE

{% block submit_buttons_bottom %}{% submit_row %}{% endblock %}
</code>```

Finally, in your app's templatetags, add this template tag:

```<code># my_app/templatetags/my_app_tags.py

from django.contrib.admin.templatetags.admin_modify import submit_row
from django.template.loader import get_template
from django import template

# this would be the path to your "submit_line.html"
t = get_template('admin/my_app/my_model/submit_line.html')
register = template.Library()
register.inclusion_tag(t, takes_context=True)(submit_row)
</code>```

That's it! Now you should see these extra <input type="submit" /> only under my_model add/change page. If you want them globally just move submit_line.html from where it is to templates/admin/. Don't forget to update the paths inside my_app/templatetags/my_app_tags.py too.

Title: Override template in django admin

Body:
After some tests and research here is the solution.

First, underneath /templates/admin/my_app/my_model/ copy-paste the submit_line.html from django/contrib/admin/templates/admin/.

Change submit_line.html and add any urls you like. Say:

<!-- submit_line.html -->

{% load i18n admin_urls %}
<div class="submit-row">
{% if show_save %}<input type="submit" value="{% trans 'Save' %}" class="default" name="_save" />{% endif %}
{% if show_delete_link %}
    {% url opts|admin_urlname:'delete' original.pk|admin_urlquote as delete_url %}
    <p class="deletelink-box"><a href="{% add_preserved_filters delete_url %}" class="deletelink">{% trans "Delete" %}</a></p>
{% endif %}

<!-- NEW SUBMIT INPUTS -->
<input type="submit" value="TEST" name="_saveasnewss" />
<input type="submit" value="TEST 2" name="_saveasnews" />
<!-- END NEW SUBMIT INPUTS -->

{% if show_save_as_new %}<input type="submit" value="{% trans 'Save as new' %}" name="_saveasnew" />{% endif %}
{% if show_save_and_add_another %}<input type="submit" value="{% trans 'Save and add another' %}" name="_addanother" />{% endif %}
{% if show_save_and_continue %}<input type="submit" value="{% trans 'Save and continue editing' %}" name="_continue" />{% endif %}
</div>

We're copy-pasting it because there aren't any {% block %} tags inside the change_form.html to override.

Further on, inside the change_form.html, add these:

<!-- change_form.html -->

{% extends "admin/change_form.html" %}

{% load my_app_tags %} /* Change "my_app" to your app name that will contain the 'submit_row' template tag */

OTHER OVERRIDES HERE

{% block submit_buttons_bottom %}{% submit_row %}{% endblock %}

Finally, in your app's templatetags, add this template tag:

# my_app/templatetags/my_app_tags.py

from django.contrib.admin.templatetags.admin_modify import submit_row
from django.template.loader import get_template
from django import template

# this would be the path to your "submit_line.html"
t = get_template('admin/my_app/my_model/submit_line.html')
register = template.Library()
register.inclusion_tag(t, takes_context=True)(submit_row)

That's it! Now you should see these extra <input type="submit" /> only under my_model add/change page. If you want them globally just move submit_line.html from where it is to templates/admin/. Don't forget to update the paths inside my_app/templatetags/my_app_tags.py too.


问:
Swift AVFoundation in playground not outputting sound
My Morse code translator will not output the sound as it should. I have tested the speakers and my methods without this function and it works flawlessly, but it is not in context with the rest of the program. The compiler gives me no errors and the playground does not crash, it just doesn't play sound. Volume and ringer is at full.

```<code>func speakTheCode(message: String) {
    var speaker = AVAudioPlayer()
    let longBeep = #fileLiteral(resourceName: "beep_long.mp3")
    let shortBeep = #fileLiteral(resourceName: "beep_short.mp3")
    let dash = "-"
    let dot = "."
    for character in message.characters {
        if character == dash[dash.startIndex] {
                speaker = try! AVAudioPlayer(contentsOf: longBeep)
                speaker.prepareToPlay()
            print("-")
        }
        else if character == dot[dot.startIndex] {
                speaker = try! AVAudioPlayer(contentsOf: shortBeep)
                speaker.prepareToPlay()
                print(".")
        }
        speaker.play()
    }
}
</code>```

I've been messing around with the code for hours now and nothing is working. What (if anything) am I doing wrong?

答:
@Fahim still it is showing error

class Morse:NSObject, AVAudioPlayerDelegate {
    private var message = ""
    private var dotSound:AVAudioPlayer!
    private var dashSound:AVAudioPlayer!
    private let dash = Character("-")
    private let dot = Character(".")
    private var index:String.Index!

```<code>init(message:String) {
    super.init()
    do {
        if let url = Bundle.main.url(forResource:"beep_short", withExtension:"mp3") {
            self.dotSound = try AVAudioPlayer(contentsOf:url)
            self.dotSound.delegate = self
            self.dotSound.prepareToPlay()
        }
    } catch {
        NSLog("Error loading dot audio!")
    }
    do {
        if let url = Bundle.main.url(forResource:"beep_long", withExtension:"mp3") {
            self.dashSound = try AVAudioPlayer(contentsOf:url)
            self.dashSound.delegate = self
            self.dashSound.prepareToPlay()
        }
    } catch {
        NSLog("Error loading dash audio!")
    }
    self.message = message
    self.index = message.startIndex
}

func playCharacter() {
    let character = message.characters[index]
    NSLog("Character: \(character)")
    if character == dash {
        dashSound.play()
    } else if character == dot {
        dotSound.play()
    }
}

func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    NSLog("Finished playing")
    if index != message.endIndex {
        self.index = message.index(after:index)
        playCharacter()
    }
}
</code>```

}

let m = Morse(message:"...---")
m.playCharacter()

PlaygroundPage.current.needsIndefiniteExecution = true

Body:
My Morse code translator will not output the sound as it should. I have tested the speakers and my methods without this function and it works flawlessly, but it is not in context with the rest of the program. The compiler gives me no errors and the playground does not crash, it just doesn't play sound. Volume and ringer is at full.

func speakTheCode(message: String) {
    var speaker = AVAudioPlayer()
    let longBeep = #fileLiteral(resourceName: "beep_long.mp3")
    let shortBeep = #fileLiteral(resourceName: "beep_short.mp3")
    let dash = "-"
    let dot = "."
    for character in message.characters {
        if character == dash[dash.startIndex] {
                speaker = try! AVAudioPlayer(contentsOf: longBeep)
                speaker.prepareToPlay()
            print("-")
        }
        else if character == dot[dot.startIndex] {
                speaker = try! AVAudioPlayer(contentsOf: shortBeep)
                speaker.prepareToPlay()
                print(".")
        }
        speaker.play()
    }
}

I've been messing around with the code for hours now and nothing is working. What (if anything) am I doing wrong?

Body:
@Fahim still it is showing error

class Morse:NSObject, AVAudioPlayerDelegate {
    private var message = ""
    private var dotSound:AVAudioPlayer!
    private var dashSound:AVAudioPlayer!
    private let dash = Character("-")
    private let dot = Character(".")
    private var index:String.Index!

init(message:String) {
    super.init()
    do {
        if let url = Bundle.main.url(forResource:"beep_short", withExtension:"mp3") {
            self.dotSound = try AVAudioPlayer(contentsOf:url)
            self.dotSound.delegate = self
            self.dotSound.prepareToPlay()
        }
    } catch {
        NSLog("Error loading dot audio!")
    }
    do {
        if let url = Bundle.main.url(forResource:"beep_long", withExtension:"mp3") {
            self.dashSound = try AVAudioPlayer(contentsOf:url)
            self.dashSound.delegate = self
            self.dashSound.prepareToPlay()
        }
    } catch {
        NSLog("Error loading dash audio!")
    }
    self.message = message
    self.index = message.startIndex
}

func playCharacter() {
    let character = message.characters[index]
    NSLog("Character: \(character)")
    if character == dash {
        dashSound.play()
    } else if character == dot {
        dotSound.play()
    }
}

func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    NSLog("Finished playing")
    if index != message.endIndex {
        self.index = message.index(after:index)
        playCharacter()
    }
}

}

let m = Morse(message:"...---")
m.playCharacter()

PlaygroundPage.current.needsIndefiniteExecution = true


问:
Get JSON Data from same file
i am trying to display google charts with data from a MYSQL database. It work's when i am using two seperate files (php/js) but i want to process the data in one file.

Heres what i got:

$table = array();
        $table['cols'] = array(
            array('label' => 'Date', 'type' => 'string'),
            array('label' => 'Meter', 'type' => 'number')
        );
        $rows = array();

        $select->execute();
        while ($result = $select->fetch(PDO::FETCH_ASSOC)) {

            $timestamp = strtotime($result['date']);
            $date = date("d.m.Y - H:i", $timestamp);

            $temp = array();
            $temp[] = array('v' => $date);
            $temp[] = array('v' => $result['meter']);
            $rows[] = array('c' => $temp);
        }
        $table['rows'] = $rows;
        $json = json_encode($table);

        echo $json;

        ?>

        ```

The PHP data gets encoded properly but i dont know how to "send" the data to the javascript part. Is it possible to receive the JSON data in the same file?
When i change async: true to false, it just displays the code from the whole page, with true it displays undefined.

Kind regards,
Skar

答:
when you echo the $json that way

```<code><?php
// ...getting data
?>
<script>
var jsonData = <?php echo $json; ?>;
</script>
<?php
// rest of page...
</code>```

you can use it in javascript later and don't need the ajax anymore.

```<code>//....
chart.draw(jsonData, {width: 1000, height: 240});
//....
</code>```

Title: Get JSON Data from same file

Body:
i am trying to display google charts with data from a MYSQL database. It work's when i am using two seperate files (php/js) but i want to process the data in one file.

Heres what i got:

$table = array();
        $table['cols'] = array(
            array('label' => 'Date', 'type' => 'string'),
            array('label' => 'Meter', 'type' => 'number')
        );
        $rows = array();

        $select->execute();
        while ($result = $select->fetch(PDO::FETCH_ASSOC)) {

            $timestamp = strtotime($result['date']);
            $date = date("d.m.Y - H:i", $timestamp);

            $temp = array();
            $temp[] = array('v' => $date);
            $temp[] = array('v' => $result['meter']);
            $rows[] = array('c' => $temp);
        }
        $table['rows'] = $rows;
        $json = json_encode($table);

        echo $json;

        ?>

The PHP data gets encoded properly but i dont know how to "send" the data to the javascript part. Is it possible to receive the JSON data in the same file?
When i change async: true to false, it just displays the code from the whole page, with true it displays undefined.

Kind regards,
Skar

Body:
when you echo the $json that way

<?php
// ...getting data
?>
<script>
var jsonData = <?php echo $json; ?>;
</script>
<?php
// rest of page...

you can use it in javascript later and don't need the ajax anymore.

//....
chart.draw(jsonData, {width: 1000, height: 240});
//....


问:
Is it ok to still use tables?

Possible Duplicate:

  Why not use tables for layout in HTML?

Just wondering, I thought I have read before that it is bad to use tables, so my question is, is it still acceptable to use tables in development?

答: Use it for tabular data, but not for creating page layout.</p>

ContentLicense: CC BY-SA 2.5

Title: Is it ok to still use tables?


问:
Scale transition in four divs
This question is related to one that i have already created transition-in-div . I didnot get answer for my next issue there so i decided to create new question.
I have four boxes and i want the transition effect in all four boxes.

What i want is whenever i click on any box, the width of that box must increase from its side to the left and right to fit the full width. Right now it only fills some portion of width.
My Code is

```<code><html>
<head>
    <title>Transition</title>
    <style type="text/css">
    .container {
  display: flex;
  justify-content: space-between;
}

.box {
  width:20%;
  height: 200px;
  transition: transform .5s;
  transform-origin: 0 0;
}
#first {
  background-color: red;
}
#second {
  background-color: green;
  transform-origin: 25% 75%;
}
#third {
  background-color: aqua;
  transform-origin: center center;
}
#fourth {
  background-color: blue;
  transform-origin: 100% 0;
}

.scale {
  transform: scaleX(4);
}
    </style>
</head>
<body>
    <div class="container">
        <div id="first" class="box"></div>
        <div id="second" class="box"></div>
        <div id="third" class="box"></div>
        <div id="fourth" class="box"></div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function() {
        var containerWidth = $(".container").width();
        $(".box").click(function() {
          var id = $(this).attr("id");
          $(this).addClass('scale');
        });
    });
</script>
</code>```

Jsfiddle

答:
Here's a solution that will work regardless of the number of boxes or their width. Better to avoid any magic numbers if possible.

Transition width instead of transform. You won't need any transform origins and it will work with any number of boxes regardless of the box size.

To make the width of the other boxes 0. You can add a class to the container.
Than use

```<code>.container.open .box:not(.scale) {
  width: 0;
}
</code>```

to set the width of any box without the class .scale to 0

http://codepen.io/flurrd/pen/xqmwLN

CSS

```<code>.container {
  display: flex;
  justify-content: space-between;
}

.box {
  width: 20%;
  height: 200px;
  transition: width .5s;
  background-color: tomato;
}

.box:nth-child(odd) {
  background-color: aquamarine;
}

.scale {
  width: 100%;
}

.container.open .box:not(.scale) {
  width: 0;
}
</code>```

JS

```<code>var containerWidth = $(".container").width();
$(".box").click(function() {
  var id = $(this).attr("id");
  $(this).toggleClass('scale');
  $(".container").toggleClass('open')
});
</code>```

Title: Scale transition in four divs

Body:
This question is related to one that i have already created transition-in-div . I didnot get answer for my next issue there so i decided to create new question.
I have four boxes and i want the transition effect in all four boxes.

What i want is whenever i click on any box, the width of that box must increase from its side to the left and right to fit the full width. Right now it only fills some portion of width.
My Code is

    <title>Transition</title>

Jsfiddle

Body:
Here's a solution that will work regardless of the number of boxes or their width. Better to avoid any magic numbers if possible.

Transition width instead of transform. You won't need any transform origins and it will work with any number of boxes regardless of the box size.

To make the width of the other boxes 0. You can add a class to the container.
Than use

.container.open .box:not(.scale) {
  width: 0;
}

to set the width of any box without the class .scale to 0

http://codepen.io/flurrd/pen/xqmwLN

CSS

.container {
  display: flex;
  justify-content: space-between;
}

.box {
  width: 20%;
  height: 200px;
  transition: width .5s;
  background-color: tomato;
}

.box:nth-child(odd) {
  background-color: aquamarine;
}

.scale {
  width: 100%;
}

.container.open .box:not(.scale) {
  width: 0;
}

JS

var containerWidth = $(".container").width();
$(".box").click(function() {
  var id = $(this).attr("id");
  $(this).toggleClass('scale');
  $(".container").toggleClass('open')
});


问:
URL Rewrite to remove www and redirect to https using web-config (c# .net)
I have the following code in my web-config to be able to redirect both the URLs with the prefix "www" and non-SSL requests to the https:// mydomain.com because the SSL certificate is registered to the domain without the www

```<code><rewrite>
  <rules>
    <rule name="Remove WWW prefix and redirect to https" >
      <match url="(.*)" ignoreCase="true" />
      <conditions logicalGrouping="MatchAny">
        <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" ignoreCase="true" />
        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
      </conditions>
      <action type="Redirect" redirectType="Permanent" url="https://mydomain.com/{R:1}" />
    </rule>
  </rules>
</rewrite>
</code>```

This is the result:

1) http:// mydomain.com/something --> https:// mydomain.com/something (Correct)

2) http:// www.mydomain.com/something --> https:// mydomain.com/something (Correct)

3) https:// www.mydomain.com/something --> Shows certificate error (There is a problem with this website's security certificate.)

When you select "Continue to this website (not recommended)." on the certificate error page, the url is rewritten correctly (https:// mydomain.com/something)

How can I make sure the certificate error does not show?

Thank you

答:
One way to solve it is to register two separate rules:

Remove www.

Force HTTPS.

```<code><rule name="Remove www" stopProcessing="true">
  <match url="(.*)" negate="false"></match>
  <conditions>
    <add input="{HTTP_HOST}" pattern="^www\.(.*)$" />
  </conditions>
  <action type="Redirect" url="https://{C:1}/{R:1}" appendQueryString="true" redirectType="Permanent" />
</rule>
<rule name="Force HTTPS" enabled="true">
  <match url="(.*)" ignoreCase="false" />
  <conditions>
    <add input="{HTTPS}" pattern="off" />
  </conditions>
  <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" />
</rule>
</code>```

Body:
I have the following code in my web-config to be able to redirect both the URLs with the prefix "www" and non-SSL requests to the https:// mydomain.com because the SSL certificate is registered to the domain without the www

<rewrite>
  <rules>
    <rule name="Remove WWW prefix and redirect to https" >
      <match url="(.*)" ignoreCase="true" />
      <conditions logicalGrouping="MatchAny">
        <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" ignoreCase="true" />
        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
      </conditions>
      <action type="Redirect" redirectType="Permanent" url="https://mydomain.com/{R:1}" />
    </rule>
  </rules>
</rewrite>

This is the result:

1) http:// mydomain.com/something --> https:// mydomain.com/something (Correct)

2) http:// www.mydomain.com/something --> https:// mydomain.com/something (Correct)

3) https:// www.mydomain.com/something --> Shows certificate error (There is a problem with this website's security certificate.)

When you select "Continue to this website (not recommended)." on the certificate error page, the url is rewritten correctly (https:// mydomain.com/something)

How can I make sure the certificate error does not show?

Thank you

Body:
One way to solve it is to register two separate rules:

Remove www.

Force HTTPS.

<rule name="Remove www" stopProcessing="true">
  <match url="(.*)" negate="false"></match>
  <conditions>
    <add input="{HTTP_HOST}" pattern="^www\.(.*)$" />
  </conditions>
  <action type="Redirect" url="https://{C:1}/{R:1}" appendQueryString="true" redirectType="Permanent" />
</rule>
<rule name="Force HTTPS" enabled="true">
  <match url="(.*)" ignoreCase="false" />
  <conditions>
    <add input="{HTTPS}" pattern="off" />
  </conditions>
  <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" />
</rule>


问:
Spring CrudRepository Insert values into mysql database
I want to create a @PostMappingwhich executes an insert statement. Here is my code:

Repository (I have findAllBy functions that are working perfectly). Here is the insert function that obviously is not working. ->

```<code>@Transactional
@Query(value = "INSERT INTO recipes(title, description) VALUES (?1, ?2)", nativeQuery = true)
    void insertRecipes(String title, String description);

@PostMapping(path = "/all/create")
public void addRecipes(@RequestParam("title") String title, @RequestParam(value = "description") String description){
    Recipes recipe = new Recipes();
    recipe.setTitle(title);
    recipe.setDescription(description);
    repo.insertRecipes(recipe.getTitle(), recipe.getDescription());
}
</code>```

I don't mention the recipes id because it's auto incremental. And here is my Entity ->

```<code>@Entity
public class Recipes {
@Column(name = "id")
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(name = "title")
    private String title;

    @Column(name = "description")
    private String description;

    //getters-setters and constructions below.
}
</code>```

My problem is that I'm getting this exception -> java.sql.SQLException: Can not issue data manipulation statements with executeQuery()

Any ideas?
PS. I have done all the connections correctly. All the GET methods are working fine.

答:
Controller

```<code>@RequestMapping(
                value = "/all/create",
                method = RequestMethod.POST,
                consumes = MediaType.APPLICATION_JSON_VALUE,
                produces = MediaType.APPLICATION_JSON_VALUE)
        public ResponseEntity<Recipes> create(
                @RequestBody Recipes recipes) {
            Recipes saved= recipesService.add(recipes);
            return new ResponseEntity<Recipes>(saved, HttpStatus.CREATED);
        }
</code>```

Service

```<code>public Recipes add(Recipes recipes) {

    Recipes save = recipesRepository.save(recipes);
    return save;
}
</code>```

if you are dealing with the JSON, then you can use this and check using Postman

Body:
I want to create a @PostMappingwhich executes an insert statement. Here is my code:

Repository (I have findAllBy functions that are working perfectly). Here is the insert function that obviously is not working. ->

@Transactional
@Query(value = "INSERT INTO recipes(title, description) VALUES (?1, ?2)", nativeQuery = true)
    void insertRecipes(String title, String description);

@PostMapping(path = "/all/create")
public void addRecipes(@RequestParam("title") String title, @RequestParam(value = "description") String description){
    Recipes recipe = new Recipes();
    recipe.setTitle(title);
    recipe.setDescription(description);
    repo.insertRecipes(recipe.getTitle(), recipe.getDescription());
}

I don't mention the recipes id because it's auto incremental. And here is my Entity ->

@Entity
public class Recipes {
@Column(name = "id")
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(name = "title")
    private String title;

    @Column(name = "description")
    private String description;

    //getters-setters and constructions below.
}

My problem is that I'm getting this exception -> java.sql.SQLException: Can not issue data manipulation statements with executeQuery()

Any ideas?
PS. I have done all the connections correctly. All the GET methods are working fine.

Body:
Controller

@RequestMapping(
                value = "/all/create",
                method = RequestMethod.POST,
                consumes = MediaType.APPLICATION_JSON_VALUE,
                produces = MediaType.APPLICATION_JSON_VALUE)
        public ResponseEntity<Recipes> create(
                @RequestBody Recipes recipes) {
            Recipes saved= recipesService.add(recipes);
            return new ResponseEntity<Recipes>(saved, HttpStatus.CREATED);
        }

Service

public Recipes add(Recipes recipes) {

    Recipes save = recipesRepository.save(recipes);
    return save;
}

if you are dealing with the JSON, then you can use this and check using Postman


问:
Javascript click start / stop interval function
I want to start a interval / function if the user clicks on a button and stop that if the user clicks on stop. But somehow it immidietly starts the startRecord function. What am I doing wrong.

HTML:

window.onload = startRecord;

startRecord = document.getElementById('startRecord');
stopRecord = document.getElementById('stopRecord');

function startRecord() {
  startRecord.onclick = generateImg(true);
  startRecord.style.display = "none";
  stopRecord.style.display = "block";
}

function stopRecord() {
  stopRecord.onclick = generateImg(false);
  startRecord.style.display = "block";
  stopRecord.style.display = "none";
}

function generateImg(start) {
  if (start) {
    var startInterval = setInterval(function() {
      console.log("foo")
    }, 1000);
  } else {
    clearInterval(startInterval);
    console.log("stop foo")
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="btn-group">
  <button type="button" class="btn btn-default btn-lg" id="startRecord">
            Start
        </button>
  <button type="button" class="btn btn-default btn-lg" id="stopRecord">
            Stop
        </button>
</div></code>```

答:
remove the onload event, bind event directly to the buttons.
see the node snippet.

btnStartRecord = document.getElementById('startRecord');
btnStopRecord = document.getElementById('stopRecord');

window.onload = function() {
  btnStartRecord.style.display = "block";
  btnStopRecord.style.display = "none";
}

var startInterval;

function startRecord() {
  generateImg(true);
  btnStartRecord.style.display = "none";
  btnStopRecord.style.display = "block";
}

function stopRecord() {
  generateImg(false);
  btnStartRecord.style.display = "block";
  btnStopRecord.style.display = "none";
}

function generateImg(start) {
  if (start) {
    startInterval = setInterval(function() {
      console.log("foo")
    }, 1000);
  } else {
    clearInterval(startInterval);
    console.log("stop foo")
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="btn-group">
  <button type="button" onclick="startRecord()" class="btn btn-default btn-lg" id="startRecord">
            Start
        </button>
  <button type="button" onclick="stopRecord()" class="btn btn-default btn-lg" id="stopRecord">
            Stop
        </button>
</div></code>```

Body:
I want to start a interval / function if the user clicks on a button and stop that if the user clicks on stop. But somehow it immidietly starts the startRecord function. What am I doing wrong.

HTML:

window.onload = startRecord;

startRecord = document.getElementById('startRecord');
stopRecord = document.getElementById('stopRecord');

function startRecord() {
  startRecord.onclick = generateImg(true);
  startRecord.style.display = "none";
  stopRecord.style.display = "block";
}

function stopRecord() {
  stopRecord.onclick = generateImg(false);
  startRecord.style.display = "block";
  stopRecord.style.display = "none";
}

function generateImg(start) {
  if (start) {
    var startInterval = setInterval(function() {
      console.log("foo")
    }, 1000);
  } else {
    clearInterval(startInterval);
    console.log("stop foo")
  }
}

  <button type="button" class="btn btn-default btn-lg" id="startRecord">
            Start
        </button>
  <button type="button" class="btn btn-default btn-lg" id="stopRecord">
            Stop
        </button>

Body:
remove the onload event, bind event directly to the buttons.
see the node snippet.

btnStartRecord = document.getElementById('startRecord');
btnStopRecord = document.getElementById('stopRecord');

window.onload = function() {
  btnStartRecord.style.display = "block";
  btnStopRecord.style.display = "none";
}

var startInterval;

function startRecord() {
  generateImg(true);
  btnStartRecord.style.display = "none";
  btnStopRecord.style.display = "block";
}

function stopRecord() {
  generateImg(false);
  btnStartRecord.style.display = "block";
  btnStopRecord.style.display = "none";
}

function generateImg(start) {
  if (start) {
    startInterval = setInterval(function() {
      console.log("foo")
    }, 1000);
  } else {
    clearInterval(startInterval);
    console.log("stop foo")
  }
}

<div class="btn-group">
  <button type="button" onclick="startRecord()" class="btn btn-default btn-lg" id="startRecord">
            <a href="#" class="btn btn-default glyphicon glyphicon-hand-up">Start</a>
        </button>
  <button type="button" onclick="stopRecord()" class="btn btn-default btn-lg" id="stopRecord">
            <a href="#" class="btn btn-default glyphicon glyphicon-hand-up">Stop</a>
        </button>
</div>


问:
Security header is not valid error message
I'm getting this message

TIMESTAMP=2017-03-29T16:36:41Z&CORRELATIONID=9d5672f086c52&ACK=Failure&VERSION=204&BUILD=31674279&L_ERRORCODE0=10002&L_SHORTMESSAGE0=Security error&L_LONGMESSAGE0=Security header is not valid&L_SEVERITYCODE0=Error

I'm sure that I'm using the right credentials, I've copied them from sandbox account, from View API Signature page.

I'm trying to connect to sandbox environment with the url https://api-3t.sandbox.paypal.com/nvp.

Here is how my payload looks like:

```<code>METHOD=MassPay&
USR=usr_api1.name.com&
PWD=9M8SWRPX6JMXDHAP&
SIGNATURE=AFcWxV21C7fd0v3bYYYRCpSSRl31AIajEwSIe41AAl--j033rVmjUPI7&
VERSION=204&
RECEIVERTYPE=EmailAddress&
CURRENCYCODE=USD&
L_EMAIL0=some.user%40company.com&
L_AMT0=25
</code>```

And I have TLS1.2 enabled. Is there any way to trace the problem except for incorrect credentials? Or maybe I have to set-up my test/dev account? By the way, my dev account isn't Business, but test account is Business and not Client.

Here is code that makes the request:

```<code>var sb = new StringBuilder();
foreach (var field in dic)
{
    sb.Append($"{field.Key}={HttpUtility.UrlEncode(field.Value)}&");
}
sb.Remove(sb.Length - 1, 1);
var payload = sb.ToString().Trim();

var req = WebRequest.Create(SandBoxHost + "?" + payload);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;

using (var resp = req.GetResponse()){}
</code>```

答:
Credentials and URL were correct. However, I found out that you are not able to send Mass Payment via txt file if your sandbox Business account does not have verified credit card. You need to specify this moment when you are creating a new sandbox user. Guess it would not work with API as well if you don't specify credit card.

The real problem was in one of the field names. I used USR instead of USER.

Body:
I'm getting this message

TIMESTAMP=2017-03-29T16:36:41Z&CORRELATIONID=9d5672f086c52&ACK=Failure&VERSION=204&BUILD=31674279&L_ERRORCODE0=10002&L_SHORTMESSAGE0=Security error&L_LONGMESSAGE0=Security header is not valid&L_SEVERITYCODE0=Error

I'm sure that I'm using the right credentials, I've copied them from sandbox account, from View API Signature page.

I'm trying to connect to sandbox environment with the url https://api-3t.sandbox.paypal.com/nvp.

Here is how my payload looks like:

METHOD=MassPay&
USR=usr_api1.name.com&
PWD=9M8SWRPX6JMXDHAP&
SIGNATURE=AFcWxV21C7fd0v3bYYYRCpSSRl31AIajEwSIe41AAl--j033rVmjUPI7&
VERSION=204&
RECEIVERTYPE=EmailAddress&
CURRENCYCODE=USD&
L_EMAIL0=some.user%40company.com&
L_AMT0=25

And I have TLS1.2 enabled. Is there any way to trace the problem except for incorrect credentials? Or maybe I have to set-up my test/dev account? By the way, my dev account isn't Business, but test account is Business and not Client.

Here is code that makes the request:

var sb = new StringBuilder();
foreach (var field in dic)
{
    sb.Append($"{field.Key}={HttpUtility.UrlEncode(field.Value)}&");
}
sb.Remove(sb.Length - 1, 1);
var payload = sb.ToString().Trim();

var req = WebRequest.Create(SandBoxHost + "?" + payload);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;

using (var resp = req.GetResponse()){}


问:
spring mongodb write-concern values
I have the following core mongo options configuration in spring:

```<code><mongo:mongo host="${db.hostname}" >
  <mongo:options
    connections-per-host="40"
    threads-allowed-to-block-for-connection-multiplier="1500"
    connect-timeout="15000"
    auto-connect-retry="true"
    socket-timeout="60000"
    write-number="1"
    write-fsync="false"/>
</mongo:mongo>
</code>```

What I want to know is about different write-number options which is relevant to write concern like none, normal, safe etc.

Can I assume the mapping of write-number to writeconcern as below?

```<code>NONE: -1
NORMAL: 0
SAFE: 1 (default)
FSYNC_SAFE: 2
REPLICAS_SAFE: 3
JOURNAL_SAFE: 4
MAJORITY: 5
</code>```

Following link has provided a good help to set mongo options in spring, but not specific enough for write-number values:
How to configure MongoDB Java driver MongoOptions for production use?

答:
You can confiture write-concern="ACKNOWLEDGED".

```<code><mongo:mongo id="replicaSetMongo" replica-set="${mongo.replicaSetSevers}" />
    <mongo:db-factory dbname="${mongo.dbname}" mongo-ref="replicaSetMongo" write-concern="ACKNOWLEDGED" />
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
    </bean>
</code>```

Hope this can help.

Title: spring mongodb write-concern values

Body:
I have the following core mongo options configuration in spring:

<mongo:mongo host="${db.hostname}" >
  <mongo:options
    connections-per-host="40"
    threads-allowed-to-block-for-connection-multiplier="1500"
    connect-timeout="15000"
    auto-connect-retry="true"
    socket-timeout="60000"
    write-number="1"
    write-fsync="false"/>
</mongo:mongo>

What I want to know is about different write-number options which is relevant to write concern like none, normal, safe etc.

Can I assume the mapping of write-number to writeconcern as below?

NONE: -1
NORMAL: 0
SAFE: 1 (default)
FSYNC_SAFE: 2
REPLICAS_SAFE: 3
JOURNAL_SAFE: 4
MAJORITY: 5

Following link has provided a good help to set mongo options in spring, but not specific enough for write-number values:
How to configure MongoDB Java driver MongoOptions for production use?

Body:
You can confiture write-concern="ACKNOWLEDGED".

<mongo:mongo id="replicaSetMongo" replica-set="${mongo.replicaSetSevers}" />
    <mongo:db-factory dbname="${mongo.dbname}" mongo-ref="replicaSetMongo" write-concern="ACKNOWLEDGED" />
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
    </bean>

Hope this can help.


问:
reset the dropdown default value using ngOptions and selectpickerintable
Controller:-

```<code>var selecteduser = [];
$scope.dataList = [
{ id:1, fname: 'abc', lname: 'xyz' },
{ id:2, fname: 'xyz', lname: 'abc' },
{ id:3, fname: 'foo', lname: 'bar' }
];
$scope.addUser = function (user) {
   selecteduser.push(user);
$scope.selectedItem = '';
}
</code>```

HTML:-

```<code><select class="dropdown" ng-model="selectedItem"
ng-options =" data as data.fname +''+ data.lname for data in dataList"
ng-change="addUser(selectedItem)">
</select>'
</code>```

Here I reset the dropdown value after pushing the value in array. But it is not working $scope.selectedItem = '';. Anything I missed ? Please help me!

Thanks

答:
Set selectedItem to null:

```<code>$scope.adduser = function (user) {
   if(user != null)
        {
           selecteduser.push(user);
           $scope.selectedItem = null;
        }
}
</code>```

Here you go:

var itemApp = angular.module("ItemApp", []);
itemApp.controller("ItemCtrl", function($scope){
     $scope.selecteduser = [];
     $scope.dataList = [
          { id:1, fname: 'abc', lname: 'xyz' },
          { id:2, fname: 'xyz', lname: 'abc' },
          { id:3, fname: 'foo', lname: 'bar' }
     ];
     $scope.addUser = function (user) {
        $scope.selecteduser.push(user);
        $scope.selectedItem = '';
     }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div data-ng-app="ItemApp" data-ng-controller="ItemCtrl">

<select class="dropdown" ng-model="selectedItem"
ng-options =" data as data.fname +''+ data.lname for data in dataList"
ng-change="addUser(selectedItem)">
</select>

<hr />
Selected Users so far:
{{ selecteduser | json }}

</div></code>```

Body:
Controller:-

var selecteduser = [];
$scope.dataList = [
{ id:1, fname: 'abc', lname: 'xyz' },
{ id:2, fname: 'xyz', lname: 'abc' },
{ id:3, fname: 'foo', lname: 'bar' }
];
$scope.addUser = function (user) {
   selecteduser.push(user);
$scope.selectedItem = '';
}

HTML:-

<select class="dropdown" ng-model="selectedItem"
ng-options =" data as data.fname +''+ data.lname for data in dataList"
ng-change="addUser(selectedItem)">
</select>'

Here I reset the dropdown value after pushing the value in array. But it is not working $scope.selectedItem = '';. Anything I missed ? Please help me!

Thanks

Body:
Set selectedItem to null:

$scope.adduser = function (user) {
   if(user != null)
        {
           selecteduser.push(user);
           $scope.selectedItem = null;
        }
}

Here you go:

var itemApp = angular.module("ItemApp", []);
itemApp.controller("ItemCtrl", function($scope){
     $scope.selecteduser = [];
     $scope.dataList = [
          { id:1, fname: 'abc', lname: 'xyz' },
          { id:2, fname: 'xyz', lname: 'abc' },
          { id:3, fname: 'foo', lname: 'bar' }
     ];
     $scope.addUser = function (user) {
        $scope.selecteduser.push(user);
        $scope.selectedItem = '';
     }

});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div data-ng-app="ItemApp" data-ng-controller="ItemCtrl">

<select class="dropdown" ng-model="selectedItem"
ng-options =" data as data.fname +''+ data.lname for data in dataList"
ng-change="addUser(selectedItem)">
</select>

<hr />
Selected Users so far:
{{ selecteduser | json }}

</div>


问:
using ng-if in angular2
I'm trying to build an ionic2 application,the shedule application send notifications to users,i want to do something like  this but it didn't worked</p>

```<code><div *ngIf="beacon.uuid=='ebefd083-70a2-47c8-9837-e7b5634df557'">{{schedule("ok","okkk")}}</div>
</code>```

答:
Change you code to this :

```<code><div *ngIf="beacon.uuid==='ebefd083-70a2-47c8-9837-e7b5634df557'">{{schedule("ok","okkk")}}</div>
</code>```

Use === instead of == , in Angular 2.

Title: using ng-if in angular2

Body:
I'm trying to build an ionic2 application,the shedule application send notifications to users,i want to do something like  this but it didn't worked

{{schedule("ok","okkk")}}

Body:
Change you code to this :

<div *ngIf="beacon.uuid==='ebefd083-70a2-47c8-9837-e7b5634df557'">{{schedule("ok","okkk")}}</div>

Use === instead of == , in Angular 2.