问:
Create an external file for side menu
How do I create an external file for my side menu?

C Programming
C++
C#
Go
Java
JavaScript
PHP
Python
Ruby
Swift
```

<p>Currently I have these kind of links in every file and the code is just getting too much. Is there a way to create an external file for the menu items?</p>

<p>I tried this but the problem is <code>class="active"</code>. I want to highlight a menu item when my menu item is in index.php
I Know how to achieve this when my menu is in each individual HTML file but how do I do that when it's in external PHP file ?</p>

<p>Index.php</p>

```

  <link rel="stylesheet" type="text/css" href="CSS/Tags.css">
  <link rel="stylesheet" type="text/css" href="CSS/Nav.css">
  <link rel="stylesheet" type="text/css" href="CSS/Card.css">
  <link rel="stylesheet" type="text/css" href="CSS/Buttons.css">
  <meta name="viewport" content="width=device-width, initial-scale=1">

&nbspOthers

 MS Excel
 MS PowerPoint
 MS Word
 WordPress

```

<p>Main file</p>

```<?php include('index.html'); ?>
```

答:
You should NOT use javascript to include your menu .
you can use PHP to simply include your menu ( but i sugget header ) file to your page :

<?php include('/template/header.html'); ?>

or you can use pre processors like Gulp :

@@include('./template/header.html')

```<code>var fileinclude = require('gulp-file-include'),
gulp = require('gulp');

gulp.task('fileinclude', function() {
  gulp.src(['index.html'])
    .pipe(fileinclude({
      prefix: '@@',
      basepath: '@file'
    }))
    .pipe(gulp.dest('./'));
});
</code>```

or Pug or Grunt and ......

About your problem in comments . lets say you are in your main folder and you have this 3 files :

```<code>index.php
header.html
homepage.html
footer.html
</code>```

index.php should be like this :

```<code><?php
include('header.html');
include('hompage.html');
include('footer.html');
?>
</code>```

and then in your browsers you should open index.php .

** don't use index.html and index.php in the same time .

if it didn't work . you should get error in your index.php file .

when your code works . i suggest you to use readfile() instead of include . if your another files are just html and not have any php codes in it .

Title: Create an external file for side menu

Body:
How do I create an external file for my side menu?

C Programming
C++
C#
Go
Java
JavaScript
PHP
Python
Ruby
Swift

Currently I have these kind of links in every file and the code is just getting too much. Is there a way to create an external file for the menu items?

I tried this but the problem is class="active". I want to highlight a menu item when my menu item is in index.php
I Know how to achieve this when my menu is in each individual HTML file but how do I do that when it's in external PHP file ?

Index.php

  <link rel="stylesheet" type="text/css" href="CSS/Tags.css">
  <link rel="stylesheet" type="text/css" href="CSS/Nav.css">
  <link rel="stylesheet" type="text/css" href="CSS/Card.css">
  <link rel="stylesheet" type="text/css" href="CSS/Buttons.css">
  <meta name="viewport" content="width=device-width, initial-scale=1">

&nbspOthers

 MS Excel
 MS PowerPoint
 MS Word
 WordPress

Main file

<?php include('index.html'); ?>

Body:
You should NOT use javascript to include your menu .
you can use PHP to simply include your menu ( but i sugget header ) file to your page :

<?php include('/template/header.html'); ?>

or you can use pre processors like Gulp :

@@include('./template/header.html')

var fileinclude = require('gulp-file-include'),
gulp = require('gulp');

gulp.task('fileinclude', function() {
  gulp.src(['index.html'])
    .pipe(fileinclude({
      prefix: '@@',
      basepath: '@file'
    }))
    .pipe(gulp.dest('./'));
});

or Pug or Grunt and ......

About your problem in comments . lets say you are in your main folder and you have this 3 files :

index.php
header.html
homepage.html
footer.html

index.php should be like this :

<?php
include('header.html');
include('hompage.html');
include('footer.html');
?>

and then in your browsers you should open index.php .

** don't use index.html and index.php in the same time .

if it didn't work . you should get error in your index.php file .

when your code works . i suggest you to use readfile() instead of include . if your another files are just html and not have any php codes in it .


来源: stackexchange

问:
If one of my POST Parameters contains character '+' it gets converted to ' ' instead of passing it correctly

When passing the id "vpzYeZkOy4HpNo + DLBb4WQ ==" disappears "+" in the body of id.

答:
Can you try passing + as a URL encoded value => %2B?

Edit: @David beat me to it

ContentLicense: CC BY-SA 4.0


问:
FullCalendar for bookings, selectable drag/click
Is it FullCalendar able to do something like the airbnb.com calendar for booking homes? Select dates between range of available days by clicking (not dragging)?

I have created a calendar that let you select dates by dragging from start to end, selectable: true and selectMinDistance: 2.

Example: https://codepen.io/khurramishaque/pen/dyyPyVX (from: FullCalendar disable select day if is not allowed in selectAllow callback)

Motivation: switch drag by click, render/select available days

My question is: can I use dayRender callback again when dateClick is fired?

答:
AFAIK there is no built-in support for this feature. However you could fairly easily implement this yourself.

In a short list:

Disable selectable, since it's not going to help you here

Bind to dateClick event and save the start date that is returned

In the same function handling the dateClick event, if you have a start date saved, get the end date and manually create the event using addEvent function

That's if you want to create an event. But you could do whatever else you want with this data and just call render on the calendar object.

For example:

```<code>var startDate = false;
var calendar = new Calendar(calendarEl, {
    selectable: false,
    dateClick: function (info) {
        if (startDate !== false) { // startDate has been selected, create event
            this.addEvent({
                title: "An event title",
                start: startDate,
                end: info.date
            });
            startDate = false;
        } else { // No start date, set it
            startDate = info.date;
        }
    }
});
</code>```

Note: I haven't tested the code above. You may need to initialize calendar first and then bind the dateClick event and replace this with calendar

Body:
AFAIK there is no built-in support for this feature. However you could fairly easily implement this yourself.

In a short list:

Disable selectable, since it's not going to help you here

Bind to dateClick event and save the start date that is returned

In the same function handling the dateClick event, if you have a start date saved, get the end date and manually create the event using addEvent function

That's if you want to create an event. But you could do whatever else you want with this data and just call render on the calendar object.

For example:

var startDate = false;
var calendar = new Calendar(calendarEl, {
    selectable: false,
    dateClick: function (info) {
        if (startDate !== false) { // startDate has been selected, create event
            this.addEvent({
                title: "An event title",
                start: startDate,
                end: info.date
            });
            startDate = false;
        } else { // No start date, set it
            startDate = info.date;
        }
    }
});

Note: I haven't tested the code above. You may need to initialize calendar first and then bind the dateClick event and replace this with calendar


问:
Which is more efficient Cstr(value) or value.ToString()
I am wondering which is more efficient, using CStr() or object.toString().
The reason I ask this is because I thought all that CStr() does is to invoke the .ToString() method on the object it was dealing with.

But when recently using a generic method without any type constraints I had to use object.ToString() instead of CStr(object).

The following is purely an example to illustrate the issue.

```<code>Public Function IDFromObject(Of ID_TYPE)(ByVal value As ID_TYPE) As String
    Return value.ToString
End Function
</code>```

Compiled as expected, but the following did not using CStr(). It gave an compilation error value of type ID_TYPE cannot be converted to string. But it obviously can use .ToString()

```<code>Public Function IDFromObject(Of ID_TYPE)(ByVal value As ID_TYPE) As String
    Return CStr(value)
End Function
</code>```

答:
Late answer, but no one else bothered to check or cite the Visual Basic documentation, and it recommends the opposite of what most of these answers do. This is straight from the Microsoft documentation:

As a rule, you should use the Visual Basic type conversion functions in preference to the .NET Framework methods such as ToString(), either on the Convert class or on an individual type structure or class. The Visual Basic functions are designed for optimal interaction with Visual Basic code, and they also make your source code shorter and easier to read.

That said, sometimes there are differences between what CStr and ToString will return, so performance and readability aren't the only considerations. There is an excellent answer on another question that describes when and why this is the case. Reproduced here:

The ToString method is a standard public method that returns a String. It is a method that is defined by the base Object type as overrideable. Each class can, therefore, override that method to return anything that it wants. It is quite common for classes to override the ToString method to make it return a nice human-readable description of the object.

CStr, on the other hand, is a casting operator. It is shorthand for CType(x, String). The casting operator, like many other operators, can be overridden by any class. Normally, though, you want casting operations to return the closest representation of the actual value of the original object, rather than a descriptive string.

It is not unusual then, that you may want ToString to return a different result than CStr. In the case of an enum, each member is essentially an Integer, so CStr on an enum member works the same as CStr on an integer. That is what you would expect. However, ToString has been overridden to return the more human readable version of the value. That is also what you would expect.

So, in summary:

When you want the closest string representation of the actual value of the original object, you should use CStr(). When you want the (potentially) customized, human-readable version of the value, you should use .ToString.

Body:
I am wondering which is more efficient, using CStr() or object.toString().
The reason I ask this is because I thought all that CStr() does is to invoke the .ToString() method on the object it was dealing with.

But when recently using a generic method without any type constraints I had to use object.ToString() instead of CStr(object).

The following is purely an example to illustrate the issue.

Public Function IDFromObject(Of ID_TYPE)(ByVal value As ID_TYPE) As String
    Return value.ToString
End Function

Compiled as expected, but the following did not using CStr(). It gave an compilation error value of type ID_TYPE cannot be converted to string. But it obviously can use .ToString()

Public Function IDFromObject(Of ID_TYPE)(ByVal value As ID_TYPE) As String
    Return CStr(value)
End Function


问:
How to properly routes all the nodejs express app request in google cloud functions
I have created an express app which is working pretty fine but when I'm trying to host the web app using firebase cloud functions  the url rewrites rules in firebase.json seems to be not working properly.

code snippet from index.js file under functions folder

```<code>exports.app = functions.https.onRequest(app);
</code>```

here is the snippet from firebase.json file

```<code>  "rewrites": [
  {
    "source": "/**{,/**}",
    "function": "app"
  }
</code>```

I have also tried

```<code>  "rewrites": [
  {
    "source": "**",
    "function": "app"
  }
</code>```

but none of the is working.
I want all my webapp's url request from "http://url/someroute" to get routed to "http://url.com/app/someroute"

Right now for now all of this to work I have to change my hyperlinks from "/someroute" to "/app/someroute"

答:
The problem is that you trying to redirect to a function, not a route, so if you want to actually change the route, you have to use destination instead of function, as follows:

```<code>"rewrites": [
{
  "source": "**",
  "destination": "/app/**"
}
</code>```

Or something similar to that, here is a community post that explain that in a little more detail and also the rewrite documentation that might be able to help you further

Body:
I have created an express app which is working pretty fine but when I'm trying to host the web app using firebase cloud functions  the url rewrites rules in firebase.json seems to be not working properly.

code snippet from index.js file under functions folder

exports.app = functions.https.onRequest(app);

here is the snippet from firebase.json file

  "rewrites": [
  {
    "source": "/**{,/**}",
    "function": "app"
  }

I have also tried

  "rewrites": [
  {
    "source": "**",
    "function": "app"
  }

but none of the is working.
I want all my webapp's url request from "http://url/someroute" to get routed to "http://url.com/app/someroute"

Right now for now all of this to work I have to change my hyperlinks from "/someroute" to "/app/someroute"

Body:
The problem is that you trying to redirect to a function, not a route, so if you want to actually change the route, you have to use destination instead of function, as follows:

"rewrites": [
{
  "source": "**",
  "destination": "/app/**"
}

Or something similar to that, here is a community post that explain that in a little more detail and also the rewrite documentation that might be able to help you further


问:
How to know if JavaScript string.replace() did anything?
The replace function returns the new string with the replaces, but if there weren't any words to replace, then the original string is returned. Is there a way to know whether it actually replaced anything apart from comparing the result with the original string?

答:
While this will require multiple operations, using .test() may suffice:

```<code>const regex = /foo/;
const yourString = 'foo bar';

if (regex.test(yourString)) {
  console.log('yourString contains regex');
  // Go ahead and do whatever else you'd like.
}
</code>```

The test() method executes a search for a match between a regular expression and a specified string. Returns true or false.

ContentLicense: CC BY-SA 2.5

Body:
While this will require multiple operations, using .test() may suffice:

const regex = /foo/;
const yourString = 'foo bar';

if (regex.test(yourString)) {
  console.log('yourString contains regex');
  // Go ahead and do whatever else you'd like.
}

The test() method executes a search for a match between a regular expression and a specified string. Returns true or false.


问:
Spark joins performance issue
I'm trying to merge historical and incremental data. As part of the incremental data, I'm getting deletes. Below is the case.

historical data  - 100 records ( 20 columns, id is the key column)

incremental data - 10 records  ( 20 columns, id is the key column)

Out of the 10 records in incremental data, only 5 will match with historical data.

Now I want 100 records in the final dataframe of which 95 records belong to historical data and 5 records belong to incremental data(wherever id column is match).

Update timestamp field is available in both historical and incremental data.

Below is the approach I tried.

```<code>    DF1 - Historical  Data
    DF2 - Incremental Delete Dataset
    DF3 = DF1 LEFTANTIJOIN DF2
    DF4 = DF2 INNERJOIN DF1
    DF5 = DF3 UNION DF4
</code>```

However, I observed It has lot of performance issue as I'm running this join on billions of records. Any better way to do this?

答:
you can use the cogroup operator combined with a user defined function to construct the different variations of the join.
Suppose we have these two RDDs as an example :

```<code>visits = sc.parallelize([("h", "1.2.3.4"), ("a", "3.4.5.6"), ("h","1.3.3.1")] )
pageNames = sc.parallelize([("h", "Home"), ("a", "About"), ("o", "Other")])
cg = visits.cogroup(pageNames).map(lambda x :(x[0], ( list(x[1][0]), list(x[1][1]))))
</code>```

You can implement an inner join as such :

```<code>innerjoin = cg.flatMap(lambda x: J(x))
</code>```

Where J is defined as such :

```<code>def J(x):
    j=[]
    k=x[0]
    if x[1][0]!=[] and x[1][1]!=[]:
        for l in x[1][0]:
            for r in x[1][1]:
                j.append((k,(l,r)))
    return j
</code>```

For a right outer join for example you just need to change the J function to an roJ function defined as such :

```<code>def roJ(x):
    j=[]
    k=x[0]
    if x[1][0]!=[] and x[1][1]!=[]:
        for l in x[1][0]:
            for r in x[1][1]:
                j.append((k,(l,r)))
    elif x[1][1]!=[] :
        for r in x[1][1]:
            j.append((k, (None, r)))
    return j
</code>```

And call it like so :

```<code>rightouterjoin = cg.flatMap(lambda x: roJ(x))
</code>```

And so on for other types of join you'd wish to implement

Title: Spark joins performance issue

Body:
I'm trying to merge historical and incremental data. As part of the incremental data, I'm getting deletes. Below is the case.

historical data  - 100 records ( 20 columns, id is the key column)

incremental data - 10 records  ( 20 columns, id is the key column)

Out of the 10 records in incremental data, only 5 will match with historical data.

Now I want 100 records in the final dataframe of which 95 records belong to historical data and 5 records belong to incremental data(wherever id column is match).

Update timestamp field is available in both historical and incremental data.

Below is the approach I tried.

    DF1 - Historical  Data
    DF2 - Incremental Delete Dataset
    DF3 = DF1 LEFTANTIJOIN DF2
    DF4 = DF2 INNERJOIN DF1
    DF5 = DF3 UNION DF4

However, I observed It has lot of performance issue as I'm running this join on billions of records. Any better way to do this?

Body:
you can use the cogroup operator combined with a user defined function to construct the different variations of the join.
Suppose we have these two RDDs as an example :

visits = sc.parallelize([("h", "1.2.3.4"), ("a", "3.4.5.6"), ("h","1.3.3.1")] )
pageNames = sc.parallelize([("h", "Home"), ("a", "About"), ("o", "Other")])
cg = visits.cogroup(pageNames).map(lambda x :(x[0], ( list(x[1][0]), list(x[1][1]))))

You can implement an inner join as such :

innerjoin = cg.flatMap(lambda x: J(x))

Where J is defined as such :

def J(x):
    j=[]
    k=x[0]
    if x[1][0]!=[] and x[1][1]!=[]:
        for l in x[1][0]:
            for r in x[1][1]:
                j.append((k,(l,r)))
    return j

For a right outer join for example you just need to change the J function to an roJ function defined as such :

def roJ(x):
    j=[]
    k=x[0]
    if x[1][0]!=[] and x[1][1]!=[]:
        for l in x[1][0]:
            for r in x[1][1]:
                j.append((k,(l,r)))
    elif x[1][1]!=[] :
        for r in x[1][1]:
            j.append((k, (None, r)))
    return j

And call it like so :

rightouterjoin = cg.flatMap(lambda x: roJ(x))

And so on for other types of join you'd wish to implement


问:
Solidity: Why does a faulty input set my boolean to "true"?
I'm using remix.ethereum.org

I wrote this very simple smart contract:

```<code>pragma solidity ^0.4.19;

contract TicTacToe {
    bool myBool = false;

    uint8 myUint8;
    uint256 myUint256;

    string myString = "myString";
    bytes myBytes = "myString";

    function setMyBoolean(bool myBoolArgument) public {
        myBool = myBoolArgument;
    }

    function getMyBoolean() public view returns(bool) {
      return myBool;
    }

}
</code>```

As you can see the default value for myBool is false
I can change this by calling the function setMyBoolean.

If I use this argument and type in true, myBool will be set to true
If I use this argument and type in false, myBool will be set to false

But if I type in any other combination of letters, myBool will be set to true as well. This surprises me because the default setting for myBool is false.

Why does this happen?

答:
It's working as intended because this is the way that remix and abi encoder decided to handle booleans

```<code>  // "false" will be converting to `false` and "true" will be working
  // fine as abiCoder assume anything in quotes as `true`
  if (type === 'bool' && args[i] === 'false') {
     args[i] = false
  }
</code>```

https://github.com/ethereum/remix/blob/807ffd9772b07dafb343c08faf44c78ee456de77/remix-lib/src/execution/txHelper.js#L18

Body:
I'm using remix.ethereum.org

I wrote this very simple smart contract:

pragma solidity ^0.4.19;

contract TicTacToe {
    bool myBool = false;

    uint8 myUint8;
    uint256 myUint256;

    string myString = "myString";
    bytes myBytes = "myString";

    function setMyBoolean(bool myBoolArgument) public {
        myBool = myBoolArgument;
    }

    function getMyBoolean() public view returns(bool) {
      return myBool;
    }

}

As you can see the default value for myBool is false
I can change this by calling the function setMyBoolean.

If I use this argument and type in true, myBool will be set to true
If I use this argument and type in false, myBool will be set to false

But if I type in any other combination of letters, myBool will be set to true as well. This surprises me because the default setting for myBool is false.

Why does this happen?

Body:
It's working as intended because this is the way that remix and abi encoder decided to handle booleans

  // "false" will be converting to `false` and "true" will be working
  // fine as abiCoder assume anything in quotes as `true`
  if (type === 'bool' && args[i] === 'false') {
     args[i] = false
  }

https://github.com/ethereum/remix/blob/807ffd9772b07dafb343c08faf44c78ee456de77/remix-lib/src/execution/txHelper.js#L18


问:
The operation is not valid for the state of the transaction In Orchard CMS
I am new in orchard CMS, I am integrating my own application in orchard CMS. I have create a edmx file then  I have created an Action to Display the records,  But it give me ERROR THAT  "The operation is not valid for the state of the transaction".

Here is a code

[HttpGet]
        public ActionResult About()
        {
                       return View(_db.tblNameTests.ToList());
        }
in view the code is:

@model List

Aboutus

    @Html.ActionLink("Create New", "Create")

            Id

            Name

@foreach (var item in Model) {

            @item.id

        @item.name

}

Is I am missing some thing?
Waiting for your valuable reply.

答: You need to opt out of Orchard's ambient transaction. See: http://orchard.codeplex.com/workitem/17291</p>

ContentLicense: CC BY-SA 3.0


问:
Receive file with servicestack from multipart/form-data
I'm submitting a form as a multipart/form-data from a react app to .net backend. I use FormData on react to post data using axios. On the serverside I'm using servicestack to process the data, text inputs I managed to figure out but the file input I don't know how to receive.

This is how I submit my form from react

```<code>handleSubmit = event => {
        event.preventDefault();
        var form = document.getElementById("imageForm"); // You need to use standard javascript object here
        var formData = new FormData(form);

        axios.post('http://myurls.com', formData, {headers: { 'Content-Type': 'multipart/form-data' }})
        .then(res=>{
            console.log(res);
        })
        .catch(error =>{
            console.log(error);
        })
    }
</code>```

This is my servicestack C#

```<code>
    #region PLUGIN
    public class FormSubmit : IPlugin
    {
        public void Register(IAppHost appHost)
        {
            appHost.RegisterService(typeof(FormSubmitService));
        }
    }

    #endregion

    #region SERVICE
    public class FormSubmitService : ServiceStack.Service
    {
        public object Post(FormSubmitRequest request)
        {
            return request;
        }
    }
    #endregion

    #region REQUEST
    [Route("/myservice/submitform")]
    public class FormSubmitRequest : IReturn<object>
    {
        public object ImageFile { get; set; }
        public string ImageTitle { get; set; }
        public string ImageDescription { get; set; }

    }
    #endregion

</code>```

I'm very new to C# and I can't pinpoint what the issue is. My guess was the datatype of the ImageFile, I tried setting it to object, string, bytes[] and System.Web.UI.WebControls.Image but that didn't seem to make any difference.

When I'm returning the request I can see my request object which contains ImageTitle and ImageDescription but no ImageFile, not even an empty key

I'm really lost and don't even know where to begin debugging the issue.

Thanks in advance for any help!

答: Here are the ServiceStack docs for handling HTTP File Uploads</p>

Body:
I'm submitting a form as a multipart/form-data from a react app to .net backend. I use FormData on react to post data using axios. On the serverside I'm using servicestack to process the data, text inputs I managed to figure out but the file input I don't know how to receive.

This is how I submit my form from react

handleSubmit = event => {
        event.preventDefault();
        var form = document.getElementById("imageForm"); // You need to use standard javascript object here
        var formData = new FormData(form);

        axios.post('http://myurls.com', formData, {headers: { 'Content-Type': 'multipart/form-data' }})
        .then(res=>{
            console.log(res);
        })
        .catch(error =>{
            console.log(error);
        })
    }

This is my servicestack C#

    #region PLUGIN
    public class FormSubmit : IPlugin
    {
        public void Register(IAppHost appHost)
        {
            appHost.RegisterService(typeof(FormSubmitService));
        }
    }

    #endregion

    #region SERVICE
    public class FormSubmitService : ServiceStack.Service
    {
        public object Post(FormSubmitRequest request)
        {
            return request;
        }
    }
    #endregion

    #region REQUEST
    [Route("/myservice/submitform")]
    public class FormSubmitRequest : IReturn<object>
    {
        public object ImageFile { get; set; }
        public string ImageTitle { get; set; }
        public string ImageDescription { get; set; }

    }
    #endregion

I'm very new to C# and I can't pinpoint what the issue is. My guess was the datatype of the ImageFile, I tried setting it to object, string, bytes[] and System.Web.UI.WebControls.Image but that didn't seem to make any difference.

When I'm returning the request I can see my request object which contains ImageTitle and ImageDescription but no ImageFile, not even an empty key

I'm really lost and don't even know where to begin debugging the issue.

Thanks in advance for any help!


问:
"Object reference not set to an instance of an object" when creating a new Web API controller with EF Scaffolding in Visual Studio 2012
I have an MVC4/Web API project, with an Entity Framework, Code First data model. When I try to create a new API Controller with read/write methods using a data context & model, I get an alert saying "Object reference not set to an instance of an object".

I've done a bit of searching and found that some causes are incorrect project type Guids in the .csproj file, incomplete installation of the MvcScaffolding nuget package and one suggestion of installing Powershell 3.

I have made sure all my project type guids are correct, made sure the MvcScaffolding package is installed correctly, and I've even installed Powershell 3.

None of this has solved the problem for me. All I can think is there is a problem with my data context/model although it created the tables/relationships fine. Code below:

Context:

```<code>public class PropertySearchContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Property>().HasRequired(p => p.Office).WithMany(o => o.Properties).HasForeignKey(p => p.OfficeId);
    }

    public DbSet<Office> Offices { get; set; }
    public DbSet<Property> Properties { get; set; }
}
</code>```

Model:

```<code>[Serializable]
public class Property
{
    public int PropertyId { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string Town { get; set; }
    public string County { get; set; }
    public string Postcode { get; set; }

    public int Bedrooms { get; set; }
    public int Bathrooms { get; set; }

    public string UmbracoNodeId { get; set; }
    public string MainImageUrl { get; set; }
    public string ListingImageUrl { get; set; }
    public int TotalImageCount { get; set; }
    public PropertyType PropertyType { get; set; }
    public PropertyStatus PropertyStatus { get; set; }
    public long Price { get; set; }
    public string ListingUrl { get; set; }

    //Navigation Properties
    public int OfficeId { get; set; }
    public virtual Office Office { get; set; }

    //Meta properties
    public DateTime CreatedAt { get; set; }
    public string CreatedBy { get; set; }
    public DateTime UpdatedAt { get; set; }
    public string UpdatedBy { get; set; }
}
</code>```

Connection String:

```<code><add name="PropertySearchContext" connectionString="Data Source=MERCURY\SQLEXPRESS;Initial Catalog=DATABASE_NAME;Integrated Security=False;User ID=dbFakeUser;Password=fakePassword;Connect Timeout=10" providerName="System.Data.SqlClient" />
</code>```

Any help with this would be greatly appreciated as I've tried every suggestion and I still can't create a controller with scaffolding. Driving me mad!

Thanks!

答:
This answer depends on many things. On my case I didn't have a problem with the model itself. After long hours looking I discovered that another project, which was being referenced on my MVC .NET website, was the one stopping the scaffolding from running correctly.

What I am doing (kind of tedious) is to remove the reference (breaks many things meanwhile), Add the controllers/views that I need, then add the reference again and voila. No "Object Reference" error.

Hope this works for you

Body:
I have an MVC4/Web API project, with an Entity Framework, Code First data model. When I try to create a new API Controller with read/write methods using a data context & model, I get an alert saying "Object reference not set to an instance of an object".

I've done a bit of searching and found that some causes are incorrect project type Guids in the .csproj file, incomplete installation of the MvcScaffolding nuget package and one suggestion of installing Powershell 3.

I have made sure all my project type guids are correct, made sure the MvcScaffolding package is installed correctly, and I've even installed Powershell 3.

None of this has solved the problem for me. All I can think is there is a problem with my data context/model although it created the tables/relationships fine. Code below:

Context:

public class PropertySearchContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Property>().HasRequired(p => p.Office).WithMany(o => o.Properties).HasForeignKey(p => p.OfficeId);
    }

    public DbSet<Office> Offices { get; set; }
    public DbSet<Property> Properties { get; set; }
}

Model:

[Serializable]
public class Property
{
    public int PropertyId { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string Town { get; set; }
    public string County { get; set; }
    public string Postcode { get; set; }

    public int Bedrooms { get; set; }
    public int Bathrooms { get; set; }

    public string UmbracoNodeId { get; set; }
    public string MainImageUrl { get; set; }
    public string ListingImageUrl { get; set; }
    public int TotalImageCount { get; set; }
    public PropertyType PropertyType { get; set; }
    public PropertyStatus PropertyStatus { get; set; }
    public long Price { get; set; }
    public string ListingUrl { get; set; }

    //Navigation Properties
    public int OfficeId { get; set; }
    public virtual Office Office { get; set; }

    //Meta properties
    public DateTime CreatedAt { get; set; }
    public string CreatedBy { get; set; }
    public DateTime UpdatedAt { get; set; }
    public string UpdatedBy { get; set; }
}

Connection String:

<add name="PropertySearchContext" connectionString="Data Source=MERCURY\SQLEXPRESS;Initial Catalog=DATABASE_NAME;Integrated Security=False;User ID=dbFakeUser;Password=fakePassword;Connect Timeout=10" providerName="System.Data.SqlClient" />

Any help with this would be greatly appreciated as I've tried every suggestion and I still can't create a controller with scaffolding. Driving me mad!

Thanks!


问:
PHP search array for a value between two numbers
What's the best way of searching an array for a number within a range? e.g. between 1000 and 1500.

```<code><?php
$numbers = array(1105,2140,3170);

$needle = **value between 1000 and 1500**;

if (in_array($needle, $numbers)) {
  echo "Match found";
} else {
  echo "Match not found";
}
?>
</code>```

In this case, this would return 'Match found' as 1105 is between 1000 and 1500.

Can I set a range for the $needle variable?

答:
What's the best way of searching an array for a number within a range. To answer this, there are 2 approaches as mentioned below:

Approach #1:

You can use a simple foreach loop to get all values from your unordered data which lie in the range.

```<code><?php

$numbers = array(1105,2140,3170);

$start = 1000;
$end = 1500;

$result = [];

foreach($numbers as $num){
    if($num >= $start && $num <= $end) $result[] = $num;
}

print_r($result);
</code>```

Demo: https://3v4l.org/D1Rfu

Approach #2:(recommended for future lookups)

You can sort your data and use binary search to get the starting point of where your numbers start falling in the range of start and end for faster lookups. Then, you can just look from that index till the index you get a higher number or reach the end of the array.

```<code><?php

$numbers = array(1105,2140,3170,1000,1500,1501);

$start = 1000;
$end  = 1500;
$start_index = -1;

sort($numbers);

$low = 0; $high = count($numbers) - 1;

while($low <= $high){
    $mid = intval(($low + $high) / 2);
    if($numbers[$mid] > $end){
        $high = $mid - 1;
    }else if($numbers[$mid] < $start){
        $low = $mid + 1;
    }else{
        $start_index = $mid;
        $high = $mid - 1;
    }
}

$result = [];
for($i = $start_index; $i < count($numbers); ++$i){
    if($numbers[$i] > $end) break;
    $result[] = $numbers[$i];
}

print_r($result);
</code>```

Demo: https://3v4l.org/WcgXv

Body:
What's the best way of searching an array for a number within a range? e.g. between 1000 and 1500.

<?php
$numbers = array(1105,2140,3170);

$needle = **value between 1000 and 1500**;

if (in_array($needle, $numbers)) {
  echo "Match found";
} else {
  echo "Match not found";
}
?>

In this case, this would return 'Match found' as 1105 is between 1000 and 1500.

Can I set a range for the $needle variable?

Body:
What's the best way of searching an array for a number within a range. To answer this, there are 2 approaches as mentioned below:

Approach #1:

You can use a simple foreach loop to get all values from your unordered data which lie in the range.

<?php

$numbers = array(1105,2140,3170);

$start = 1000;
$end = 1500;

$result = [];

foreach($numbers as $num){
    if($num >= $start && $num <= $end) $result[] = $num;
}

print_r($result);

Demo: https://3v4l.org/D1Rfu

Approach #2:(recommended for future lookups)

You can sort your data and use binary search to get the starting point of where your numbers start falling in the range of start and end for faster lookups. Then, you can just look from that index till the index you get a higher number or reach the end of the array.

<?php

$numbers = array(1105,2140,3170,1000,1500,1501);

$start = 1000;
$end  = 1500;
$start_index = -1;

sort($numbers);

$low = 0; $high = count($numbers) - 1;

while($low <= $high){
    $mid = intval(($low + $high) / 2);
    if($numbers[$mid] > $end){
        $high = $mid - 1;
    }else if($numbers[$mid] < $start){
        $low = $mid + 1;
    }else{
        $start_index = $mid;
        $high = $mid - 1;
    }
}

$result = [];
for($i = $start_index; $i < count($numbers); ++$i){
    if($numbers[$i] > $end) break;
    $result[] = $numbers[$i];
}

print_r($result);

Demo: https://3v4l.org/WcgXv


问:
How to print a message only once in a loop
I am using for loops combined with if statements to read integers from a text file into a two-dimensional array.

This is my code:

```<code>for (int i = 0; i < MAX_ROWS;i++) {
        for (int j = 0; j < MAX_COLUMNS; j++) {
            inFile >> ArrB[i][j];
            if (ArrB[i][j] == -1) {
                bad = true;
                cout << "The array does not have enough integers" << endl;
                break;
            }
            else {
                if (ArrB[i][j] < 1) {
                    invalidnum = true;
                }
            }

            if (invalidnum = true) {
                cout << *(*(ArrB + i) + j) << " ";
                cout << "There is/are negative number(s) or zero(s) in the array imported from your text file." << endl;

            }
        }
    }
</code>```

This code will read in the first 6 integers (max_row * max_column) from a text file into ArrB.

If  -1 exists in the first 6 integers, it will exit the loop and print out "The array does not have enough integers".

If there is no -1 in the first 6 integers, then it will check all 6 integers to see if there are any other negative numbers or zero.

If there are negative numbers or zero, I want it to still print out the array, then print out the error message (There is/are negative number(s) or zero(s) in the array imported from your text file) ONLY ONCE.

For example, this is my text file. As you can see, there is no -1 in the first 6 numbers, but there is a -7.

So, ideally, the result should be something like:

```<code>2 4 5 6 9 -7

There is/are negative number(s) or zero(s) in the array imported from your text file
</code>```

But this is what I am getting if I run my code above:

-------------------------------------UPDATE--------------------------------------

Figured it out based on @ZedLepplin 's comment

Here is the code:

```<code>for (int i = 0; i < MAX_ROWS;i++) {
        for (int j = 0; j < MAX_COLUMNS; j++) {
            inFile >> ArrB[i][j];
            if (ArrB[i][j] == -1) {
                bad = true;
                cout << "The array does not have enough integers" << endl;
                break;
            }
            else {
                if (ArrB[i][j] < 1) {
                    invalidnum = true;
                }
            }
            cout << *(*(ArrB + i) + j) << " ";
        }
    }
    if (invalidnum == true) {
        cout << "There is/are negative number(s) or zero(s) in the array imported from your text file." << endl;
    }
</code>```

答:
Put the conditional error message print after your for loop. Leave the cout for displaying the array number inside the for loop so it is output for every iteration of the loop.</p>

```<code>for (int i = 0; i<MAX_ROWS;i++) {
    for (int j = 0; j<MAX_COLUMNS; j++) {
        inFile >> ArrB[i][j];
        if (ArrB[i][j] == -1) {
            bad = true;
            cout << "The array does not have enough integers" << endl;
            break;
        }
        else {
            if (ArrB[i][j] < 1) {
                invalidnum = true;
            }
        }

        cout << * (*(ArrB + i) + j) << " ";
    }
}

if (invalidnum = true) {
        cout << "There is/are negative number(s) or zero(s) in the array imported from your text file." << endl;
}
</code>```

Body:
I am using for loops combined with if statements to read integers from a text file into a two-dimensional array.

This is my code:

for (int i = 0; i < MAX_ROWS;i++) {
        for (int j = 0; j < MAX_COLUMNS; j++) {
            inFile >> ArrB[i][j];
            if (ArrB[i][j] == -1) {
                bad = true;
                cout << "The array does not have enough integers" << endl;
                break;
            }
            else {
                if (ArrB[i][j] < 1) {
                    invalidnum = true;
                }
            }

            if (invalidnum = true) {
                cout << *(*(ArrB + i) + j) << " ";
                cout << "There is/are negative number(s) or zero(s) in the array imported from your text file." << endl;

            }
        }
    }

This code will read in the first 6 integers (max_row * max_column) from a text file into ArrB.

If  -1 exists in the first 6 integers, it will exit the loop and print out "The array does not have enough integers".

If there is no -1 in the first 6 integers, then it will check all 6 integers to see if there are any other negative numbers or zero.

If there are negative numbers or zero, I want it to still print out the array, then print out the error message (There is/are negative number(s) or zero(s) in the array imported from your text file) ONLY ONCE.

For example, this is my text file. As you can see, there is no -1 in the first 6 numbers, but there is a -7.

So, ideally, the result should be something like:

2 4 5 6 9 -7

There is/are negative number(s) or zero(s) in the array imported from your text file

But this is what I am getting if I run my code above:

-------------------------------------UPDATE--------------------------------------

Figured it out based on @ZedLepplin 's comment

Here is the code:

for (int i = 0; i < MAX_ROWS;i++) {
        for (int j = 0; j < MAX_COLUMNS; j++) {
            inFile >> ArrB[i][j];
            if (ArrB[i][j] == -1) {
                bad = true;
                cout << "The array does not have enough integers" << endl;
                break;
            }
            else {
                if (ArrB[i][j] < 1) {
                    invalidnum = true;
                }
            }
            cout << *(*(ArrB + i) + j) << " ";
        }
    }
    if (invalidnum == true) {
        cout << "There is/are negative number(s) or zero(s) in the array imported from your text file." << endl;
    }

Body:
Put the conditional error message print after your for loop. Leave the cout for displaying the array number inside the for loop so it is output for every iteration of the loop.

for (int i = 0; i<MAX_ROWS;i++) {
    for (int j = 0; j<MAX_COLUMNS; j++) {
        inFile >> ArrB[i][j];
        if (ArrB[i][j] == -1) {
            bad = true;
            cout << "The array does not have enough integers" << endl;
            break;
        }
        else {
            if (ArrB[i][j] < 1) {
                invalidnum = true;
            }
        }

        cout << * (*(ArrB + i) + j) << " ";
    }
}

if (invalidnum = true) {
        cout << "There is/are negative number(s) or zero(s) in the array imported from your text file." << endl;
}


问:
Translate Array with Array
I search a way to translate a key from one array with other array.

tmp_title=$3
title=$(echo ${tmp_title,,} | sed -e 's/\s/-/g')
tags=(computer media state society)
de=(computer medien staat gesellschaft)
fr=(ordinateur journalisme politique société)
ru=(Компьютер СМИ штат общество)

      file="./content/de/blog/$(date +"%Y")/$(date +"%m")/$title.md"
      if test -n "$2"; then

        # check tag is in tags array
        if [[ ${tags[*]} =~ $2 ]]; then

          # check the folder structure is right
          if [[ -d ./content/de/blog/$(date +"%Y")/$(date +"%m") ]]; then

            # create the content and fill up the file
            echo "---" >> "$file"
            echo "title: \"$3\"" >> "$file"
            echo "date: $(date +\"%Y-%m-%d\")" >> "$file"
            echo "draft: false" >> "$file"
            echo "tags: \"$2\"" >> "$file"
            echo "shorttext:" >> "$file"
            echo "cover: \"$2\"" >> "$file"
            echo "lang: $1" >> "$file"
            echo "---" >> "$file"
          fi
        else
          echo "Enter a valid tag name ..."
        fi
      fi
```

I search a way to translate "tags: \"$2\"" >> "$file" in the language array value. When I append society to the script then should be tags: "gesellschaft".

Thank you for help.

Silvio

答:
Consider this approach</p>

```<code>case $LANG in
    *en*) tags=(computer   media       state     society     );;
    *de*) tags=(computer   medien      staat     gesellschaft);;
    *fr*) tags=(ordinateur journalisme politique société     );;
    *ru*) tags=(Компьютер  СМИ         штат      общество    );;
esac
</code>```

Title: Translate Array with Array

Body:
I search a way to translate a key from one array with other array.

tmp_title=$3
title=$(echo ${tmp_title,,} | sed -e 's/\s/-/g')
tags=(computer media state society)
de=(computer medien staat gesellschaft)
fr=(ordinateur journalisme politique société)
ru=(Компьютер СМИ штат общество)

      file="./content/de/blog/$(date +"%Y")/$(date +"%m")/$title.md"
      if test -n "$2"; then

        # check tag is in tags array
        if [[ ${tags[*]} =~ $2 ]]; then

          # check the folder structure is right
          if [[ -d ./content/de/blog/$(date +"%Y")/$(date +"%m") ]]; then

            # create the content and fill up the file
            echo "---" >> "$file"
            echo "title: \"$3\"" >> "$file"
            echo "date: $(date +\"%Y-%m-%d\")" >> "$file"
            echo "draft: false" >> "$file"
            echo "tags: \"$2\"" >> "$file"
            echo "shorttext:" >> "$file"
            echo "cover: \"$2\"" >> "$file"
            echo "lang: $1" >> "$file"
            echo "---" >> "$file"
          fi
        else
          echo "Enter a valid tag name ..."
        fi
      fi

I search a way to translate "tags: \"$2\"" >> "$file" in the language array value. When I append society to the script then should be tags: "gesellschaft".

Thank you for help.

Silvio

Body:
Consider this approach

case $LANG in
    *en*) tags=(computer   media       state     society     );;
    *de*) tags=(computer   medien      staat     gesellschaft);;
    *fr*) tags=(ordinateur journalisme politique société     );;
    *ru*) tags=(Компьютер  СМИ         штат      общество    );;
esac


问:
WPF datagrid edit row not working
I want to set a cell in my WPF DataGrid on a button click.

I fill a WPF DataGrid like this:

```<code>myDataGrid.ItemsSource = GetMyList();
</code>```

The DataGrid is set to autoGenerateColumns. I get my list using a mySql select.

The objects in my list implement the INotifyPropertyChanged interface.

On my button click I do this:

```<code>MyObject o = (MyObject)myDataGrid.SelectedItem;
o.Checkin = DateTime.Now; //set date on button click is what i want
</code>```

The data is set but the DataGrid doesn't update its view. Why?

Edited:
I implement the INotifyPropertyChanged interface like this:

```<code>private void NotifyPropertyChanged(String info)   {
    if (PropertyChanged != null)    {
        PropertyChanged(this, new PropertyChangedEventArgs(info));
    }
}

public DateTime Checkin    {
    get {return this.checkin;}
    set  {
            this.checkin= value;
            NotifyPropertyChanged("Checkin");
        }
    }
}
</code>```

答:
this did the trick:</p>

```<code>   myDataGrid.Items.Refresh();
</code>```

Title: WPF datagrid edit row not working

Body:
I want to set a cell in my WPF DataGrid on a button click.

I fill a WPF DataGrid like this:

myDataGrid.ItemsSource = GetMyList();

The DataGrid is set to autoGenerateColumns. I get my list using a mySql select.

The objects in my list implement the INotifyPropertyChanged interface.

On my button click I do this:

MyObject o = (MyObject)myDataGrid.SelectedItem;
o.Checkin = DateTime.Now; //set date on button click is what i want

The data is set but the DataGrid doesn't update its view. Why?

Edited:
I implement the INotifyPropertyChanged interface like this:

private void NotifyPropertyChanged(String info)   {
    if (PropertyChanged != null)    {
        PropertyChanged(this, new PropertyChangedEventArgs(info));
    }
}

public DateTime Checkin    {
    get {return this.checkin;}
    set  {
            this.checkin= value;
            NotifyPropertyChanged("Checkin");
        }
    }
}

Body:
this did the trick:

   myDataGrid.Items.Refresh();


问:
How to specify programming language for 'Fastfile' in Android Studio?
I use Fastlane in my Android Project. And when I open 'fastlfile' file, Android Studio doesn't recognize this file as ruby code. And the code is not colorful. How can I specify programming language for the file? </p>

答:
If you're working with file types that are not recognized by Android studio (for example, if it's a proprietary file type developed in-house), or if you need to code in an unsupported language, you can create a custom file type.

https://www.jetbrains.com/help/ruby/creating-and-registering-file-types.html


问:
Run a Docker image as a container
After building a Docker image from a dockerfile, I see the image was built successfully, but what do I do with it? Shouldn't i be able to run it as a container?

答:
To view a list of all images on your Docker host, run:

```<code>  $ docker images
   REPOSITORY          TAG           IMAGE ID            CREATED             SIZE
   apache_snapshot     latest        13037686eac3        22 seconds ago      249MB
   ubuntu              latest        00fd29ccc6f1        3 weeks ago         111MB
</code>```

Now you can run the Docker image as a container in interactive mode:

```<code>   $ docker run -it apache_snapshot /bin/bash
</code>```

OR if you don't have any images locally,Search Docker Hub for an image to download:

```<code>    $ docker search ubuntu
    NAME                            DESCRIPTION             STARS  OFFICIAL  AUTOMATED
    ubuntu                          Ubuntu is a Debian...   6759   [OK]
    dorowu/ubuntu-desktop-lxde-vnc  Ubuntu with openss...   141              [OK]
    rastasheep/ubuntu-sshd          Dockerized SSH ser...   114              [OK]
    ansible/ubuntu14.04-ansible     Ubuntu 14.04 LTS w...   88               [OK]
    ubuntu-upstart                  Upstart is an even...   80     [OK]
</code>```

Pull the Docker image from a repository with the docker pull command:

```<code>     $ docker pull ubuntu
</code>```

Run the Docker image as a container:

```<code>     $ docker run -it ubuntu /bin/bash
</code>```

Title: Run a Docker image as a container

Body:
To view a list of all images on your Docker host, run:

  $ docker images
   REPOSITORY          TAG           IMAGE ID            CREATED             SIZE
   apache_snapshot     latest        13037686eac3        22 seconds ago      249MB
   ubuntu              latest        00fd29ccc6f1        3 weeks ago         111MB

Now you can run the Docker image as a container in interactive mode:

   $ docker run -it apache_snapshot /bin/bash

OR if you don't have any images locally,Search Docker Hub for an image to download:

    $ docker search ubuntu
    NAME                            DESCRIPTION             STARS  OFFICIAL  AUTOMATED
    ubuntu                          Ubuntu is a Debian...   6759   [OK]
    dorowu/ubuntu-desktop-lxde-vnc  Ubuntu with openss...   141              [OK]
    rastasheep/ubuntu-sshd          Dockerized SSH ser...   114              [OK]
    ansible/ubuntu14.04-ansible     Ubuntu 14.04 LTS w...   88               [OK]
    ubuntu-upstart                  Upstart is an even...   80     [OK]

Pull the Docker image from a repository with the docker pull command:

     $ docker pull ubuntu

Run the Docker image as a container:

     $ docker run -it ubuntu /bin/bash


问:
Javascript - function doesn't get external input values from JQuery
I have the following function stored in my sdk.php file:

```<code><script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script>
function saveObject(params) {
    console.log('p: ' + params);
}
</script>
</code>```

In another php file - index.php - I call that function passing input values as parameters:

```<code>Text: <input type="text" name="aText" id="aText"><br>
Number: <input type="number" name="aNumber" id="aNumber"><br>
<script>
// Save object
var params = [
    'tableName=' + 'Test',
    '&ST_text=' + $('#aText').val(),
    '&NU_likes=' + $('#aNumber').val(),
].toString().replace(/,/g, '');
</script>
<a class="btn btn-info" href="#" onclick="saveObject(params)">Save Object</a>
</code>```

Now, if I type something in the 2 input files and hit the Save Object button, this is what I get in the Chrome console:

```<code>p: tableName=Test&ST_text=&NU_likes=
</code>```

Why am I not getting the aText and aNumber values in the string I compose?

I'm asking this because if I move the params array into the saveObject() function, I get the values.

What am I doing wrong?

答:
Your params are not being defined because the script is only executed on page load. You need to define the values after an event, like clicking the Save Object button.
Try something like this:

```<code><a class="btn btn-info" id="saveButton" href="#">Save Object</a>
</code>```

In jQuery:

```<code>$("#saveButton").click(function () {
var params = [//define params here];
saveObject(params);
});
</code>```

Body:
I have the following function stored in my sdk.php file:

In another php file - index.php - I call that function passing input values as parameters:

Text: <input type="text" name="aText" id="aText">

Number: <input type="number" name="aNumber" id="aNumber">

Save Object

Now, if I type something in the 2 input files and hit the Save Object button, this is what I get in the Chrome console:

p: tableName=Test&ST_text=&NU_likes=

Why am I not getting the aText and aNumber values in the string I compose?

I'm asking this because if I move the params array into the saveObject() function, I get the values.

What am I doing wrong?

Body:
Your params are not being defined because the script is only executed on page load. You need to define the values after an event, like clicking the Save Object button.
Try something like this:

<a class="btn btn-info" id="saveButton" href="#">Save Object</a>

In jQuery:

$("#saveButton").click(function () {
var params = [//define params here];
saveObject(params);
});


问:
data- attribute not working to grab dynamic id from foreach
I am using JS in a razor page to grab a dynamic ID from a col in a foreach.

In the past, I have used this and it worked fine. However, it seems that it is currently only grabbing the ID from the first col no matter which one I click.

Can someone please tell me if I am still doing this right? Or if I am missing something. Thank you.

View:

```<code>            <div class="list-group container" id="JobRequestMonitorTable">
            <div class="row list-group-item list-group-item-heading container divTableHeading" style="margin-bottom:0px;">
                <div class="col-md-4"> Job Code </div>
                <div class="col-md-4"> Description </div>
                <div class="col-md-2"> Schedule </div>
                <div class="col-md-1"> Running </div>
                <div class="col-md-1"></div>
            </div>
            @if (!string.IsNullOrEmpty(ViewBag.ErrorMessage))
            {
                <div class="row list-group-item-danger">
                    <div class="col-md-1 text-center">@ViewBag.ErrorMessage</div>
                </div>
            }
            @foreach (var item in Model.JobRequests)
            {
                <div class="row list-group-item container">
                    <div class="hidden" data-id="@item.JobRequestId" id="requestId">@item.JobRequestId</div>
                    <div class="col-md-4">@item.JobCode</div>
                    <div class="col-md-4">@item.Description</div>
                    <div class="col-md-2">@item.Schedule</div>
                    @if (@item.IsRunning == true)
                    {
                        <div class="col-md-1" style="margin-left:25px;"><span class="glyphicon glyphicon-ok"></span></div>
                        <div class="col-md-1"></div>
                    }
                    else
                    {
                        <div class="col-md-1"></div>
                        <div class="col-md-1">
                            <button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn"></button>
                        </div>
                    }
                </div>
            }
        </div>
</code>```

JS:

```<code>        $("button").click(function () {

            var col = $('#requestId');
            var jobRequestId = col.data('Id');

             $.ajax({
                url: '@Url.Action("JobPollerParameters", "Tools")',
                 data: { "jobRequestId": jobRequestId},
                 success: function (results) {

                    $modal = $('#paramsModal');
                    $modal.modal("show");

                     var arr = results;
                     //loop through arr created from dictionary to grab key(s)
                     for (var key in arr) {
                         if (arr.hasOwnProperty(key)) {
                             var myKey = key;
                         }
                     }

                     var name = myKey;
                     var value = results[myKey];

                    $('#modalName').text(name);
                     $('#modalMessage').text(value);

                }
            });
        });
</code>```

Really the only important part to see in the JS is var col = $('#requestId');
            var jobRequestId = col.data('Id');

But I suppose I will include the whole script just in case people ask.

答:
Once you have a button for each item, you could also store the data into the button value attribute, which leads to a simple implementation in the JS:

$("button").click(function (e) {

    var jobRequestId = $(e.target).val();
    console.log(jobRequestId);

    $.ajax({
        url: '@Url.Action("JobPollerParameters", "Tools")',
         data: { "jobRequestId": jobRequestId},
         success: function (results) {

            $modal = $('#paramsModal');
            $modal.modal("show");

             var arr = results;
             //loop through arr created from dictionary to grab key(s)
             for (var key in arr) {
                 if (arr.hasOwnProperty(key)) {
                     var myKey = key;
                 }
             }

             var name = myKey;
             var value = results[myKey];

            $('#modalName').text(name);
             $('#modalMessage').text(value);

        }
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="1">Job 1</button><br />
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="2">Job 2</button><br />
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="3">Job 3</button><br />
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="4">Job 4</button><br />
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="5">Job 5</button></code>```

Obs.: value must be equal to @item.JobRequestId like so: <button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="@item.JobRequestId">Job 5</button>

Body:
I am using JS in a razor page to grab a dynamic ID from a col in a foreach.

In the past, I have used this and it worked fine. However, it seems that it is currently only grabbing the ID from the first col no matter which one I click.

Can someone please tell me if I am still doing this right? Or if I am missing something. Thank you.

View:

 Job Code

 Description

 Schedule

 Running

            @if (!string.IsNullOrEmpty(ViewBag.ErrorMessage))
            {

@ViewBag.ErrorMessage

            }
            @foreach (var item in Model.JobRequests)
            {

@item.JobRequestId

@item.JobCode

@item.Description

@item.Schedule

                    @if (@item.IsRunning == true)
                    {

                    }
                    else
                    {

                            <button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn"></button>

                    }

            }

JS:

        $("button").click(function () {

            var col = $('#requestId');
            var jobRequestId = col.data('Id');

             $.ajax({
                url: '@Url.Action("JobPollerParameters", "Tools")',
                 data: { "jobRequestId": jobRequestId},
                 success: function (results) {

                    $modal = $('#paramsModal');
                    $modal.modal("show");

                     var arr = results;
                     //loop through arr created from dictionary to grab key(s)
                     for (var key in arr) {
                         if (arr.hasOwnProperty(key)) {
                             var myKey = key;
                         }
                     }

                     var name = myKey;
                     var value = results[myKey];

                    $('#modalName').text(name);
                     $('#modalMessage').text(value);

                }
            });
        });

Really the only important part to see in the JS is var col = $('#requestId');
            var jobRequestId = col.data('Id');

But I suppose I will include the whole script just in case people ask.

Body:
Once you have a button for each item, you could also store the data into the button value attribute, which leads to a simple implementation in the JS:

$("button").click(function (e) {

    var jobRequestId = $(e.target).val();
    console.log(jobRequestId);

    $.ajax({
        url: '@Url.Action("JobPollerParameters", "Tools")',
         data: { "jobRequestId": jobRequestId},
         success: function (results) {

            $modal = $('#paramsModal');
            $modal.modal("show");

             var arr = results;
             //loop through arr created from dictionary to grab key(s)
             for (var key in arr) {
                 if (arr.hasOwnProperty(key)) {
                     var myKey = key;
                 }
             }

             var name = myKey;
             var value = results[myKey];

            $('#modalName').text(name);
             $('#modalMessage').text(value);

        }
    });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="1">Job 1</button><br />
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="2">Job 2</button><br />
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="3">Job 3</button><br />
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="4">Job 4</button><br />
<button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="5">Job 5</button>

Obs.: value must be equal to @item.JobRequestId like so: <button class="glyphicon glyphicon-list-alt btn btn-primary" id="paramModalBtn" name="paramsBtn" value="@item.JobRequestId">Job 5</button>


问:
DefaultMessageListenerContainer stops processing messages
I'm hoping this is a simple configuration issue but I can't seem to figure out what it might be.

Set-up

Spring-Boor 2.2.2.RELEASE

cloud-starter

cloud-starter-aws

spring-jms

spring-cloud-dependencies Hoxton.SR1

amazon-sqs-java-messaging-lib 1.0.8

Problem

My application starts up fine and begins to process messages from Amazon SQS. After some amount of time I see the following warning

2020-02-01 04:16:21.482 LogLevel=WARN 1 --- [ecutor-thread14] o.s.j.l.DefaultMessageListenerContainer  : Number of scheduled consumers has dropped below concurrentConsumers limit, probably due to tasks having been rejected. Check your thread pool configuration! Automatic recovery to be triggered by remaining consumers.

The above warning gets printed multiple times and eventually I see the following two INFO messages

2020-02-01 04:17:51.552 LogLevel=INFO 1 --- [ecutor-thread40] c.a.s.javamessaging.SQSMessageConsumer   : Shutting down ConsumerPrefetch executor

2020-02-01 04:18:06.640 LogLevel=INFO 1 --- [ecutor-thread40] com.amazon.sqs.javamessaging.SQSSession  : Shutting down SessionCallBackScheduler executor

The above 2 messages will display several times and at some point no more messages are consumed from SQS. I don't see any other messages in my log to indicate an issue, but I get no messages from my handlers that they are processing messages (I have 2~) and I can see the AWS SQS queue growing in the number of messages and the age.

~: This exact code was working fine when I had a single handler, this problem started when I added the second one.

Configuration/Code

The first "WARNing" I realize is caused by the currency of the ThreadPoolTaskExecutor, but I can not get a configuration which works properly. Here is my current configuration for the JMS stuff, I have tried various levels of max pool size with no real affect other than the warings start sooner or later based on the pool size

```<code>    public ThreadPoolTaskExecutor asyncAppConsumerTaskExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setThreadGroupName("asyncConsumerTaskExecutor");
        taskExecutor.setThreadNamePrefix("asyncConsumerTaskExecutor-thread");
        taskExecutor.setCorePoolSize(10);
        // Allow the thread pool to grow up to 4 times the core size, evidently not
        // having the pool be larger than the max concurrency causes the JMS queue
        // to barf on itself with messages like
        // "Number of scheduled consumers has dropped below concurrentConsumers limit, probably due to tasks having been rejected. Check your thread pool configuration! Automatic recovery to be triggered by remaining consumers"
        taskExecutor.setMaxPoolSize(10 * 4);
        taskExecutor.setQueueCapacity(0); // do not queue up messages
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        taskExecutor.setAwaitTerminationSeconds(60);
        return taskExecutor;
    }
</code>```

Here is the JMS Container Factory we create

```<code>    public DefaultJmsListenerContainerFactory jmsListenerContainerFactory(SQSConnectionFactory sqsConnectionFactory, ThreadPoolTaskExecutor asyncConsumerTaskExecutor) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setConnectionFactory(sqsConnectionFactory);
        factory.setDestinationResolver(new DynamicDestinationResolver());
        // The JMS processor will start 'concurrency' number of tasks
        // and supposedly will increase this to the max of '10 * 3'
        factory.setConcurrency(10 + "-" + (10 * 3));
        factory.setTaskExecutor(asyncConsumerTaskExecutor);
        // Let the task process 100 messages, default appears to be 10
        factory.setMaxMessagesPerTask(100);
        // Wait up to 5 seconds for a timeout, this keeps the task around a bit longer
        factory.setReceiveTimeout(5000L);
        factory.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE);
        return factory;
    }
</code>```

I added the setMaxMessagesPerTask & setReceiveTimeout calls based on stuff found on the internet, the problem persists without these and at various settings (50, 2500L, 25, 1000L, etc...)

We create a default SQS connection factory

```<code>    public SQSConnectionFactory sqsConnectionFactory(AmazonSQS amazonSQS) {
        return new SQSConnectionFactory(new ProviderConfiguration(), amazonSQS);
    }
</code>```

Finally the handlers look like this

```<code>    @JmsListener(destination = "consumer-event-queue")
    public void receiveEvents(String message) throws IOException {
        MyEventDTO myEventDTO = jsonObj.readValue(message, MyEventDTO.class);
        //messageTask.process(myEventDTO);
    }

    @JmsListener(destination = "myalert-sqs")
    public void receiveAlerts(String message) throws IOException, InterruptedException {
        final MyAlertDTO myAlert = jsonObj.readValue(message, MyAlertDTO.class);
        myProcessor.addAlertToQueue(myAlert);
    }
</code>```

You can see in the first function (receiveEvents) we just take the message from the queue and exit, we have not implemented the processing code for that.
The second function (receiveAlerts) gets the message, the myProcessor.addAlertToQueue function creates a runnable object and submits it to a threadpool to be processed at some point in the future.

The problem only started (the warning, info and failure to consume messages) only started when we added the receiveAlerts function, previously the other function was the only one present and we did not see this behavior.

More

This is part of a larger project and I am working on breaking this code out into a smaller test case to see if I can duplicate this issue. I will post a follow-up with the results.

In the Mean Time

I'm hoping this is just a config issue and someone more familiar with this can tell me what I'm doing wrong, or that someone can provide some thoughts and comments on how to correct this to work properly.

Thank you!

答:
After fighting this one for a bit I think I finally resolved it.

The issue appears to be due to the "DefaultJmsListenerContainerFactory", this factory creates a new "DefaultJmsListenerContainer" for EACH method with a '@JmsListener' annotation. The person who originally wrote the code thought it was only called once for the application, and the created container would be re-used. So the issue was two-fold

The 'ThreadPoolTaskExecutor' attached to the factory had 40 threads, when the application had 1 '@JmsListener' method this worked fine, but when we aded a second method then each method got 10 threads (total of 20) for listening. This is fine, however; since we stated that each listener could grow up to 30 listeners we quickly ran out of threads in the pool mentioned in 1 above. This caused the "Number of scheduled consumers has dropped below concurrentConsumers limit" error

This is probably obvious given the above, but I wanted to call it out explicitly. In the Listener Factory we set the concurrency to be "10-30", however; all of the listeners have to share that pool. As such the max concurrency has to be setup so that each listeners' max value is small enough so that if each listener creates its maximum that it doesn't exceed the maximum number of threads in the pool (e.g. if we have 2 '@JmsListener' annotated methods and a pool with 40 threads, then the max value can be no more than 20).

Hopefully this might help someone else with a similar issue in the future....

Body:
I'm hoping this is a simple configuration issue but I can't seem to figure out what it might be.

Set-up

Spring-Boor 2.2.2.RELEASE

cloud-starter

cloud-starter-aws

spring-jms

spring-cloud-dependencies Hoxton.SR1

amazon-sqs-java-messaging-lib 1.0.8

Problem

My application starts up fine and begins to process messages from Amazon SQS. After some amount of time I see the following warning

2020-02-01 04:16:21.482 LogLevel=WARN 1 --- [ecutor-thread14] o.s.j.l.DefaultMessageListenerContainer  : Number of scheduled consumers has dropped below concurrentConsumers limit, probably due to tasks having been rejected. Check your thread pool configuration! Automatic recovery to be triggered by remaining consumers.

The above warning gets printed multiple times and eventually I see the following two INFO messages

2020-02-01 04:17:51.552 LogLevel=INFO 1 --- [ecutor-thread40] c.a.s.javamessaging.SQSMessageConsumer   : Shutting down ConsumerPrefetch executor

2020-02-01 04:18:06.640 LogLevel=INFO 1 --- [ecutor-thread40] com.amazon.sqs.javamessaging.SQSSession  : Shutting down SessionCallBackScheduler executor

The above 2 messages will display several times and at some point no more messages are consumed from SQS. I don't see any other messages in my log to indicate an issue, but I get no messages from my handlers that they are processing messages (I have 2~) and I can see the AWS SQS queue growing in the number of messages and the age.

~: This exact code was working fine when I had a single handler, this problem started when I added the second one.

Configuration/Code

The first "WARNing" I realize is caused by the currency of the ThreadPoolTaskExecutor, but I can not get a configuration which works properly. Here is my current configuration for the JMS stuff, I have tried various levels of max pool size with no real affect other than the warings start sooner or later based on the pool size

    public ThreadPoolTaskExecutor asyncAppConsumerTaskExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setThreadGroupName("asyncConsumerTaskExecutor");
        taskExecutor.setThreadNamePrefix("asyncConsumerTaskExecutor-thread");
        taskExecutor.setCorePoolSize(10);
        // Allow the thread pool to grow up to 4 times the core size, evidently not
        // having the pool be larger than the max concurrency causes the JMS queue
        // to barf on itself with messages like
        // "Number of scheduled consumers has dropped below concurrentConsumers limit, probably due to tasks having been rejected. Check your thread pool configuration! Automatic recovery to be triggered by remaining consumers"
        taskExecutor.setMaxPoolSize(10 * 4);
        taskExecutor.setQueueCapacity(0); // do not queue up messages
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        taskExecutor.setAwaitTerminationSeconds(60);
        return taskExecutor;
    }

Here is the JMS Container Factory we create

    public DefaultJmsListenerContainerFactory jmsListenerContainerFactory(SQSConnectionFactory sqsConnectionFactory, ThreadPoolTaskExecutor asyncConsumerTaskExecutor) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setConnectionFactory(sqsConnectionFactory);
        factory.setDestinationResolver(new DynamicDestinationResolver());
        // The JMS processor will start 'concurrency' number of tasks
        // and supposedly will increase this to the max of '10 * 3'
        factory.setConcurrency(10 + "-" + (10 * 3));
        factory.setTaskExecutor(asyncConsumerTaskExecutor);
        // Let the task process 100 messages, default appears to be 10
        factory.setMaxMessagesPerTask(100);
        // Wait up to 5 seconds for a timeout, this keeps the task around a bit longer
        factory.setReceiveTimeout(5000L);
        factory.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE);
        return factory;
    }

I added the setMaxMessagesPerTask & setReceiveTimeout calls based on stuff found on the internet, the problem persists without these and at various settings (50, 2500L, 25, 1000L, etc...)

We create a default SQS connection factory

    public SQSConnectionFactory sqsConnectionFactory(AmazonSQS amazonSQS) {
        return new SQSConnectionFactory(new ProviderConfiguration(), amazonSQS);
    }

Finally the handlers look like this

    @JmsListener(destination = "consumer-event-queue")
    public void receiveEvents(String message) throws IOException {
        MyEventDTO myEventDTO = jsonObj.readValue(message, MyEventDTO.class);
        //messageTask.process(myEventDTO);
    }

    @JmsListener(destination = "myalert-sqs")
    public void receiveAlerts(String message) throws IOException, InterruptedException {
        final MyAlertDTO myAlert = jsonObj.readValue(message, MyAlertDTO.class);
        myProcessor.addAlertToQueue(myAlert);
    }

You can see in the first function (receiveEvents) we just take the message from the queue and exit, we have not implemented the processing code for that.
The second function (receiveAlerts) gets the message, the myProcessor.addAlertToQueue function creates a runnable object and submits it to a threadpool to be processed at some point in the future.

The problem only started (the warning, info and failure to consume messages) only started when we added the receiveAlerts function, previously the other function was the only one present and we did not see this behavior.

More

This is part of a larger project and I am working on breaking this code out into a smaller test case to see if I can duplicate this issue. I will post a follow-up with the results.

In the Mean Time

I'm hoping this is just a config issue and someone more familiar with this can tell me what I'm doing wrong, or that someone can provide some thoughts and comments on how to correct this to work properly.

Thank you!


问:
Cant login with docker compose to Postgres via pgadmin
I have the following docker-compose:

```<code>version: '3.1'
services:
  db:
    image: postgres
    restart: always
    environment:
      POSTGRES_PASSWORD: postgres
    volumes:
      - postgres:/pgdata
    ports:
        - "5432:5432"

  pdadmin:
    image: dpage/pgadmin4
    restart: always
    ports:
      - "8080:80"
    environment:
     PGADMIN_DEFAULT_EMAIL: example@gmail.com
     PGADMIN_DEFAULT_PASSWORD: example

volumes:
  postgres:
</code>```

when I try to login to postgres via pgadmin i am getting the error: password authentication failed for user "postgres"

I am trying with user postgres and password postgres.

I also tryied to add explisit POSTGRES_USER to the env with no success.

How can I login to my postgres database?

Thanks

答:
you're very close:

```<code>version: '3.1'

services:
  db:
    image: postgres
    restart: always
    environment:
      POSTGRES_USER: postgres # <-- add this
      POSTGRES_PASSWORD: postgres
    volumes:
      - postgres:/pgdata
    ports:
      - "5432:5432"

  pdadmin:
    image: dpage/pgadmin4
    restart: always
    ports:
      - "8080:80"
    environment:
      PGADMIN_DEFAULT_EMAIL: example@gmail.com
      PGADMIN_DEFAULT_PASSWORD: example
    depends_on: # <-- add this
      - db # <-- add this
    links: # <-- add this
      - db # <-- add this

volumes:
  postgres:
</code>```

Then connect to pgadmin http://localhost:8080
when you want to add new server you need to add the IP of the container

```<code>docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' <container_id>
</code>```

That it !

Body:
I have the following docker-compose:

version: '3.1'
services:
  db:
    image: postgres
    restart: always
    environment:
      POSTGRES_PASSWORD: postgres
    volumes:
      - postgres:/pgdata
    ports:
        - "5432:5432"

  pdadmin:
    image: dpage/pgadmin4
    restart: always
    ports:
      - "8080:80"
    environment:
     PGADMIN_DEFAULT_EMAIL: example@gmail.com
     PGADMIN_DEFAULT_PASSWORD: example

volumes:
  postgres:

when I try to login to postgres via pgadmin i am getting the error: password authentication failed for user "postgres"

I am trying with user postgres and password postgres.

I also tryied to add explisit POSTGRES_USER to the env with no success.

How can I login to my postgres database?

Thanks

Body:
you're very close:

version: '3.1'

services:
  db:
    image: postgres
    restart: always
    environment:
      POSTGRES_USER: postgres # <-- add this
      POSTGRES_PASSWORD: postgres
    volumes:
      - postgres:/pgdata
    ports:
      - "5432:5432"

  pdadmin:
    image: dpage/pgadmin4
    restart: always
    ports:
      - "8080:80"
    environment:
      PGADMIN_DEFAULT_EMAIL: example@gmail.com
      PGADMIN_DEFAULT_PASSWORD: example
    depends_on: # <-- add this
      - db # <-- add this
    links: # <-- add this
      - db # <-- add this

volumes:
  postgres:

Then connect to pgadmin http://localhost:8080
when you want to add new server you need to add the IP of the container

docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' <container_id>

That it !


问:
Javascript array reduce return zero instead of undefined
I've got an example array that I'm trying to reduce by the counts of the occurrence of a key (sentiment in this example):

const sentimentLog = [
  {
    id: 1,
    createdOn: new Date('2020-02-13'),
    sentiment: 1
  },
  {
    id: 2,
    createdOn: new Date('2020-02-12'),
    sentiment: 1
  },
  {
    id: 3,
    createdOn: new Date('2020-02-12'),
    sentiment: 2
  },
  {
    id: 4,
    createdOn: new Date('2020-02-11'),
    sentiment: 3
  },
  {
    id: 5,
    createdOn: new Date('2020-02-11'),
    sentiment: 2
  },
  {
    id: 6,
    createdOn: new Date('2020-02-10'),
    sentiment: 1
  },
  {
    id: 7,
    createdOn: new Date('2020-02-10'),
    sentiment: 2
  },
  {
    id: 8,
    createdOn: new Date('2020-02-09'),
    sentiment: 1
  }
]
```

<p>I'm using:</p>

<pre class="lang-js prettyprint-override"><code>const sentimentGrouped = (sentiments) => {
  return sentiments.reduce((hash, { sentiment }) => {
    hash[sentiment] = (hash[sentiment] || 0) + 1
    return hash
  }, [])
}
</code>```

And it's nearly there. What I can't figure out is how to replace undefined when there's no sentiment scores of 0 (which is a possibility).

console.log('sentimentGrouped', sentimentGrouped(sentimentLog))
```

<p>The above produces:</p>

```"sentimentGrouped" [undefined, 4, 3, 1]
```

<p>Whereas I'd like:</p>

```"sentimentGrouped" [0, 4, 3, 1]
```

What am I missing?

Thanks in advance.

Edit: I'll elaborate a bit further, there's 4 scores that will be returned (0 to 3). The data returned will be based on a date range. So there may be instances where there'll be no 1s returned, similarly no 3s returned by a different date range.

答:
The issue is that if you never touch an element of the array, then it stays as a hole in the array, which means it's treated as undefined. Since you know the length of the array i would just prefill the array with zeros. Any sentiment score that does occur will be incremented. Any one that doesn't will stay with its initial value.</p>

```<code>return sentiments.reduce((hash, { sentiment }) => {
  hash[sentiment] = hash[sentiment] + 1
  return hash
}, [0, 0, 0, 0])
</code>```

Body:
I've got an example array that I'm trying to reduce by the counts of the occurrence of a key (sentiment in this example):

const sentimentLog = [
  {
    id: 1,
    createdOn: new Date('2020-02-13'),
    sentiment: 1
  },
  {
    id: 2,
    createdOn: new Date('2020-02-12'),
    sentiment: 1
  },
  {
    id: 3,
    createdOn: new Date('2020-02-12'),
    sentiment: 2
  },
  {
    id: 4,
    createdOn: new Date('2020-02-11'),
    sentiment: 3
  },
  {
    id: 5,
    createdOn: new Date('2020-02-11'),
    sentiment: 2
  },
  {
    id: 6,
    createdOn: new Date('2020-02-10'),
    sentiment: 1
  },
  {
    id: 7,
    createdOn: new Date('2020-02-10'),
    sentiment: 2
  },
  {
    id: 8,
    createdOn: new Date('2020-02-09'),
    sentiment: 1
  }
]

I'm using:

const sentimentGrouped = (sentiments) => {
  return sentiments.reduce((hash, { sentiment }) => {
    hash[sentiment] = (hash[sentiment] || 0) + 1
    return hash
  }, [])
}

And it's nearly there. What I can't figure out is how to replace undefined when there's no sentiment scores of 0 (which is a possibility).

console.log('sentimentGrouped', sentimentGrouped(sentimentLog))

The above produces:

"sentimentGrouped" [undefined, 4, 3, 1]

Whereas I'd like:

"sentimentGrouped" [0, 4, 3, 1]

What am I missing?

Thanks in advance.

Edit: I'll elaborate a bit further, there's 4 scores that will be returned (0 to 3). The data returned will be based on a date range. So there may be instances where there'll be no 1s returned, similarly no 3s returned by a different date range.

Body:
The issue is that if you never touch an element of the array, then it stays as a hole in the array, which means it's treated as undefined. Since you know the length of the array i would just prefill the array with zeros. Any sentiment score that does occur will be incremented. Any one that doesn't will stay with its initial value.

return sentiments.reduce((hash, { sentiment }) => {
  hash[sentiment] = hash[sentiment] + 1
  return hash
}, [0, 0, 0, 0])


问:
Append a json object to another json object java
I have a two json objects

```<code>JSONObject org_query = new JSONObject("{\"query\": {\"bool\": {\"must\": [], \"must_not\": [], \"should\": []}}}");

JSONObject query_form = new JSONObject("{\"match_phrase\": {\"Sales Channel\": \"Online\"}}");
</code>```

I want to append the second object to first one inside the key must and form a new JSON object.

Required Output:

```<code>{"query":{"bool":{"must_not":[],"should":[],"must":[{"match_phrase": {"Sales Channel": "Online"}}]}}}
</code>```

I tried this,

```<code>org_query["query"]["bool"]["must"].append(query_form);
</code>```

But shows error.

```<code>array type expected found org.json.jsonarray java
</code>```

How to make it

答:
In this case you can do:</p>

```<code>org_query = org_query.put("query", org_query.getJSONObject("query").put("bool", org_query.getJSONObject("query").getJSONObject("bool").append("must", query_form)));
</code>```

Body:
I have a two json objects

JSONObject org_query = new JSONObject("{\"query\": {\"bool\": {\"must\": [], \"must_not\": [], \"should\": []}}}");

JSONObject query_form = new JSONObject("{\"match_phrase\": {\"Sales Channel\": \"Online\"}}");

I want to append the second object to first one inside the key must and form a new JSON object.

Required Output:

{"query":{"bool":{"must_not":[],"should":[],"must":[{"match_phrase": {"Sales Channel": "Online"}}]}}}

I tried this,

org_query["query"]["bool"]["must"].append(query_form);

But shows error.

array type expected found org.json.jsonarray java

How to make it

Body:
In this case you can do:

org_query = org_query.put("query", org_query.getJSONObject("query").put("bool", org_query.getJSONObject("query").getJSONObject("bool").append("must", query_form)));


问:
Loading page fragments using $.post in jQuery
I am fetching 2 div's from a page using $.post jQuery AJAX request.  Now the data that comes after the execution is from a POST request and is something like this...

```<code>//data.php
<div id="alpha">alpha</div><div id="beta">beta</div>
</code>```

Now if i want to load the data of just the div with id 'alpha' into a div with id 'container' in the present page and if the data came by a GET request my life would be easier...

```<code>$("#container").load('data.php #alpha');
</code>```

would solve the problem.

I want to do similar filtering on success function using $.post function in jQuery so i can load the appropriate div's at the appropriate page in the current page.  How can i achieve this?

```<code>$.post('data.php',null,function(data){
//what to do here?
});
</code>```

Thanks

Body:
I am fetching 2 div's from a page using $.post jQuery AJAX request.  Now the data that comes after the execution is from a POST request and is something like this...

//data.php

alpha

beta

Now if i want to load the data of just the div with id 'alpha' into a div with id 'container' in the present page and if the data came by a GET request my life would be easier...

$("#container").load('data.php #alpha');

would solve the problem.

I want to do similar filtering on success function using $.post function in jQuery so i can load the appropriate div's at the appropriate page in the current page.  How can i achieve this?

$.post('data.php',null,function(data){
//what to do here?
});

Thanks

Body: $('#container').append($(data).find('#alpha'));


问:
Button hover doesnt do anything
I have these hover effects set up and it doesn't seem to be changing a thing. I can't figure out why.

Same thing happens with the primary button at the bottom.

body { background-color: #aaa }

.button {
  background: #fff;
  border-radius: 5px;
  border: none;
  padding: 5px;
  width: 100px;
  height: 50px;
}

.button:hover {
  background: #1c1c1c;
  color: #fff;
  transition: 0.3s ease;
  cursor: pointer;
}

.button-primary {
  background: yellow;
  border-radius: 5px;
  border: none;
  padding: 5px;
  width: 100px;
  height: 50px;
  margin-bottom: 10px;
}

.button-primary:hover {
  background: #1c1c1c;
  transition: 0.3s ease;
}

.button-down {
  height: 70px;
  width: 70px;
  border-radius: 50%;
  border: 1px solid white;
  background: transparent;
  color: white;
}

.button-down:hover {
  background: white;
  color: #1c1c1c;
  border: 1px solid #1c1c1c;
  cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <div class="down">
    <button class='button-down'><i class='fas fa-arrow-down'></i></button>
  </div>

  <input type="text" name='email' id='email' placeholder='signup to our newsletter...'>
  <br>
  <button class='button-primary' type='submit' name='submit'>Submit</button>
</div></code>```

答:
You linked your stylesheet to your html?
Also, .button-down class in is not declared in css  but instead you have .button
Replace .button with .button-down and try again.</p>

```<code>.button-down{
    background: #fff;
    border-radius: 5px;
    border: none;
    padding: 5px;
    width: 100px;
    height: 50px;
}
.button-down:hover{
    background: #1c1c1c;
    color: #fff;
    transition: 0.3s ease;
    cursor: pointer;
}
</code>```

Title: Button hover doesnt do anything

Body:
I have these hover effects set up and it doesn't seem to be changing a thing. I can't figure out why.

Same thing happens with the primary button at the bottom.

body { background-color: #aaa }

.button {
  background: #fff;
  border-radius: 5px;
  border: none;
  padding: 5px;
  width: 100px;
  height: 50px;
}

.button:hover {
  background: #1c1c1c;
  color: #fff;
  transition: 0.3s ease;
  cursor: pointer;
}

.button-primary {
  background: yellow;
  border-radius: 5px;
  border: none;
  padding: 5px;
  width: 100px;
  height: 50px;
  margin-bottom: 10px;
}

.button-primary:hover {
  background: #1c1c1c;
  transition: 0.3s ease;
}

.button-down {
  height: 70px;
  width: 70px;
  border-radius: 50%;
  border: 1px solid white;
  background: transparent;
  color: white;
}

.button-down:hover {
  background: white;
  color: #1c1c1c;
  border: 1px solid #1c1c1c;
  cursor: pointer;
}

    <button class='button-down'></button>

  <input type="text" name='email' id='email' placeholder='signup to our newsletter...'>

  <button class='button-primary' type='submit' name='submit'>Submit</button>

Body:
You linked your stylesheet to your html?
Also, .button-down class in is not declared in css  but instead you have .button
Replace .button with .button-down and try again.

.button-down{
    background: #fff;
    border-radius: 5px;
    border: none;
    padding: 5px;
    width: 100px;
    height: 50px;
}
.button-down:hover{
    background: #1c1c1c;
    color: #fff;
    transition: 0.3s ease;
    cursor: pointer;
}


问:
Is there a way to remove italic style from  tag without effecting document.execCommand("italic")
I'd like to make text in  tag not appear italic in a contenteditable div.

However, as you can see in the code snippet below, if I add font-style:normal to italic style, document.execCommand('italic') to unitalicize no longer works, as the browser correctly detects that the text is not italic.

Would there be any way to have both unitalic-looking  and a way to unitalicize?

function italicize(){
  document.execCommand("italic");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>i{
  font-style:normal;
  color:red;
}</code>```

abc

<button onclick=italicize()>italic</button>```

答:
function italicize() {
  let myDiv = document.querySelector("#myDiv");
  myDiv.style.fontStyle.localeCompare("italic") ? myDiv.style.fontStyle = "italic" : myDiv.style.fontStyle = "normal";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>i {
  font-style: normal;
  color: red;
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Document</title>

abc

  <button onclick="italicize()">italic</button>

```

Is this what you are looking for? #newToStackOverflow

Title: Is there a way to remove italic style from <i> tag without effecting document.execCommand("italic")

Body:
I'd like to make text in  tag not appear italic in a contenteditable div.

However, as you can see in the code snippet below, if I add font-style:normal to italic style, document.execCommand('italic') to unitalicize no longer works, as the browser correctly detects that the text is not italic.

Would there be any way to have both unitalic-looking  and a way to unitalicize?

function italicize(){
  document.execCommand("italic");
}

i{
  font-style:normal;
  color:red;
}

abc

<button onclick=italicize()>italic</button>

Body:
function italicize() {
  let myDiv = document.querySelector("#myDiv");
  myDiv.style.fontStyle.localeCompare("italic") ? myDiv.style.fontStyle = "italic" : myDiv.style.fontStyle = "normal";
}

i {
  font-style: normal;
  color: red;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>

<body>
  <div id="myDiv" contenteditable=true>a<i>b</i>c</div>
  <button onclick="italicize()">italic</button>
</body>

</html>

Is this what you are looking for? #newToStackOverflow


问:
throws Exception in finally blocks
Is there an elegant way to handle exceptions that are thrown in finally block?

For example:

```<code>try {
  // Use the resource.
}
catch( Exception ex ) {
  // Problem with the resource.
}
finally {
   try{
     resource.close();
   }
   catch( Exception ex ) {
     // Could not close the resource?
   }
}
</code>```

How do you avoid the try/catch in the finally block?

答:
I encountered a situation similar where I couldn't use try with resources but I also wanted to handle the exception coming from the close, not just log and ignore it like closeQuietly mechanism do. in my case I'm not actually dealing with an output stream, so the failure on close is of more interest than a simple stream.</p>

```<code>IOException ioException = null;
try {
  outputStream.write("Something");
  outputStream.flush();
} catch (IOException e) {
  throw new ExportException("Unable to write to response stream", e);
}
finally {
  try {
    outputStream.close();
  } catch (IOException e) {
    ioException = e;
  }
}
if (ioException != null) {
  throw new ExportException("Unable to close outputstream", ioException);
}
</code>```

OwnerDisplayName: Paul

Title: throws Exception in finally blocks

Body:
Is there an elegant way to handle exceptions that are thrown in finally block?

For example:

try {
  // Use the resource.
}
catch( Exception ex ) {
  // Problem with the resource.
}
finally {
   try{
     resource.close();
   }
   catch( Exception ex ) {
     // Could not close the resource?
   }
}

How do you avoid the try/catch in the finally block?

LastEditorDisplayName: uzhin

Body:
I encountered a situation similar where I couldn't use try with resources but I also wanted to handle the exception coming from the close, not just log and ignore it like closeQuietly mechanism do. in my case I'm not actually dealing with an output stream, so the failure on close is of more interest than a simple stream.

IOException ioException = null;
try {
  outputStream.write("Something");
  outputStream.flush();
} catch (IOException e) {
  throw new ExportException("Unable to write to response stream", e);
}
finally {
  try {
    outputStream.close();
  } catch (IOException e) {
    ioException = e;
  }
}
if (ioException != null) {
  throw new ExportException("Unable to close outputstream", ioException);
}


答:
One way to do this can be by creating a specific style rule that removes the default italic style from all  elements inside a
.

Then, with querySelectorAll you can target all the  that live inside a
 attribute and make the text italicized by toggling a class:

function italicize() {
  let contentDivs = document.querySelectorAll('[contenteditable="true"] > i')
  for (let div of contentDivs) {
    div.classList.toggle('add-italic');
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div > i {
  font-style: normal;
  color: red;
}

.add-italic {
  font-style: italic;
}</code>```

abc

<button onclick="italicize()">italic</button>```

Body:
One way to do this can be by creating a specific style rule that removes the default italic style from all <i> elements inside a <div>.

Then, with querySelectorAll you can target all the <i> that live inside a <div contenteditable="true"> attribute and make the text italicized by toggling a class:

function italicize() {
  let contentDivs = document.querySelectorAll('[contenteditable="true"] > i')
  for (let div of contentDivs) {
    div.classList.toggle('add-italic');
  }
}

div > i {
  font-style: normal;
  color: red;
}

.add-italic {
  font-style: italic;
}

<div contenteditable="true">a<i>b</i>c</div>

<button onclick="italicize()">italic</button>