问:
ShellExecute (and ShellExecuteEx) do nothing with my URL
I'm creating a project with C++Builder XE7, in which a user can click on a button to open a web link, e.g. to open a support page, or to share his experience on a social media. For that, I use the ShellExecute() function, and it works well, except for one button.

When I click on this button, simply nothing happens. The ShellExecute() function returns without error (the returned value is 42), but my default browser does not open, and the web page isn't shown at all.

Here is my ShellExecute() implementation

const HINSTANCE result = ::ShellExecute(handle, "open", url.c_str(), NULL, NULL, SW_SHOWDEFAULT);
```

<p>I also tried the <code>ShellExecuteEx()</code> function:</p>

<pre class="lang-cpp prettyprint-override"><code>::SHELLEXECUTEINFO info;
std::memset(&info, 0, sizeof(info));
info.cbSize = sizeof(info);
info.hwnd   = handle;
info.lpVerb = "open";
info.lpFile = url.c_str();
info.nShow  = SW_SHOWDEFAULT;

if (!::ShellExecuteEx(&info))
</code>```

The url parameter contains the website link I am trying to open. For security reasons, I cannot post it here as a sample, however I tested it in my browser (FireFox) and it works well. On the other hand, if I execute my code by just replacing the url content with Google's website, all works as expected.

The handle is just the Handle parameter of the parent frame.

I also tried to tweak the ShellExecute/Ex() parameters, like the hwnd and nShow fields, but no change.

Can anybody point me to what is wrong?

答:
The url is formatted like this: http:// www.
mysite.xxx/selectPage.php?arg1=xxx&arg2=yyy&...&argX=a text containing
"quotes" and some %26amp%3b special chars!

In this example you have to URL-encode the double quotes and the spaces because these are not valid characters for the query part of an URL.

Fix it by replacing double quotes with %22 and spaces with %20. I suggest to use a function like UrlEscape() to properly encode the URL.

Although most browsers have an error tolerance for user input and will also accept an URL which does not have valid encoding, it's better to strictly follow the spec because you are not guaranteed that tolerance.

In addition, the double quotes will make problems when the URL is passed as a command-line argument to the command associated with the URL protocol. This is because double quotes are reserved characters for defining command-line parameters that contain spaces.

For instance, on my machine the http protocol is associated with the following command (see HKEY_CLASSES_ROOT\http\shell\open\command):

"C:\Program Files (x86)\Mozilla Firefox\firefox.exe" -osint -url "%1"

You can see that the double quotes are already used to enclose the last parameter, which obviously gets messed up if you have unencoded double quotes within the URL.

Example for correctly encoding an URL for use with ShellExecuteEx():

```<code>#include <windows.h>
#include <Shellapi.h>

int main()
{
    ::CoInitialize(nullptr);

    SHELLEXECUTEINFOW info{ sizeof(info) };
    info.fMask  = SEE_MASK_NOASYNC; // because we exit process after ShellExecuteEx()
    info.lpVerb = L"open";
    info.lpFile = L"http://www.google.de/search?q=ShellExecuteEx%20URL%20%22double%20quotes%22";
    info.nShow  = SW_SHOWDEFAULT;

    if( !::ShellExecuteExW( &info ) )
    {
        DWORD err = ::GetLastError();
        printf("ShellExecuteEx failed with error %d\n", err );
    }

    ::CoUninitialize();
}
</code>```

Body:
I'm creating a project with C++Builder XE7, in which a user can click on a button to open a web link, e.g. to open a support page, or to share his experience on a social media. For that, I use the ShellExecute() function, and it works well, except for one button.

When I click on this button, simply nothing happens. The ShellExecute() function returns without error (the returned value is 42), but my default browser does not open, and the web page isn't shown at all.

Here is my ShellExecute() implementation

const HINSTANCE result = ::ShellExecute(handle, "open", url.c_str(), NULL, NULL, SW_SHOWDEFAULT);

I also tried the ShellExecuteEx() function:

::SHELLEXECUTEINFO info;
std::memset(&info, 0, sizeof(info));
info.cbSize = sizeof(info);
info.hwnd   = handle;
info.lpVerb = "open";
info.lpFile = url.c_str();
info.nShow  = SW_SHOWDEFAULT;

if (!::ShellExecuteEx(&info))

The url parameter contains the website link I am trying to open. For security reasons, I cannot post it here as a sample, however I tested it in my browser (FireFox) and it works well. On the other hand, if I execute my code by just replacing the url content with Google's website, all works as expected.

The handle is just the Handle parameter of the parent frame.

I also tried to tweak the ShellExecute/Ex() parameters, like the hwnd and nShow fields, but no change.

Can anybody point me to what is wrong?

Body:
The url is formatted like this: http:// www.
mysite.xxx/selectPage.php?arg1=xxx&arg2=yyy&...&argX=a text containing
"quotes" and some %26amp%3b special chars!

In this example you have to URL-encode the double quotes and the spaces because these are not valid characters for the query part of an URL.

Fix it by replacing double quotes with %22 and spaces with %20. I suggest to use a function like UrlEscape() to properly encode the URL.

Although most browsers have an error tolerance for user input and will also accept an URL which does not have valid encoding, it's better to strictly follow the spec because you are not guaranteed that tolerance.

In addition, the double quotes will make problems when the URL is passed as a command-line argument to the command associated with the URL protocol. This is because double quotes are reserved characters for defining command-line parameters that contain spaces.

For instance, on my machine the http protocol is associated with the following command (see HKEY_CLASSES_ROOT\http\shell\open\command):

"C:\Program Files (x86)\Mozilla Firefox\firefox.exe" -osint -url "%1"

You can see that the double quotes are already used to enclose the last parameter, which obviously gets messed up if you have unencoded double quotes within the URL.

Example for correctly encoding an URL for use with ShellExecuteEx():

#include <windows.h>
#include <Shellapi.h>

int main()
{
    ::CoInitialize(nullptr);

    SHELLEXECUTEINFOW info{ sizeof(info) };
    info.fMask  = SEE_MASK_NOASYNC; // because we exit process after ShellExecuteEx()
    info.lpVerb = L"open";
    info.lpFile = L"http://www.google.de/search?q=ShellExecuteEx%20URL%20%22double%20quotes%22";
    info.nShow  = SW_SHOWDEFAULT;

    if( !::ShellExecuteExW( &info ) )
    {
        DWORD err = ::GetLastError();
        printf("ShellExecuteEx failed with error %d\n", err );
    }

    ::CoUninitialize();
}


来源: stackexchange

问:
What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?
Can anybody give a clear explanation of how variable assignment really works in Makefiles.

What is the difference between :

```<code> VARIABLE = value
 VARIABLE ?= value
 VARIABLE := value
 VARIABLE += value
</code>```

I have read the section in GNU Make's manual, but it still doesn't make sense to me.

答:
When you use VARIABLE = value, if value is actually a reference to another variable, then the value is only determined when VARIABLE is used. This is best illustrated with an example:

```<code>VAL = foo
VARIABLE = $(VAL)
VAL = bar

# VARIABLE and VAL will both evaluate to "bar"
</code>```

When you use VARIABLE := value, you get the value of value as it is now. For example:

```<code>VAL = foo
VARIABLE := $(VAL)
VAL = bar

# VAL will evaluate to "bar", but VARIABLE will evaluate to "foo"
</code>```

Using VARIABLE ?= val means that you only set the value of VARIABLE if VARIABLE is not set already. If it's not set already, the setting of the value is deferred until VARIABLE is used (as in example 1).

VARIABLE += value just appends value to VARIABLE. The actual value of value is determined as it was when it was initially set, using either = or :=.

OwnerDisplayName: mmoris

ContentLicense: CC BY-SA 3.0

Body:
Can anybody give a clear explanation of how variable assignment really works in Makefiles.

What is the difference between :

 VARIABLE = value
 VARIABLE ?= value
 VARIABLE := value
 VARIABLE += value

I have read the section in GNU Make's manual, but it still doesn't make sense to me.

Body:
When you use VARIABLE = value, if value is actually a reference to another variable, then the value is only determined when VARIABLE is used. This is best illustrated with an example:

VAL = foo
VARIABLE = $(VAL)
VAL = bar

# VARIABLE and VAL will both evaluate to "bar"

When you use VARIABLE := value, you get the value of value as it is now. For example:

VAL = foo
VARIABLE := $(VAL)
VAL = bar

# VAL will evaluate to "bar", but VARIABLE will evaluate to "foo"

Using VARIABLE ?= val means that you only set the value of VARIABLE if VARIABLE is not set already. If it's not set already, the setting of the value is deferred until VARIABLE is used (as in example 1).

VARIABLE += value just appends value to VARIABLE. The actual value of value is determined as it was when it was initially set, using either = or :=.

OwnerDisplayName: mipadi

ContentLicense: CC BY-SA 2.5


问:
App works in Simulator but not on Device - NSMutableArray
I have a problem with my app, which run well on the simulator but when I launch on my iDevice I got an error:

```<code>     Terminating app due to uncaught exception 'NSInvalidArgumentException',
         reason: '*** -[NSMutableArray insertObject:atIndex:]: attempt to insert nil object at 0'

    0   CoreFoundation                      0x3513cfd3 __exceptionPreprocess + 114
    1   libobjc.A.dylib                     0x303928a5 objc_exception_throw + 24
    2   CoreFoundation                      0x350bff99 -[__NSArrayM insertObject:atIndex:] + 472
    3   CoreFoundation                      0x350bfda7 -[__NSArrayM addObject:] + 34
    ....
    Program received signal:  “SIGABRT”.
</code>```

In the debugger I can see where is the problem. The error comes from there, at the addObject:

```<code>for (int i = 0; i < [arrayValues count]; i++) {
    f = [[NSNumberFormatter alloc] init];
    [f setNumberStyle:NSNumberFormatterDecimalStyle];
    myNumber =[f numberFromString:[arrayValues objectAtIndex:i]];

    [arrayValues2 addObject:myNumber];
    [f release];    }
</code>```

Here I convert objects of arrayValues (NSString) in NSNumbers in arrayValues2.

In the Simulator there is no problem, the arrays are not empties.
I don't know where to look for.

I also checked the other posts of stackoverflow, they are not really like my error

答:
well... I'm not sure what your problem is, but there is a much better way to do this...

```<code>for(NSString *theString in arrayValues){
    NSNumber *aNumber = [NSNumber numberWithFloat:[theString floatValue]];
    [arrayValues2 addObject:aNumber];
}
</code>```

which may help because you won't be outstepping any array boundaries, or inserting any nil objects.

If you want some more help you're going to have to NSLog arrayValues and give us the output so we can see what you're dealing with. :)

Body:
I have a problem with my app, which run well on the simulator but when I launch on my iDevice I got an error:

     Terminating app due to uncaught exception 'NSInvalidArgumentException',
         reason: '*** -[NSMutableArray insertObject:atIndex:]: attempt to insert nil object at 0'

    0   CoreFoundation                      0x3513cfd3 __exceptionPreprocess + 114
    1   libobjc.A.dylib                     0x303928a5 objc_exception_throw + 24
    2   CoreFoundation                      0x350bff99 -[__NSArrayM insertObject:atIndex:] + 472
    3   CoreFoundation                      0x350bfda7 -[__NSArrayM addObject:] + 34
    ....
    Program received signal:  “SIGABRT”.

In the debugger I can see where is the problem. The error comes from there, at the addObject:

for (int i = 0; i < [arrayValues count]; i++) {
    f = [[NSNumberFormatter alloc] init];
    [f setNumberStyle:NSNumberFormatterDecimalStyle];
    myNumber =[f numberFromString:[arrayValues objectAtIndex:i]];

    [arrayValues2 addObject:myNumber];
    [f release];    }

Here I convert objects of arrayValues (NSString) in NSNumbers in arrayValues2.

In the Simulator there is no problem, the arrays are not empties.
I don't know where to look for.

I also checked the other posts of stackoverflow, they are not really like my error

Body:
well... I'm not sure what your problem is, but there is a much better way to do this...

for(NSString *theString in arrayValues){
    NSNumber *aNumber = [NSNumber numberWithFloat:[theString floatValue]];
    [arrayValues2 addObject:aNumber];
}

which may help because you won't be outstepping any array boundaries, or inserting any nil objects.

If you want some more help you're going to have to NSLog arrayValues and give us the output so we can see what you're dealing with. :)


问:
C++ slow loop computation
I have the following loop for a monte-carlo computation I am performing:

the variables below are pre-computed/populated and is defined as:

```<code>    w_ = std::vector<std::vector<double>>(150000, std::vector<double>(800));
    C_ = Eigen::MatrixXd(800,800);
    Eigen::VectorXd a(800);
    Eigen::VectorXd b(800);
</code>```

The while loop is taking me about 570 seconds to compute.Just going by the the loops I understand that I have nPaths*m = 150,000 * 800 = 120,000,000 sets of computations happening (I have not taken into account the cdf computations handled by boost libraries).

I am a below average programmer and was wondering if there are any obvious mistakes which I am making which maybe slowing the computation down. Or is there any other way to handle the computation which can speed things up.

```<code>    int N(0);
    int nPaths(150000);
    int m(800);
    double Varsum(0.);
    double err;
    double delta;
    double v1, v2, v3, v4;

    Eigen::VectorXd d = Eigen::VectorXd::Zero(m);
    Eigen::VectorXd e = Eigen::VectorXd::Zero(m);
    Eigen::VectorXd f = Eigen::VectorXd::Zero(m);
    Eigen::VectorXd y;
    y0 = Eigen::VectorXd::Zero(m);
    boost::math::normal G(0, 1.);
    d(0) = boost::math::cdf(G, a(0) / C_(0, 0));
    e(0) = boost::math::cdf(G, b(0) / C_(0, 0));
    f(0) = e(0) - d(0);
    while (N < (nPaths-1))
    {
        y = y0;
        for (int i = 1; i < m; i++)
        {
            v1 = d(i - 1) + w_[N][(i - 1)]*(e(i - 1) - d(i - 1));
            y(i - 1) = boost::math::quantile(G, v1);
            v2 = (a(i) - C_.row(i).dot(y)) / C_(i, i);
            v3 = (b(i) - C_.row(i).dot(y)) / C_(i, i);
            d(i) = boost::math::cdf(G, v2);
            e(i) = boost::math::cdf(G, v3);
            f(i) = (e(i) - d(i))*f(i - 1);
        }

        N++;
        delta = (f(m-1) - Intsum) / N;
        Intsum += delta;
        Varsum = (N - 2)*Varsum / N + delta*delta;
        err = alpha_*std::sqrt(Varsum);
   }
</code>```

答:
If I understand your code right, the running time is actually O(nPaths*m*m)=10^11, due to  the dot-product C_.row(i).dot(y) which needs O(m) operation.

You could speed up the program by factor of two by not calculating it twice:

```<code>double prod=C_.row(i).dot(y)
v2 = (a(i) - prod) / C_(i, i);
v3 = (b(i) - prod) / C_(i, i);
</code>```

but maybe compiler already does it for you.

The other thing is that y consists of zeros (at least at the beginning) so you don't have to do the full dot-product but only until current value of i. That should give another factor 2 speed up.

So taken into the account the sheer number of operation your timings are not so bad. There is some room for improvement of the code, but if you are interested in speeding up some orders of magnitude you probably should be thinking about changing your formulation.

Title: C++ slow loop computation

Body:
I have the following loop for a monte-carlo computation I am performing:

the variables below are pre-computed/populated and is defined as:

    w_ = std::vector<std::vector<double>>(150000, std::vector<double>(800));
    C_ = Eigen::MatrixXd(800,800);
    Eigen::VectorXd a(800);
    Eigen::VectorXd b(800);

The while loop is taking me about 570 seconds to compute.Just going by the the loops I understand that I have nPaths*m = 150,000 * 800 = 120,000,000 sets of computations happening (I have not taken into account the cdf computations handled by boost libraries).

I am a below average programmer and was wondering if there are any obvious mistakes which I am making which maybe slowing the computation down. Or is there any other way to handle the computation which can speed things up.

    int N(0);
    int nPaths(150000);
    int m(800);
    double Varsum(0.);
    double err;
    double delta;
    double v1, v2, v3, v4;

    Eigen::VectorXd d = Eigen::VectorXd::Zero(m);
    Eigen::VectorXd e = Eigen::VectorXd::Zero(m);
    Eigen::VectorXd f = Eigen::VectorXd::Zero(m);
    Eigen::VectorXd y;
    y0 = Eigen::VectorXd::Zero(m);
    boost::math::normal G(0, 1.);
    d(0) = boost::math::cdf(G, a(0) / C_(0, 0));
    e(0) = boost::math::cdf(G, b(0) / C_(0, 0));
    f(0) = e(0) - d(0);
    while (N < (nPaths-1))
    {
        y = y0;
        for (int i = 1; i < m; i++)
        {
            v1 = d(i - 1) + w_[N][(i - 1)]*(e(i - 1) - d(i - 1));
            y(i - 1) = boost::math::quantile(G, v1);
            v2 = (a(i) - C_.row(i).dot(y)) / C_(i, i);
            v3 = (b(i) - C_.row(i).dot(y)) / C_(i, i);
            d(i) = boost::math::cdf(G, v2);
            e(i) = boost::math::cdf(G, v3);
            f(i) = (e(i) - d(i))*f(i - 1);
        }

        N++;
        delta = (f(m-1) - Intsum) / N;
        Intsum += delta;
        Varsum = (N - 2)*Varsum / N + delta*delta;
        err = alpha_*std::sqrt(Varsum);
   }

Body:
If I understand your code right, the running time is actually O(nPaths*m*m)=10^11, due to  the dot-product C_.row(i).dot(y) which needs O(m) operation.

You could speed up the program by factor of two by not calculating it twice:

double prod=C_.row(i).dot(y)
v2 = (a(i) - prod) / C_(i, i);
v3 = (b(i) - prod) / C_(i, i);

but maybe compiler already does it for you.

The other thing is that y consists of zeros (at least at the beginning) so you don't have to do the full dot-product but only until current value of i. That should give another factor 2 speed up.

So taken into the account the sheer number of operation your timings are not so bad. There is some room for improvement of the code, but if you are interested in speeding up some orders of magnitude you probably should be thinking about changing your formulation.


问:
Given only vector of dates, expand data in between (unequal) date points
Other questions have centered around having a start and end date. (see the following for examples
Given start date and end date, reshape/expand data for each day between (each day on a row)
Expand rows by date range using start and end date

My question is different in that I only have one date column and I would like to convert the unequal date ranges to daily counts. This specific example created deals with number of workers on a job site at one time. Different crews of people come on different dates

A brief data frame provided is as follows:

```<code>dd <- data.frame(date=as.Date(c("1999-03-22","1999-03-29","1999-04-08")),work=c(43,95,92),cumwork=c(43,138,230))
</code>```

I would like the data to look like this:

```<code>dw <- data.frame(date=c(seq(as.Date("1999-03-22"),as.Date("1999-04-10"),by= "day")),
       work=c(rep(43,7),rep(95,10),rep(92,3)),
       cumwork=c(rep(43,7),rep(138,10),rep(230,3)))
</code>```

I have been stuck on this for some time. Any help would be appreciated!

UPDATE (7/5/2017): As pointed out by @Scarabee the dates in the dataframe 'dd' should be in date format. Have updated the code to reflect this

答:
A solution similar, with base R (and zoo package):

```<code>dd$date <- as.Date(as.character(dd$date))
my.seq <- data.frame(date=seq.Date(from=range(dd$date)[1], to=range(dd$date)[2], by="day"))
output <- merge(my.seq, dd, all.x=TRUE)
output <- zoo::na.locf(output)
</code>```

You first have to transform your date into a Date format. Then separately create a vector of complete dates and merge it with the original data. Eventually, run a "last observation carried forward" algorithm.

Body:
Other questions have centered around having a start and end date. (see the following for examples
Given start date and end date, reshape/expand data for each day between (each day on a row)
Expand rows by date range using start and end date

My question is different in that I only have one date column and I would like to convert the unequal date ranges to daily counts. This specific example created deals with number of workers on a job site at one time. Different crews of people come on different dates

A brief data frame provided is as follows:

dd <- data.frame(date=as.Date(c("1999-03-22","1999-03-29","1999-04-08")),work=c(43,95,92),cumwork=c(43,138,230))

I would like the data to look like this:

dw <- data.frame(date=c(seq(as.Date("1999-03-22"),as.Date("1999-04-10"),by= "day")),
       work=c(rep(43,7),rep(95,10),rep(92,3)),
       cumwork=c(rep(43,7),rep(138,10),rep(230,3)))

I have been stuck on this for some time. Any help would be appreciated!

UPDATE (7/5/2017): As pointed out by @Scarabee the dates in the dataframe 'dd' should be in date format. Have updated the code to reflect this

Body:
A solution similar, with base R (and zoo package):

dd$date <- as.Date(as.character(dd$date))
my.seq <- data.frame(date=seq.Date(from=range(dd$date)[1], to=range(dd$date)[2], by="day"))
output <- merge(my.seq, dd, all.x=TRUE)
output <- zoo::na.locf(output)

You first have to transform your date into a Date format. Then separately create a vector of complete dates and merge it with the original data. Eventually, run a "last observation carried forward" algorithm.


问:
Oracle SQL: Alternative to aggregate large texts (when exceeding Listagg limit)
I have a simple Select query that aggregates one column containing large texts.
The following worked for me with small texts but I am now exceeding the Listagg character limit (4000 bytes ?).

I am very new to Oracle and couldn't find a proper solution for this online that I could apply here.

Can someone tell me the best alternative to this ?

My Query (simplified):

```<code>SELECT
    m.S_ID AS SID
    , LISTAGG
    (
        'ITEM NO.: ' || m.ITEM ||
        ' -nl-ARTICLE: ' || a.ARTICLE ||
        ' -nl-NET: ' || m.NET ||
        ' -nl-TAX: ' || NVL(m.TAX, 0) ||
        ' -nl-GROSS: ' || (m.NET + m.TAX),
        ' -nl--nl-'
    ) WITHIN GROUP (ORDER BY m.S_ID) AS Details
    /* ... */
FROM
    myTable m
/* ... */
</code>```

Many thanks for any help with this,

Mike

答:
One of possible method.

```<code>select xmlagg(xmlelement(xxx,'ITEM NO.: ' || m.ITEM ||
        ' -nl-ARTICLE: ' || a.ARTICLE ||
        ' -nl-NET: ' || m.NET ||
        ' -nl-TAX: ' || NVL(m.TAX, 0) ||
        ' -nl-GROSS: ' || (m.NET + m.TAX),
        ' -nl--nl-'||',<-separator').extract('//text()') order m.S_ID).getClobval() from mytable
group by ...
</code>```

2nd method.
oracle allows to creat own aggregation function user defined aggregation function

Body:
I have a simple Select query that aggregates one column containing large texts.
The following worked for me with small texts but I am now exceeding the Listagg character limit (4000 bytes ?).

I am very new to Oracle and couldn't find a proper solution for this online that I could apply here.

Can someone tell me the best alternative to this ?

My Query (simplified):

SELECT
    m.S_ID AS SID
    , LISTAGG
    (
        'ITEM NO.: ' || m.ITEM ||
        ' -nl-ARTICLE: ' || a.ARTICLE ||
        ' -nl-NET: ' || m.NET ||
        ' -nl-TAX: ' || NVL(m.TAX, 0) ||
        ' -nl-GROSS: ' || (m.NET + m.TAX),
        ' -nl--nl-'
    ) WITHIN GROUP (ORDER BY m.S_ID) AS Details
    /* ... */
FROM
    myTable m
/* ... */

Many thanks for any help with this,

Mike

Body:
One of possible method.

select xmlagg(xmlelement(xxx,'ITEM NO.: ' || m.ITEM ||
        ' -nl-ARTICLE: ' || a.ARTICLE ||
        ' -nl-NET: ' || m.NET ||
        ' -nl-TAX: ' || NVL(m.TAX, 0) ||
        ' -nl-GROSS: ' || (m.NET + m.TAX),
        ' -nl--nl-'||',<-separator').extract('//text()') order m.S_ID).getClobval() from mytable
group by ...

2nd method.
oracle allows to creat own aggregation function user defined aggregation function


问:
Angular 2/4 img src
I'm simply trying to render an image in a component.  I can't seem to find a decent answer that works.

Can someone point me in the right direction?

Enviroment:

angular/cli 1.1.2

node 8.1.0

OS win x64

angular -v 4.2.5

What I have tired (HTML):

```<code><img [src]={{imgUrl}} />
<img [src]="imgUrl" />

<img src={{imgUrl}} />
<img src="imgUrl" />

<img ng-src="imgUrl" />

<img src="assets/images/img.jpg" />
<!-- and a few more -->
</code>```

With .ts file like:

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  imgUrl = "";

  constructor() {}

  ngOnInit() {
     this.imgUrl = 'assets/images/img.jpg';
     // i have also tried
     // ~/assets/...
     // ./assets/...
     // etc
  }

}
</code>```

Project structure:

```<code>src
--app
----home
------ts-files
--assets
----images
------img.jpg
</code>```

I have also tried moving the file from assets to the same ts folder, and some other places.

But I only get the same 404 error.

GET http://localhost:4200/assets/images/img.jpg 404 (Not Found)

UPDATE

.angular-cli.json content (autogenerated):

```<code>{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "Test"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json"
    },
    {
      "project": "src/tsconfig.spec.json"
    },
    {
      "project": "e2e/tsconfig.e2e.json"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {}
  }
}
</code>```

答: Are you sure that  doesn't work? Note the leading '/' in it. When you're using the Angular CLI, if you run ng build it should create a dist directory in your project with the built static Web files. Can you confirm that the assets/images/img.jpg file is in your generated output from ng build?

Title: Angular 2/4 img src

Body:
I'm simply trying to render an image in a component.  I can't seem to find a decent answer that works.

Can someone point me in the right direction?

Enviroment:

angular/cli 1.1.2

node 8.1.0

OS win x64

angular -v 4.2.5

What I have tired (HTML):

With .ts file like:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  imgUrl = "";

  constructor() {}

  ngOnInit() {
     this.imgUrl = 'assets/images/img.jpg';
     // i have also tried
     // ~/assets/...
     // ./assets/...
     // etc
  }

}

Project structure:

src
--app
----home
------ts-files
--assets
----images
------img.jpg

I have also tried moving the file from assets to the same ts folder, and some other places.

But I only get the same 404 error.

GET http://localhost:4200/assets/images/img.jpg 404 (Not Found)

UPDATE

.angular-cli.json content (autogenerated):

{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "Test"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json"
    },
    {
      "project": "src/tsconfig.spec.json"
    },
    {
      "project": "e2e/tsconfig.e2e.json"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {}
  }
}

Body: Are you sure that <img src="/assets/images/img.jpg"> doesn't work? Note the leading '/' in it. When you're using the Angular CLI, if you run ng build it should create a dist directory in your project with the built static Web files. Can you confirm that the assets/images/img.jpg file is in your generated output from ng build?


问:
How to read and use ruby-nmap documentation?
I find myself unable to use the ruby-nmap documentation at

http://www.rubydoc.info/gems/ruby-nmap/Nmap

There are simply no code examples and therefore I quite can't figure out on how to use & read the documentation properly. Can somebody give me an overview on how to get started and what for example "#address" means?

答: You could look at the github page, that seems to have some usage examples.</p>


问:
MQOPEN gives error 2085, which I didn't have before
I have everything was working OK, until today I on MQOPEN got error

    2085 MQRC_UNKNOWN_OBJECT_NAME

```<code>#include <stdio.h>
#include <cmqc.h>
#include <cmqxc.h>
#include "dte_mq.h"
#include <string.h>
#include <stdlib.h>

typedef struct tagDTE_QUEUE_DESCRIPTOR
{
    MQHOBJ handle;
    int    IsSyncpointControled;
} DTE_QUEUE_DESCRIPTOR, *PDTE_QUEUE_DESCRIPTOR;

static MQHCONN sHConn = 0;
static MQLONG  sCompCode = MQCC_OK;
static MQLONG  sReason = MQRC_NONE;
static int     sNumOpenQueues = 0;
static PDTE_QUEUE_DESCRIPTOR sQueues = NULL;
MQLONG   OpenCode;
MQOD     od = {MQOD_DEFAULT};    /* Object Descriptor */
MQMD     md = {MQMD_DEFAULT};
MQPMO    pmo = {MQPMO_DEFAULT};
MQLONG   O_options;/* MQCONNX options */
MQCNO   Connect_options = {MQCNO_DEFAULT};
/* Client connection channel */
MQCD    ClientConn = {MQCD_CLIENT_CONN_DEFAULT};

#define MAX_NUM_OPEN_QUEUES     10

int dteMqOpen(const char *name, int *qd)
{
    MQLONG   options;
    MQHOBJ   hObj;
    int      i;
    printf("SAM\n");
    strncpy(od.ObjectName, name, MQ_Q_NAME_LENGTH);
    printf("SAM2\n");
    O_options = MQOO_INPUT_AS_Q_DEF + MQOO_FAIL_IF_QUIESCING;
    printf("SAM3\n");
    MQOPEN(sHConn, &od, O_options, &hObj, &sCompCode, &sReason);
    printf("MQopen = %d and %d\n",sCompCode,sReason);
    if (sCompCode != MQCC_OK)
    {
        printf("RETURN %d\n",DTE_MQR_FAILED);
        return DTE_MQR_FAILED;
   }
   ++sNumOpenQueues;
  *qd = 1;
  for(i = 0; i < MAX_NUM_OPEN_QUEUES; i++)
  {
      printf("In the loop1\n");
      if(sQueues[i].handle == -1)
      {
          *qd = i;
          printf("QDESC1 = %d\n",qd);
          sQueues[i].handle = hObj;
          sQueues[i].IsSyncpointControled = 0;
          break;
     }
     printf("In the loop\n");
   }
   printf("QDESC = %d\n",qd);
   return DTE_MQR_OK;
}
</code>```

Function call is:

```<code>qd = -1;
dteretopen = dteMqOpen(QName, &qd);
printf ("Return code from dteMqOpen = %d\n",dteretopen);
if (dteretopen ==0)
{
    printf("MQOPEN could not open MQ, check errpr log\n");
    exit(99);
}
</code>```

Error 2085. But several days before there was no such error

  Connection is OK, but MQOPEN failed

答:
```<code>dteretopen = dteMqOpen(QName, &qd);
</code>```

Clearly 'QName' has an invalid value.

You have been posting question after question about the same program.  Obviously, you have zero training in MQ programming.  You need to get some MQ training ASAP. There is lots and lots of information on the web and videos too.

Why aren't you doing some basic debugging and outputting 'QName?

You need to take some initiative in debugging your program before posting questions here.  We are not here to do your work.

Body:
I have everything was working OK, until today I on MQOPEN got error

    2085 MQRC_UNKNOWN_OBJECT_NAME

#include <stdio.h>
#include <cmqc.h>
#include <cmqxc.h>
#include "dte_mq.h"
#include <string.h>
#include <stdlib.h>

typedef struct tagDTE_QUEUE_DESCRIPTOR
{
    MQHOBJ handle;
    int    IsSyncpointControled;
} DTE_QUEUE_DESCRIPTOR, *PDTE_QUEUE_DESCRIPTOR;

static MQHCONN sHConn = 0;
static MQLONG  sCompCode = MQCC_OK;
static MQLONG  sReason = MQRC_NONE;
static int     sNumOpenQueues = 0;
static PDTE_QUEUE_DESCRIPTOR sQueues = NULL;
MQLONG   OpenCode;
MQOD     od = {MQOD_DEFAULT};    /* Object Descriptor */
MQMD     md = {MQMD_DEFAULT};
MQPMO    pmo = {MQPMO_DEFAULT};
MQLONG   O_options;/* MQCONNX options */
MQCNO   Connect_options = {MQCNO_DEFAULT};
/* Client connection channel */
MQCD    ClientConn = {MQCD_CLIENT_CONN_DEFAULT};

#define MAX_NUM_OPEN_QUEUES     10

int dteMqOpen(const char *name, int *qd)
{
    MQLONG   options;
    MQHOBJ   hObj;
    int      i;
    printf("SAM\n");
    strncpy(od.ObjectName, name, MQ_Q_NAME_LENGTH);
    printf("SAM2\n");
    O_options = MQOO_INPUT_AS_Q_DEF + MQOO_FAIL_IF_QUIESCING;
    printf("SAM3\n");
    MQOPEN(sHConn, &od, O_options, &hObj, &sCompCode, &sReason);
    printf("MQopen = %d and %d\n",sCompCode,sReason);
    if (sCompCode != MQCC_OK)
    {
        printf("RETURN %d\n",DTE_MQR_FAILED);
        return DTE_MQR_FAILED;
   }
   ++sNumOpenQueues;
  *qd = 1;
  for(i = 0; i < MAX_NUM_OPEN_QUEUES; i++)
  {
      printf("In the loop1\n");
      if(sQueues[i].handle == -1)
      {
          *qd = i;
          printf("QDESC1 = %d\n",qd);
          sQueues[i].handle = hObj;
          sQueues[i].IsSyncpointControled = 0;
          break;
     }
     printf("In the loop\n");
   }
   printf("QDESC = %d\n",qd);
   return DTE_MQR_OK;
}

Function call is:

qd = -1;
dteretopen = dteMqOpen(QName, &qd);
printf ("Return code from dteMqOpen = %d\n",dteretopen);
if (dteretopen ==0)
{
    printf("MQOPEN could not open MQ, check errpr log\n");
    exit(99);
}

Error 2085. But several days before there was no such error

  Connection is OK, but MQOPEN failed

Body:
dteretopen = dteMqOpen(QName, &qd);

Clearly 'QName' has an invalid value.

You have been posting question after question about the same program.  Obviously, you have zero training in MQ programming.  You need to get some MQ training ASAP. There is lots and lots of information on the web and videos too.

Why aren't you doing some basic debugging and outputting 'QName?

You need to take some initiative in debugging your program before posting questions here.  We are not here to do your work.


问:
Print a stack trace to stdout on errors in Django while using IIS
I have my Django Web application already mounted in IIS version 10 and I am able to see some views but I am unable to see other views working because I am getting the following error in my browser's console when I do my AJAX request:

```<code>GET http://10.51.112.24:89/statistics/chart-data3 500 (Internal Server Error)
</code>```

I am searching for a snippet of a logging configuration to get Django or IIS to just output a stack trace when it encounters an error during a request. This code is specifically for local debugging and mainly when I do AJAX GET/POST requests.

So far, I have enabled the following logging configurations in my settings.py file but they are not enough to trace down this error:

```<code>DEBUG = True
DEBUG_PROPAGATE_EXCEPTIONS = True
</code>```

Any tool or code snippet that can help me to troubleshoot better this problem besides the web browser console from Chrome is welcome.

答:
This code helped me to better troubleshoot my Ajax request problem:

This code goes into the ajax request, results are displayed in the console web browser.

```<code> error: function(jqXHR, textStatus, errorThrown) {
    console.log(JSON.stringify(jqXHR));
    console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
 }
</code>```

Body:
I have my Django Web application already mounted in IIS version 10 and I am able to see some views but I am unable to see other views working because I am getting the following error in my browser's console when I do my AJAX request:

GET http://10.51.112.24:89/statistics/chart-data3 500 (Internal Server Error)

I am searching for a snippet of a logging configuration to get Django or IIS to just output a stack trace when it encounters an error during a request. This code is specifically for local debugging and mainly when I do AJAX GET/POST requests.

So far, I have enabled the following logging configurations in my settings.py file but they are not enough to trace down this error:

DEBUG = True
DEBUG_PROPAGATE_EXCEPTIONS = True

Any tool or code snippet that can help me to troubleshoot better this problem besides the web browser console from Chrome is welcome.

Body:
This code helped me to better troubleshoot my Ajax request problem:

This code goes into the ajax request, results are displayed in the console web browser.

 error: function(jqXHR, textStatus, errorThrown) {
    console.log(JSON.stringify(jqXHR));
    console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
 }


问:
bash script for creating multiple files using forloop
I am brand new at bash script. I want to write a script using forloop which will give me the following line and execute also these lines.

```<code>gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 1000 -e 10000 -skip 10 -o 1.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 2000 -e 20000 -skip 10 -o 2.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 3000 -e 30000 -skip 10 -o 3.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 4000 -e 40000 -skip 10 -o 4.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 5000 -e 50000 -skip 10 -o 5.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 6000 -e 60000 -skip 10 -o 6.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 7000 -e 70000 -skip 10 -o 7.out
</code>```

....

答:
You can also save a couple of lines of typing and get them all done in parallel with GNU Parallel:

```<code>parallel gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b {}000 -e {}0000 -skip 10 -o {}.out ::: {1..7}
</code>```

Use parallel --dry-run if you want to see what it would do but without actually doing anything.

Body:
I am brand new at bash script. I want to write a script using forloop which will give me the following line and execute also these lines.

gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 1000 -e 10000 -skip 10 -o 1.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 2000 -e 20000 -skip 10 -o 2.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 3000 -e 30000 -skip 10 -o 3.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 4000 -e 40000 -skip 10 -o 4.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 5000 -e 50000 -skip 10 -o 5.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 6000 -e 60000 -skip 10 -o 6.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 7000 -e 70000 -skip 10 -o 7.out

....

Body:
You can also save a couple of lines of typing and get them all done in parallel with GNU Parallel:

parallel gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b {}000 -e {}0000 -skip 10 -o {}.out ::: {1..7}

Use parallel --dry-run if you want to see what it would do but without actually doing anything.


问:
predict.lm after regression with missing data in Y
I don't understand how to generate predicted values from a linear regression using the predict.lm command when some value of the dependent variable Y are missing, even though no independent X observation is missing. Algebraically, this isn't a problem, but I don't know an efficient method to do it in R. Take for example this fake dataframe and regression model. I attempt to assign predictions in the source dataframe but am unable to do so because of one missing Y value: I get an error.

```<code># Create a fake dataframe
x <- c(1,2,3,4,5,6,7,8,9,10)
y <- c(100,200,300,400,NA,600,700,800,900,100)
df <- as.data.frame(cbind(x,y))

# Regress X and Y
model<-lm(y~x+1)
summary(model)

# Attempt to generate predictions in source dataframe but am unable to.
df$y_ip<-predict.lm(testy)

Error in `$<-.data.frame`(`*tmp*`, y_ip, value = c(221.............
  replacement has 9 rows, data has 10
</code>```

I got around this problem by generating the predictions using algebra, df$y<-B0+ B1*df$x, or  generating the predictions by calling the coefficients of the model df$y<-((summary(model)$coefficients[1, 1]) + (summary(model)$coefficients[2, 1]*(df$x)) ; however, I am now working with a big data model with hundreds of coefficients, and these methods are no longer practical. I'd like to know how to do it using the predict function.

Thank you in advance for your assistance!

答:
There is built-in functionality for this in R (but not necessarily obvious): it's the na.action argument/?na.exclude function. With this option set, predict() (and similar downstream processing functions) will automatically fill in NA values in the relevant spots.

Set up data:

```<code>df <- data.frame(x=1:10,y=100*(1:10))
df$y[5] <- NA
</code>```

Fit model: default na.action is na.omit, which simply removes non-complete cases.

```<code>mod1 <- lm(y~x+1,data=df)
predict(mod1)
##    1    2    3    4    6    7    8    9   10
##  100  200  300  400  600  700  800  900 1000
</code>```

na.exclude removes non-complete cases before fitting, but then restores them (filled with NA) in predicted vectors:

```<code>mod2 <- update(mod1,na.action=na.exclude)
predict(mod2)
##    1    2    3    4    5    6    7    8    9   10
##  100  200  300  400   NA  600  700  800  900 1000
</code>```

Body:
I don't understand how to generate predicted values from a linear regression using the predict.lm command when some value of the dependent variable Y are missing, even though no independent X observation is missing. Algebraically, this isn't a problem, but I don't know an efficient method to do it in R. Take for example this fake dataframe and regression model. I attempt to assign predictions in the source dataframe but am unable to do so because of one missing Y value: I get an error.

# Create a fake dataframe
x <- c(1,2,3,4,5,6,7,8,9,10)
y <- c(100,200,300,400,NA,600,700,800,900,100)
df <- as.data.frame(cbind(x,y))

# Regress X and Y
model<-lm(y~x+1)
summary(model)

# Attempt to generate predictions in source dataframe but am unable to.
df$y_ip<-predict.lm(testy)

Error in `$<-.data.frame`(`*tmp*`, y_ip, value = c(221.............
  replacement has 9 rows, data has 10

I got around this problem by generating the predictions using algebra, df$y<-B0+ B1*df$x, or  generating the predictions by calling the coefficients of the model df$y<-((summary(model)$coefficients[1, 1]) + (summary(model)$coefficients[2, 1]*(df$x)) ; however, I am now working with a big data model with hundreds of coefficients, and these methods are no longer practical. I'd like to know how to do it using the predict function.

Thank you in advance for your assistance!

Body:
There is built-in functionality for this in R (but not necessarily obvious): it's the na.action argument/?na.exclude function. With this option set, predict() (and similar downstream processing functions) will automatically fill in NA values in the relevant spots.

Set up data:

df <- data.frame(x=1:10,y=100*(1:10))
df$y[5] <- NA

Fit model: default na.action is na.omit, which simply removes non-complete cases.

mod1 <- lm(y~x+1,data=df)
predict(mod1)
##    1    2    3    4    6    7    8    9   10
##  100  200  300  400  600  700  800  900 1000

na.exclude removes non-complete cases before fitting, but then restores them (filled with NA) in predicted vectors:

mod2 <- update(mod1,na.action=na.exclude)
predict(mod2)
##    1    2    3    4    5    6    7    8    9   10
##  100  200  300  400   NA  600  700  800  900 1000


问:
Text expands outside the div it's inside?
I've got this code:

```<code><html>
<head>
<style type="text/css">

body {
    text-align: center;
}

#content {
    width: 60em;
    margin: 0, auto;
    background-color: #CCC;
}

</style>
</head>

<body>
<center>
<div id="content">kdsjlglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgkhlglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgkkjdghkdsfjgksdjfhg</div>
</center>
</body>

</html>
</code>```

Why does the text not stay inside the div, but go in a single line until it ends? I want it to have line breaks relative to the div it's inside. How can I do this?

答:
Because word wrapping occurs between words.

At least by default. The word-break property can change that in some browsers, but you should avoid having nonsensical 'words' in the content.

Body:
I've got this code:

kdsjlglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgkhlglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgklglkdfjgolksdjflgojsdfsdoljfglsdfghsdkjfgkdhfgkkjdghkdsfjgksdjfhg

Why does the text not stay inside the div, but go in a single line until it ends? I want it to have line breaks relative to the div it's inside. How can I do this?


问:
Android google maps navigation without Intent
I tried navigation with Intents when user click on marker and it's work well. Problem is that I need implement that in my own app. (without opening GoogleMaps app)

How to start implement navigation from current location to markers in my own app without intents? Any help will be appreciated :)

答: You may use this library. It uses Directions API but in free plan it has limit to 2500 requests/day.</p>


问:
Python list comprehension => Ruby select / reject on index rather than element
Given:

```<code>arr=[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
      0   1   2   3   4   5   6   7   8    9    # index of arr
</code>```

In Python, one can select or reject elements of a list given the index of that element by combining enumerate and an if clause in a list comprehension:

Every item except the third:

```<code>>>> [e for i,e in enumerate(arr) if i%3]
[20, 30, 50, 60, 80, 90]
</code>```

Every third item in a list:

```<code>>>> [e for i,e in enumerate(arr) if not i%3]
[10, 40, 70, 100]
</code>```

Or, even easier, with a slice:

```<code>>>> arr[::3]
[10, 40, 70, 100]
</code>```

In Ruby, we have .select and .reject

```<code>> arr.each_with_index.reject { |e,i| i%3==0 }
=> [[20, 1], [30, 2], [50, 4], [60, 5], [80, 7], [90, 8]]
> arr.each_with_index.select { |e,i| i%3==0 }
=> [[10, 0], [40, 3], [70, 6], [100, 9]]
</code>```

And then apply .collect to that:

```<code>> arr.each_with_index.select { |e,i| i%3==0 }.collect{|e,i| e}
=> [10, 40, 70, 100]
</code>```

For the slice, the rough Ruby equivalent might be:

```<code>> (0..arr.length).step(3).each { |e| p arr[e] }
10
40
70
100
=> 0..10
</code>```

But I can't figure out how toe collect those into a new array other than:

```<code>> new_arr=[]
=> []
> (0..arr.length).step(3).each { |e| new_arr.push(arr[e]) }
=> 0..10
> new_arr
=> [10, 40, 70, 100]
</code>```

Questions:

Are these the best Ruby idioms for what I am trying to do (.select or .reject with .collect)?

Is there a way to do something along these lines with a slice:

 new_arr=(0..arr.length).step(3).each { |e| arr[e] }.some_method?

答:
"But I can't figure out how to collect those into a new array other than(...)"
There is a method which does that, and you found its name while formulating your question:

```<code>arr=[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
new_arr = (0..arr.length).step(3).collect { |e|  arr[e] }
</code>```

collect has an alias: map .

Body:
Given:

arr=[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
      0   1   2   3   4   5   6   7   8    9    # index of arr

In Python, one can select or reject elements of a list given the index of that element by combining enumerate and an if clause in a list comprehension:

Every item except the third:

>>> [e for i,e in enumerate(arr) if i%3]
[20, 30, 50, 60, 80, 90]

Every third item in a list:

>>> [e for i,e in enumerate(arr) if not i%3]
[10, 40, 70, 100]

Or, even easier, with a slice:

>>> arr[::3]
[10, 40, 70, 100]

In Ruby, we have .select and .reject

> arr.each_with_index.reject { |e,i| i%3==0 }
=> [[20, 1], [30, 2], [50, 4], [60, 5], [80, 7], [90, 8]]
> arr.each_with_index.select { |e,i| i%3==0 }
=> [[10, 0], [40, 3], [70, 6], [100, 9]]

And then apply .collect to that:

> arr.each_with_index.select { |e,i| i%3==0 }.collect{|e,i| e}
=> [10, 40, 70, 100]

For the slice, the rough Ruby equivalent might be:

> (0..arr.length).step(3).each { |e| p arr[e] }
10
40
70
100
=> 0..10

But I can't figure out how toe collect those into a new array other than:

> new_arr=[]
=> []
> (0..arr.length).step(3).each { |e| new_arr.push(arr[e]) }
=> 0..10
> new_arr
=> [10, 40, 70, 100]

Questions:

Are these the best Ruby idioms for what I am trying to do (.select or .reject with .collect)?

Is there a way to do something along these lines with a slice:

 new_arr=(0..arr.length).step(3).each { |e| arr[e] }.some_method?

Body:
"But I can't figure out how to collect those into a new array other than(...)"
There is a method which does that, and you found its name while formulating your question:

arr=[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
new_arr = (0..arr.length).step(3).collect { |e|  arr[e] }

collect has an alias: map .


问:
Splitting all output directories in Gradle
Gradle 4.0 came out yesterday and I updated my project for it.

Now I am getting the following warning:

Gradle now uses separate output directories for each JVM language, but
  this build assumes a single directory for all classes from a source
  set. This behaviour has been deprecated and is scheduled to be removed
  in Gradle 5.0

I would like to use separate output directories for each language. What do I need to change to make that happen?

Things I tried:

gradle clean followed by gradle build

deleting the build directory then running gradle build.

deleting the gradle and build directory then running gradle

Related GitHub issue

Gradle Plugins:

java

eclipse

idea

org.springframework.boot

答:
Gradle 4.0 introduces multiple sourceSets per JVM language in order to enable remote build caching. With the java plugin your build/classes/main should become build/classes/java/main and build/classes/test should become build/classes/java/test, etc.

The warning you're seeing is defined in DefaultSourceSets.java

Therefore, if any plugin within your project or your build.gradle calls DefaultSourceSetOutput.getClassesDir() (or access classesDir) you get this warning.

Solution 1

Use

```<code>sourceSets.main.output.classesDir = new File(buildDir, "classes/main")
</code>```

which corresponds to:

```<code>@Override
public boolean isLegacyLayout() {
    return classesDir!=null;
}

@Override
public void setClassesDir(File classesDir) {
    setClassesDir((Object)classesDir);
}

@Override
public void setClassesDir(Object classesDir) {
    this.classesDir = classesDir;
    this.classesDirs.setFrom(classesDir);
}
</code>```

Note that SourceSetOutput.java marks getClassesDir() as deprecated.

So until all plugins in your project get support for Gradle 4.0 you should stick to the workaround and ignore the deprecation warnings.

Another issue is test files. If you don't want to have the new layout (build/classes/main and build/classes/java/test) you should adjust test path too:

```<code>sourceSets.main.output.classesDir = new File(buildDir, "classes/main")
sourceSets.test.output.classesDir = new File(buildDir, "classes/test")
</code>```

UPDATE
Users of IDEA may notice that IDE starts using separate out directories for build if Gradle 4.x is detected. That makes impossible hot app reloading if you run app outside of IDEA. To fix that add and reimport:

```<code>subprojects {
    apply plugin: 'idea'
    // Due to Gradle 4.x changes (separate output directories per JVM language)
    // Idea developers refuse to reuse Gradle classpath and use own 'out/' directory.
    // Revert to old behavior to allow Spring Devtool to work with using fast Idea compiler.
    // https://youtrack.jetbrains.com/issue/IDEA-175172
    // Alternatively use native Gradle builds or bootRun.addResources = true
    // To use this feature push Ctrl+Shift+F9 to recompile!
    // Be aware that Idea put resources into classes/ directory!!
    idea.module.inheritOutputDirs = false
    idea.module.outputDir = sourceSets.main.output.classesDir
    idea.module.testOutputDir = sourceSets.test.output.classesDir
}
</code>```

Please note that IDEA puts resources into the same directory as .class files so your Gradle classpath could be corrupted. Just do gradle clean for modules on which you use IDEA built-in build commands (Ctrl+Shift+F10, etc).

Body:
Gradle 4.0 introduces multiple sourceSets per JVM language in order to enable remote build caching. With the java plugin your build/classes/main should become build/classes/java/main and build/classes/test should become build/classes/java/test, etc.

The warning you're seeing is defined in DefaultSourceSets.java

Therefore, if any plugin within your project or your build.gradle calls DefaultSourceSetOutput.getClassesDir() (or access classesDir) you get this warning.

Solution 1

Use

sourceSets.main.output.classesDir = new File(buildDir, "classes/main")

which corresponds to:

@Override
public boolean isLegacyLayout() {
    return classesDir!=null;
}

@Override
public void setClassesDir(File classesDir) {
    setClassesDir((Object)classesDir);
}

@Override
public void setClassesDir(Object classesDir) {
    this.classesDir = classesDir;
    this.classesDirs.setFrom(classesDir);
}

Note that SourceSetOutput.java marks getClassesDir() as deprecated.

So until all plugins in your project get support for Gradle 4.0 you should stick to the workaround and ignore the deprecation warnings.

Another issue is test files. If you don't want to have the new layout (build/classes/main and build/classes/java/test) you should adjust test path too:

sourceSets.main.output.classesDir = new File(buildDir, "classes/main")
sourceSets.test.output.classesDir = new File(buildDir, "classes/test")

UPDATE
Users of IDEA may notice that IDE starts using separate out directories for build if Gradle 4.x is detected. That makes impossible hot app reloading if you run app outside of IDEA. To fix that add and reimport:

subprojects {
    apply plugin: 'idea'
    // Due to Gradle 4.x changes (separate output directories per JVM language)
    // Idea developers refuse to reuse Gradle classpath and use own 'out/' directory.
    // Revert to old behavior to allow Spring Devtool to work with using fast Idea compiler.
    // https://youtrack.jetbrains.com/issue/IDEA-175172
    // Alternatively use native Gradle builds or bootRun.addResources = true
    // To use this feature push Ctrl+Shift+F9 to recompile!
    // Be aware that Idea put resources into classes/ directory!!
    idea.module.inheritOutputDirs = false
    idea.module.outputDir = sourceSets.main.output.classesDir
    idea.module.testOutputDir = sourceSets.test.output.classesDir
}

Please note that IDEA puts resources into the same directory as .class files so your Gradle classpath could be corrupted. Just do gradle clean for modules on which you use IDEA built-in build commands (Ctrl+Shift+F10, etc).

ContentLicense: CC BY-SA 4.0


问:
Referring to a macro variable already defined
I was going through a SAS code and found the following ways of referencing a macro variable.

&variable_name .

&variable_name

I know that the first way of referencing is the normal way of how we refer to a defined macro variable in sas.

But, could you please explain how does the second way(without period after the macro variable name) is different from the first way

答:
When you reference a macro variable, the & sign signals a macro variable reference is beginning. The macro processor also needs to determine the end of the macro variable reference.

In most cases, the macro reference is ended by either white space or a semicolon.

```<code>38   %let x=Hello;
39
40   %put &x;   *semicolon ends the reference;
Hello
41
42   %put &x World; *white space ends the reference;
Hello World
</code>```

Macro variable names can consist of letters, numbers, and underscores.  Any symbol which cannot be part of a macro variable will end a reference.  For example a question mark:

```<code>44   %put &x?; *Question mark ends the reference;
Hello?
</code>```

Now, suppose you want to generate the string HelloWorld, with no space between Hello and World:

```<code>46   %put &xWorld;
WARNING: Apparent symbolic reference XWORLD not resolved.
&xWorld
</code>```

That didn't work.  The macro processor saw a reference to a macro variable named xWorld, and there is no such macro variable.  So we need a way to tell the macro processor that the macro variable reference ends after the x.  We can add a period after the x, to say that "macro variable reference ends here."

```<code>47   %put &x.World;
HelloWorld
</code>```

Note that importantly, the period we typed is not shown in the text written to the log. The macro processor "eats" the period when it uses it as the end of the macro variable reference.

This means that in cases where you want to have a period after a macro variable reference, you must type two periods.  The first is eaten by the macro processor.  The usual example of this is with a libref:

```<code>48   %let mylib=sashelp;
49
50   proc print data=&mylib.class;run;
ERROR: File WORK.SASHELPCLASS.DATA does not exist.

NOTE: The SAS System stopped processing this step because of errors.
51
52   proc print data=&mylib..class;run;

NOTE: There were 19 observations read from the data set SASHELP.CLASS.
</code>```

Some people like to always use periods after macro variable references, as a coding style.  Personally, I only uses the period when it is necessary to specify the end of a macro variables reference.

Body:
When you reference a macro variable, the & sign signals a macro variable reference is beginning. The macro processor also needs to determine the end of the macro variable reference.

In most cases, the macro reference is ended by either white space or a semicolon.

38   %let x=Hello;
39
40   %put &x;   *semicolon ends the reference;
Hello
41
42   %put &x World; *white space ends the reference;
Hello World

Macro variable names can consist of letters, numbers, and underscores.  Any symbol which cannot be part of a macro variable will end a reference.  For example a question mark:

44   %put &x?; *Question mark ends the reference;
Hello?

Now, suppose you want to generate the string HelloWorld, with no space between Hello and World:

46   %put &xWorld;
WARNING: Apparent symbolic reference XWORLD not resolved.
&xWorld

That didn't work.  The macro processor saw a reference to a macro variable named xWorld, and there is no such macro variable.  So we need a way to tell the macro processor that the macro variable reference ends after the x.  We can add a period after the x, to say that "macro variable reference ends here."

47   %put &x.World;
HelloWorld

Note that importantly, the period we typed is not shown in the text written to the log. The macro processor "eats" the period when it uses it as the end of the macro variable reference.

This means that in cases where you want to have a period after a macro variable reference, you must type two periods.  The first is eaten by the macro processor.  The usual example of this is with a libref:

48   %let mylib=sashelp;
49
50   proc print data=&mylib.class;run;
ERROR: File WORK.SASHELPCLASS.DATA does not exist.

NOTE: The SAS System stopped processing this step because of errors.
51
52   proc print data=&mylib..class;run;

NOTE: There were 19 observations read from the data set SASHELP.CLASS.

Some people like to always use periods after macro variable references, as a coding style.  Personally, I only uses the period when it is necessary to specify the end of a macro variables reference.


问:
Hold php variable for an hour then execute condition
I got a simple form to send emails, now im facing an issue, im getting variables from 2 differents pages send to the same php page to submit the email. both variables are sent via ajax. 1 section is an array and the other its a confirmation variable, page  A that has array emails to waiting.php page and page B sends 1 value as well to waiting.php .

```<code> <?php
$groupD = "yesy";//$_GET["info"];

  //sleep (60);
   foreach ($groupD  as $gtm) {
   $message .= $gtm;
  $test .=  $mail[9];
  echo $test;

    }
 $groupx = $test;
 $groupz = "someting ";  //$_GET["confirm"];
 $datetime1 = new DateTime($test );
$datetime2 = new DateTime();
$interval = $datetime1->diff($datetime2);
//echo $interval->format('%h');

if ($interval->format('%h') > 1 ) {
if (!is_null($groupx) & !is_null($groupz)){
/// mail function

  }
else{
    echo "false empty fields";
}
}
else{
    echo "time false";
}

 ?>
</code>```

will it even work if i use sleep class from php. page A has the submit time its fetch out from the array so i can use it with interval, my question will be, should i keep both variables on hold and after an hour , release or which is the best approach, will highly appriciate you guys help.

here is my js

```<code> <script>
  $(document).ready( function() {
  var msg = google_tag_manager["GTM-xxx"].dataLayer.get('hPackageId');
  var msg1 = google_tag_manager["GTM-xxx"].dataLayer.get('hPackageTotal');
  var msg2 = google_tag_manager["GTM-xxx"].dataLayer.get('hUserName');
  var msg3 = google_tag_manager["GTM-xxxx"].dataLayer.get('hUserLastName');
  new Date(Date.parse).toUTCString()
  var d = new Date();
   d.setTime(d);
   var msg4 =(d.toString().slice(0, 24));
   var getall = [msg, msg1, msg2, msg3, msg4];
  // console.log(getall);

   $.ajax({
   type: "GET",
    url: "mypagepage.php",
    data:{info: getall},
     datatype: 'html',
    success: function(data) {}
   });

  });

 </script>
</code>```

both scripts are sent via ajax due my scenario, page A page B has the same sintac

答:
Scripting languages such as PHP are generally designed to respond to an individual web (e.g., https) request and do something right away. I have used sleep() in PHP scripts when they are running in the background, but that is a different type of setup. Putting a delay in a regular script might work, but will result in extra processes running - e.g., if 100 people use the page in an hour then there will be 100 processes running at the same time. While most of the processes would be sleeping (not wasting CPU cycles) that is still a significant load on the server in terms of memory, process descriptors, etc.

If I understand the question correctly, you want to process multiple parts of a transaction that results in an email being sent after an hour of wait time for completion or changes. I suggest using a database (e.g., MySQL) to store the information from each request. Have a separate process - e.g., a cronjob run automatically once an hour - read information for all unsent emails from the database, send the emails and update the database so that the emails won't get sent again an hour later.

Body:
I got a simple form to send emails, now im facing an issue, im getting variables from 2 differents pages send to the same php page to submit the email. both variables are sent via ajax. 1 section is an array and the other its a confirmation variable, page  A that has array emails to waiting.php page and page B sends 1 value as well to waiting.php .

 <?php
$groupD = "yesy";//$_GET["info"];

  //sleep (60);
   foreach ($groupD  as $gtm) {
   $message .= $gtm;
  $test .=  $mail[9];
  echo $test;

    }
 $groupx = $test;
 $groupz = "someting ";  //$_GET["confirm"];
 $datetime1 = new DateTime($test );
$datetime2 = new DateTime();
$interval = $datetime1->diff($datetime2);
//echo $interval->format('%h');

if ($interval->format('%h') > 1 ) {
if (!is_null($groupx) & !is_null($groupz)){
/// mail function

  }
else{
    echo "false empty fields";
}
}
else{
    echo "time false";
}

 ?>

will it even work if i use sleep class from php. page A has the submit time its fetch out from the array so i can use it with interval, my question will be, should i keep both variables on hold and after an hour , release or which is the best approach, will highly appriciate you guys help.

here is my js

both scripts are sent via ajax due my scenario, page A page B has the same sintac


问:
How to send and receive a large image using tcp (VB.NET)
I need to send and receive a large image between programs running on different machines within the same network.

I've looked at using upd. However, I ran into problems with the size of the packets and (after breaking the image into smaller pieces to get past this problem) the number of packets needing to be processed all at once - and ultimately packet loss.

I've also thought of sending the image by storing it in a common file folder and receiving it by using file watcher as a trigger. However, this just adds further complexities in setup where common folders don't already exist.

Assuming I'm barking up the right tree looking at TCP, can someone point me to/provide an example of how to send an image file using it (VB.NET would be ideal). Also, are there practical limits to TCP package sizes?

If I am not barking up the right tree, and there is an easier way to do this I'd surely appreciate some guidance/examples.

答: Take a look at Socket.SendFile Method (MSDN).


问:
MockMVC for a controller method with Path variable and Object
I have the controller as below:

```<code>@RestController
@RequestMapping("/v1/controller")
public class FindValue {

@RequestMapping(path="{id}/Method", method = POST)
    public ResponseEntity<HttpStatus> setMethodValue (@PathVariable Integer id, @RequestBody FindRequest findRequest) {
</code>```

How to call this method from Junit using mockMvc

```<code>import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.springframework.test.web.servlet.MockMvc;

@RunWith(MockitoJUnitRunner.class)
public class FindValue {
    @InjectMocks
    private FindValue mockFindValue;

    private MockMvc mockMvc;

    @Test
    public void testMethodValue() throws Exception {
        FindRequest findRequest = new FindRequest();
        findRequest.setValue("thevalue");

        mockMvc
            .perform(post("/v1/controller/{id}/Method", 1)
            .header("Content-Type", "application/json")
            .header("Accept", "application/json;charset=utf-8")
            .content(asJsonString(findRequest))
            ).andExpect(status().isCreated());

    }
</code>```

But this returns 404 error

Could someone pls help

答:
you have root reuqest mapping for controller /v1/controller ,and mapping for resource "{id}/Method"

it test you create url that not mapped :
"/v1/controller/{id}/Method"

I thinks it should be

```<code>@RequestMapping(path="/{id}/Method", method = POST)
</code>```

and @JB Nizet +1

Body:
I have the controller as below:

@RestController
@RequestMapping("/v1/controller")
public class FindValue {

@RequestMapping(path="{id}/Method", method = POST)
    public ResponseEntity<HttpStatus> setMethodValue (@PathVariable Integer id, @RequestBody FindRequest findRequest) {

How to call this method from Junit using mockMvc

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.springframework.test.web.servlet.MockMvc;

@RunWith(MockitoJUnitRunner.class)
public class FindValue {
    @InjectMocks
    private FindValue mockFindValue;

    private MockMvc mockMvc;

    @Test
    public void testMethodValue() throws Exception {
        FindRequest findRequest = new FindRequest();
        findRequest.setValue("thevalue");

        mockMvc
            .perform(post("/v1/controller/{id}/Method", 1)
            .header("Content-Type", "application/json")
            .header("Accept", "application/json;charset=utf-8")
            .content(asJsonString(findRequest))
            ).andExpect(status().isCreated());

    }

But this returns 404 error

Could someone pls help

Body:
you have root reuqest mapping for controller /v1/controller ,and mapping for resource "{id}/Method"

it test you create url that not mapped :
"/v1/controller/{id}/Method"

I thinks it should be

@RequestMapping(path="/{id}/Method", method = POST)

and @JB Nizet +1


问:
Font styling issue in IE
I am creating a list that contains fonts using angular directive

```<code><li  ng-repeat='o in options'><button class='btn btn-blue checked-dropdown' style='font-family: {{o.css}}; width: 100%' type='button' ng-click='action($event, o.css)'><i ng-if='o.active' class='fa fa-check'></i>{{o.name}}</button></li>

  options: [
            { name: 'Sans-Serif', css: 'Arial, Helvetica, sans-serif' },
            { name: 'Serif', css: "'times new roman', serif" },
            { name: 'Wide', css: "'arial black', sans-serif" },
            { name: 'Narrow', css: "'arial narrow', sans-serif" },
            { name: 'Comic Sans MS', css: "'comic sans ms', sans-serif" },
            { name: 'Courier New', css: "'courier new', monospace" },
            { name: 'Garamond', css: 'garamond, serif' },
            { name: 'Georgia', css: 'georgia, serif' },
            { name: 'Tahoma', css: 'tahoma, sans-serif' },
            { name: 'Trebuchet MS', css: "'trebuchet ms', sans-serif" },
            { name: "Helvetica", css: "'Helvetica Neue', Helvetica, Arial, sans-serif" },
            { name: 'Verdana', css: 'verdana, sans-serif' },
            { name: 'Proxima Nova', css: 'proxima_nova_rgregular' }
        ]
</code>```

when I click on button then the full font list is shown with their css applied on it.
It is working fine in Chrome but in IE only the font name is shown in plain text
  IE Image      Chrome Image

答:
Instead of attaching model value to specific property in style attr, you can make use of ng-style directive & call the function on ng-style as:  ng-style = "mystyle($index)"

```<code>$scope.mystyle = function(index){
      return {
        'font-family': $scope.options[index].css,
         'width': "100%"
      }
    }
</code>```

http://plnkr.co/edit/Ew8VyCWojAiyCqaU55qM?p=preview

Title: Font styling issue in IE

Body:
I am creating a list that contains fonts using angular directive

<button class='btn btn-blue checked-dropdown' style='font-family: {{o.css}}; width: 100%' type='button' ng-click='action($event, o.css)'>{{o.name}}</button>

  options: [
            { name: 'Sans-Serif', css: 'Arial, Helvetica, sans-serif' },
            { name: 'Serif', css: "'times new roman', serif" },
            { name: 'Wide', css: "'arial black', sans-serif" },
            { name: 'Narrow', css: "'arial narrow', sans-serif" },
            { name: 'Comic Sans MS', css: "'comic sans ms', sans-serif" },
            { name: 'Courier New', css: "'courier new', monospace" },
            { name: 'Garamond', css: 'garamond, serif' },
            { name: 'Georgia', css: 'georgia, serif' },
            { name: 'Tahoma', css: 'tahoma, sans-serif' },
            { name: 'Trebuchet MS', css: "'trebuchet ms', sans-serif" },
            { name: "Helvetica", css: "'Helvetica Neue', Helvetica, Arial, sans-serif" },
            { name: 'Verdana', css: 'verdana, sans-serif' },
            { name: 'Proxima Nova', css: 'proxima_nova_rgregular' }
        ]

when I click on button then the full font list is shown with their css applied on it.
It is working fine in Chrome but in IE only the font name is shown in plain text
  IE Image      Chrome Image

Body:
Instead of attaching model value to specific property in style attr, you can make use of ng-style directive & call the function on ng-style as:  ng-style = "mystyle($index)"

$scope.mystyle = function(index){
      return {
        'font-family': $scope.options[index].css,
         'width': "100%"
      }
    }

http://plnkr.co/edit/Ew8VyCWojAiyCqaU55qM?p=preview


问:
Issue with custom serialization using Newtonsoft JSON
To increase performance I tried to make a custom serializer to use with Newtonsoft JSON, however for some reason, the function stops randomly and the function calling the serializer ends as well. There are no exceptions, therefore I am unable to determine the cause. This is the function:

```<code>    public string customSerialize(List<EntityJSON> data)
    {
        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);
        JsonTextWriter writer = new JsonTextWriter(sw);
        writer.WriteStartObject();
        writer.WriteStartArray(); // <-- Line 89
        foreach (EntityJSON json in data)
        {
            writer.WritePropertyName("type");
            writer.WriteValue(json.type);

            writer.WritePropertyName("name");
            writer.WriteValue(json.name);

            writer.WritePropertyName("position");
            writer.WriteStartArray();
            writer.WritePropertyName("x");
            writer.WriteValue(json.position.x);
            writer.WritePropertyName("z");
            writer.WriteValue(json.position.z);
            writer.WritePropertyName("rot");
            writer.WriteValue(json.position.rot);
            writer.WriteEndArray();

            writer.WritePropertyName("flags");
            writer.WriteValue(json.flags);
        }
        writer.WriteEndArray();
        writer.WriteEndObject();

        return sb.ToString();
    }
</code>```

Update: Got the exception thanks to @Ayoub_B, this is the exception:Exception: Newtonsoft.Json.JsonWriterException: Token StartArray in state ObjectStart would result in an invalid JSON object. Path ''. ...

Sadly, I do not know what this means, I have marked the exception like in the code above (line 89).

答:
Are you by any chance calling this code under another thread? Maybe a Background Worker?
If so then that might be the reason why the exception isn't thrown.
Just wrap all the code inside a Try-Catch block and you'll be able to catch all the exceptions.

Update:

I think the exception is raised because you're putting an array inside a JSON object without a property name, If you did so, By inserting this line

```<code>writer.WritePropertyName("arrayKey");
</code>```

before line 89, the previous exception will disappear, But you'll get a new one inside the loop, This new exception is caused because key-value pairs must be within an object {}, So you can't put them directly inside an Array.

At any rate, I fixed the code you posted and got the following result from it:

```<code>[
    {
        "type": "type_0",
        "name": "type_0",
        "position": {
            "x": "position.x_0",
            "z": "position.a_0",
            "rot": "position.rot_0"
        },
        "flags": "flags_0"
    },
    {
        "type": "type_1",
        "name": "type_1",
        "position": {
            "x": "position.x_1",
            "z": "position.a_1",
            "rot": "position.rot_1"
        },
        "flags": "flags_1"
    }
]
</code>```

Code:

```<code>        writer.WriteStartArray(); // <-- Line 89
        for (int i = 0; i < 2; i++)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("type");
            writer.WriteValue("type_" + i);

            writer.WritePropertyName("name");
            writer.WriteValue("type_" + i);

            writer.WritePropertyName("position");
            writer.WriteStartObject();

            writer.WritePropertyName("x");
            writer.WriteValue("position.x_" + i);
            writer.WritePropertyName("z");
            writer.WriteValue("position.a_" + i);
            writer.WritePropertyName("rot");
            writer.WriteValue("position.rot_" + i);
            writer.WriteEndObject();

            writer.WritePropertyName("flags");
            writer.WriteValue("flags_" + i);
            writer.WriteEndObject();
        }
        writer.WriteEndArray();
</code>```

Body:
To increase performance I tried to make a custom serializer to use with Newtonsoft JSON, however for some reason, the function stops randomly and the function calling the serializer ends as well. There are no exceptions, therefore I am unable to determine the cause. This is the function:

    public string customSerialize(List<EntityJSON> data)
    {
        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);
        JsonTextWriter writer = new JsonTextWriter(sw);
        writer.WriteStartObject();
        writer.WriteStartArray(); // <-- Line 89
        foreach (EntityJSON json in data)
        {
            writer.WritePropertyName("type");
            writer.WriteValue(json.type);

            writer.WritePropertyName("name");
            writer.WriteValue(json.name);

            writer.WritePropertyName("position");
            writer.WriteStartArray();
            writer.WritePropertyName("x");
            writer.WriteValue(json.position.x);
            writer.WritePropertyName("z");
            writer.WriteValue(json.position.z);
            writer.WritePropertyName("rot");
            writer.WriteValue(json.position.rot);
            writer.WriteEndArray();

            writer.WritePropertyName("flags");
            writer.WriteValue(json.flags);
        }
        writer.WriteEndArray();
        writer.WriteEndObject();

        return sb.ToString();
    }

Update: Got the exception thanks to @Ayoub_B, this is the exception:Exception: Newtonsoft.Json.JsonWriterException: Token StartArray in state ObjectStart would result in an invalid JSON object. Path ''. ...

Sadly, I do not know what this means, I have marked the exception like in the code above (line 89).

Body:
Are you by any chance calling this code under another thread? Maybe a Background Worker?
If so then that might be the reason why the exception isn't thrown.
Just wrap all the code inside a Try-Catch block and you'll be able to catch all the exceptions.

Update:

I think the exception is raised because you're putting an array inside a JSON object without a property name, If you did so, By inserting this line

writer.WritePropertyName("arrayKey");

before line 89, the previous exception will disappear, But you'll get a new one inside the loop, This new exception is caused because key-value pairs must be within an object {}, So you can't put them directly inside an Array.

At any rate, I fixed the code you posted and got the following result from it:

[
    {
        "type": "type_0",
        "name": "type_0",
        "position": {
            "x": "position.x_0",
            "z": "position.a_0",
            "rot": "position.rot_0"
        },
        "flags": "flags_0"
    },
    {
        "type": "type_1",
        "name": "type_1",
        "position": {
            "x": "position.x_1",
            "z": "position.a_1",
            "rot": "position.rot_1"
        },
        "flags": "flags_1"
    }
]

Code:

        writer.WriteStartArray(); // <-- Line 89
        for (int i = 0; i < 2; i++)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("type");
            writer.WriteValue("type_" + i);

            writer.WritePropertyName("name");
            writer.WriteValue("type_" + i);

            writer.WritePropertyName("position");
            writer.WriteStartObject();

            writer.WritePropertyName("x");
            writer.WriteValue("position.x_" + i);
            writer.WritePropertyName("z");
            writer.WriteValue("position.a_" + i);
            writer.WritePropertyName("rot");
            writer.WriteValue("position.rot_" + i);
            writer.WriteEndObject();

            writer.WritePropertyName("flags");
            writer.WriteValue("flags_" + i);
            writer.WriteEndObject();
        }
        writer.WriteEndArray();


问:
remove repeated items from an xml array in jquery
I am trying to eliminate repeated elements in an xml output. The loop works, but I need to skip over the repeated ID and PO values from all but the first loop.

Right now, the output looks like:

2 123456

1234567890: AA100

2 123456

0987654321: BB100

3 123456

11223345: CC00

3 123456

554433221: DD100

I am trying to make it look like:

2 123456

1234567890: AA100

0987654321: BB100

3 123456

11223345: CC00

554433221: DD100

This is my code - and you can see an example here:
https://codepen.io/BIGREDBOOTS/pen/VWQNBw

```<code>jQuery(function ($) {
   $("#dvContent").append("<p class='mainblock'></p>");
  var customerInfo = [];

  $.get("https://cdn.shopify.com/s/files/1/0453/8489/t/26/assets/sample.xml", function(xml) {
    $('manifest', xml).each(function() {
      var id = $(this).find('id').text();
      var po = $(this).find('po').text();
      var loc = {
        "UPC": $(this).find("upc").first().text(),
        "Contents": {
          "Item": $.map($(this).find("item").toArray(), function(manifest) {
            return {
              "ID": id,
              "PO": po,
              "UPC": $(manifest).find("upc").text(),
              "SKU": $(manifest).find("sku").text()
            };
          })
        }
      };
      customerInfo.push(loc);

      $("<div></div>").html($.map($(loc.Contents.Item).toArray(), function(manifest) {
        return '<div class="title">' + manifest.ID + ' ' + manifest.PO + '</div>' +
          '<span class="title">' + manifest.UPC + ": " + manifest.SKU + '</span> <br/>' ;
      }).join("")).append("<br>").appendTo("#dvContent p");
    });
  });
});
</code>```

答:
Well, I tried to improve your code and achieved what's needed...

(just read the code comments)

// Constants
var MANIFEST_XML_URL = 'https://cdn.shopify.com/s/files/1/0453/8489/t/26/assets/sample.xml';

// Event handlers
$(document).ready(function() {
  loadManifestXml();
});

/**
 * Used to load 'manifest' XML from server
 */
function loadManifestXml() {
  $.get(MANIFEST_XML_URL, onGetManifest);
}

/**
 * Used as a callback when loading 'manifest' XML from server
 *
 * @param {Object} response - The server response
 */
function onGetManifest(response) {
  // Parse and display data
  var data = getManifestData(response),
      html = getManifestHtml(data);

  if (html) {
     $('#content').html(html);
  }
}

/**
 * Used to marshal 'manifest' XML server response
 *
 * @param {Object} response - The server response
 * @returns {Object[]} data - An array of objects
 */
function getManifestData(response) {
  var data;

  if (response) {
    data = $('manifest', response).map(function(i, manifest) {
      manifest = $(manifest);

      var cfg = {
          id: manifest.find('id').text(),
          po: manifest.find('po').text(),
          items: []
        },
        items = manifest.find('contents item');

      items.each(function(j, item) {
        item = $(item);

        cfg.items.push({
          sku: item.find('sku').text(),
          upc: item.find('upc').text()
        });
      });

      return cfg;
    });
  }

  return data || []; // Map can return 'null' so force it to be an 'Array'
}

/**
 * Used to build a HTML with 'manifest' data
 *
 * @param {Object[]} data - An array of objects
 * @returns {String} html
 */
function getManifestHtml(data) {
  var html = '';

  for (var i = 0; i < (data || []).length; ++i) {
    var obj = data[i];

    if (obj) {
      html = html + '' + obj.id + ' ' + obj.po + '
';

      var items = obj.items;

      for (var j = 0; j < (items || []).length; ++j) {
        var item = items[j];

        if (item) {
            html = html + item.upc + ': ' + item.sku + '
';
        }
      }

      html = html + '
';
    }
  }

  return html;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
</div></code>```

Body:
I am trying to eliminate repeated elements in an xml output. The loop works, but I need to skip over the repeated ID and PO values from all but the first loop.

Right now, the output looks like:

2 123456

1234567890: AA100

2 123456

0987654321: BB100

3 123456

11223345: CC00

3 123456

554433221: DD100

I am trying to make it look like:

2 123456

1234567890: AA100

0987654321: BB100

3 123456

11223345: CC00

554433221: DD100

This is my code - and you can see an example here:
https://codepen.io/BIGREDBOOTS/pen/VWQNBw

jQuery(function ($) {
   $("#dvContent").append("

");
  var customerInfo = [];

  $.get("https://cdn.shopify.com/s/files/1/0453/8489/t/26/assets/sample.xml", function(xml) {
    $('manifest', xml).each(function() {
      var id = $(this).find('id').text();
      var po = $(this).find('po').text();
      var loc = {
        "UPC": $(this).find("upc").first().text(),
        "Contents": {
          "Item": $.map($(this).find("item").toArray(), function(manifest) {
            return {
              "ID": id,
              "PO": po,
              "UPC": $(manifest).find("upc").text(),
              "SKU": $(manifest).find("sku").text()
            };
          })
        }
      };
      customerInfo.push(loc);

      $("

").html($.map($(loc.Contents.Item).toArray(), function(manifest) {
        return '
' + manifest.ID + ' ' + manifest.PO + '
' +
          '' + manifest.UPC + ": " + manifest.SKU + '
' ;
      }).join("")).append("
").appendTo("#dvContent p");
    });
  });
});

Body:
Well, I tried to improve your code and achieved what's needed...

(just read the code comments)

// Constants
var MANIFEST_XML_URL = 'https://cdn.shopify.com/s/files/1/0453/8489/t/26/assets/sample.xml';

// Event handlers
$(document).ready(function() {
  loadManifestXml();
});

/**
 * Used to load 'manifest' XML from server
 */
function loadManifestXml() {
  $.get(MANIFEST_XML_URL, onGetManifest);
}

/**
 * Used as a callback when loading 'manifest' XML from server
 *
 * @param {Object} response - The server response
 */
function onGetManifest(response) {
  // Parse and display data
  var data = getManifestData(response),
      html = getManifestHtml(data);

  if (html) {
     $('#content').html(html);
  }
}

/**
 * Used to marshal 'manifest' XML server response
 *
 * @param {Object} response - The server response
 * @returns {Object[]} data - An array of objects
 */
function getManifestData(response) {
  var data;

  if (response) {
    data = $('manifest', response).map(function(i, manifest) {
      manifest = $(manifest);

      var cfg = {
          id: manifest.find('id').text(),
          po: manifest.find('po').text(),
          items: []
        },
        items = manifest.find('contents item');

      items.each(function(j, item) {
        item = $(item);

        cfg.items.push({
          sku: item.find('sku').text(),
          upc: item.find('upc').text()
        });
      });

      return cfg;
    });
  }

  return data || []; // Map can return 'null' so force it to be an 'Array'
}

/**
 * Used to build a HTML with 'manifest' data
 *
 * @param {Object[]} data - An array of objects
 * @returns {String} html
 */
function getManifestHtml(data) {
  var html = '';

  for (var i = 0; i < (data || []).length; ++i) {
    var obj = data[i];

    if (obj) {
      html = html + '<b>' + obj.id + ' ' + obj.po + '</b><br>';

      var items = obj.items;

      for (var j = 0; j < (items || []).length; ++j) {
        var item = items[j];

        if (item) {
            html = html + item.upc + ': ' + item.sku + '<br>';
        }
      }

      html = html + '<br>';
    }
  }

  return html;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
</div>


问:
Array of structs - struct?
If we pass an array of structs as method parameter, in the method body do we have a reference to an array of structs, or a new array of structs?</p>

答: Array is  a class in the .net framework so if you create a struct arrays so you will have a reference type ,i am not commenting how and where these will be stored whether it is stack or heap because it is pure implementational details but Microsoft implementation of reference type will go on the HEAP.</p>

Title: Array of structs - struct?


问:
Why is disruptor slower with smaller ring buffer?
Following the Disruptor Getting Started Guide, I've built a minimal disruptor with a single producer and single consumer.

Producer

```<code>import com.lmax.disruptor.RingBuffer;

public class LongEventProducer
{
    private final RingBuffer<LongEvent> ringBuffer;

    public LongEventProducer(RingBuffer<LongEvent> ringBuffer)
    {
        this.ringBuffer = ringBuffer;
    }

    public void onData()
    {
        long sequence = ringBuffer.next();
        try
        {
            LongEvent event = ringBuffer.get(sequence);
        }
        finally
        {
            ringBuffer.publish(sequence);
        }
    }
}
</code>```

Consumer (Notice the consumer does nothing onEvent)

```<code>import com.lmax.disruptor.EventHandler;

public class LongEventHandler implements EventHandler<LongEvent>
{
    public void onEvent(LongEvent event, long sequence, boolean endOfBatch)
    {}
}
</code>```

My goal was to performance test going around a large ring buffer once versus traversing a smaller ring multiple times.  In each case the total ops (bufferSize X rotations) is the same.  I found was that the ops/sec rate fell drastically as the ring buffer got smaller.

```<code>RingBuffer Size |  Revolutions  | Total Ops   |   Mops/sec

    1048576     |      1        |  1048576    |     50-60

       1024     |      1024     |  1048576    |     8-16

        64      |      16384    |  1048576    |    0.5-0.7

        8       |      131072   |  1048576    |    0.12-0.14
</code>```

Question: what is the reason for the massive degradation of performance when the ring buffer size is reduced but the total iterations is fixed?  This trend is independent of the WaitStrategy and Single vs MultiProducer- the throughput is reduced, but the trend is the same.

Main (notice SingleProducer and BusySpinWaitStrategy)

```<code>import com.lmax.disruptor.BusySpinWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.ProducerType;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class LongEventMainJava{
        static double ONEMILLION = 1000000.0;
        static double ONEBILLION = 1000000000.0;

    public static void main(String[] args) throws Exception {
            // Executor that will be used to construct new threads for consumers
            Executor executor = Executors.newCachedThreadPool();

            // TUNABLE PARAMS
            int ringBufferSize = 1048576; // 1024, 64, 8
            int rotations = 1; // 1024, 16384, 131702

            // Construct the Disruptor
            Disruptor disruptor = new Disruptor<>(new LongEventFactory(), ringBufferSize, executor, ProducerType.SINGLE, new BusySpinWaitStrategy());

            // Connect the handler
            disruptor.handleEventsWith(new LongEventHandler());

            // Start the Disruptor, starts all threads running
            disruptor.start();

            // Get the ring buffer from the Disruptor to be used for publishing.
            RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();
            LongEventProducer producer = new LongEventProducer(ringBuffer);

            long start = System.nanoTime();
            long totalIterations = rotations * ringBufferSize;
            for (long i = 0; i < totalIterations; i++) {
                producer.onData();
            }
            double duration = (System.nanoTime()-start)/ONEBILLION;
            System.out.println(String.format("Buffersize: %s, rotations: %s, total iterations = %s, duration: %.2f seconds, rate: %.2f Mops/s",
                    ringBufferSize, rotations, totalIterations, duration, totalIterations/(ONEMILLION * duration)));
        }
}
</code>```

And to run, you'll need the trivial Factory code

```<code>import com.lmax.disruptor.EventFactory;

public class LongEventFactory implements EventFactory<LongEvent>
{
    public LongEvent newInstance()
    {
        return new LongEvent();
    }
}
</code>```

Running on core i5-2400, 12GB ram, windows 7

Sample Output

```<code>Buffersize: 1048576, rotations: 1, total iterations = 1048576, duration: 0.02 seconds, rate: 59.03 Mops/s

Buffersize: 64, rotations: 16384, total iterations = 1048576, duration: 2.01 seconds, rate: 0.52 Mops/s
</code>```

答:
When the producer(s) fills up the ring buffer, it has to wait until events are consumed before being able to proceed.

When your buffer is exactly the size of the number of elements you will put in, the producer never has to wait. It'll never overflow. All it's doing is essentially incrementing a count, the index, and publishing the data in the ring buffer at that index.

When your buffer is smaller, it's still just incrementing a count and publishing, but it's doing it faster than the consumer can consume. The producer therefore has to wait until elements are consumed and space on the ring buffer is freed up.

Body:
Following the Disruptor Getting Started Guide, I've built a minimal disruptor with a single producer and single consumer.

Producer

import com.lmax.disruptor.RingBuffer;

public class LongEventProducer
{
    private final RingBuffer<LongEvent> ringBuffer;

    public LongEventProducer(RingBuffer<LongEvent> ringBuffer)
    {
        this.ringBuffer = ringBuffer;
    }

    public void onData()
    {
        long sequence = ringBuffer.next();
        try
        {
            LongEvent event = ringBuffer.get(sequence);
        }
        finally
        {
            ringBuffer.publish(sequence);
        }
    }
}

Consumer (Notice the consumer does nothing onEvent)

import com.lmax.disruptor.EventHandler;

public class LongEventHandler implements EventHandler<LongEvent>
{
    public void onEvent(LongEvent event, long sequence, boolean endOfBatch)
    {}
}

My goal was to performance test going around a large ring buffer once versus traversing a smaller ring multiple times.  In each case the total ops (bufferSize X rotations) is the same.  I found was that the ops/sec rate fell drastically as the ring buffer got smaller.

RingBuffer Size |  Revolutions  | Total Ops   |   Mops/sec

    1048576     |      1        |  1048576    |     50-60

       1024     |      1024     |  1048576    |     8-16

        64      |      16384    |  1048576    |    0.5-0.7

        8       |      131072   |  1048576    |    0.12-0.14

Question: what is the reason for the massive degradation of performance when the ring buffer size is reduced but the total iterations is fixed?  This trend is independent of the WaitStrategy and Single vs MultiProducer- the throughput is reduced, but the trend is the same.

Main (notice SingleProducer and BusySpinWaitStrategy)

import com.lmax.disruptor.BusySpinWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.ProducerType;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class LongEventMainJava{
        static double ONEMILLION = 1000000.0;
        static double ONEBILLION = 1000000000.0;

    public static void main(String[] args) throws Exception {
            // Executor that will be used to construct new threads for consumers
            Executor executor = Executors.newCachedThreadPool();

            // TUNABLE PARAMS
            int ringBufferSize = 1048576; // 1024, 64, 8
            int rotations = 1; // 1024, 16384, 131702

            // Construct the Disruptor
            Disruptor disruptor = new Disruptor<>(new LongEventFactory(), ringBufferSize, executor, ProducerType.SINGLE, new BusySpinWaitStrategy());

            // Connect the handler
            disruptor.handleEventsWith(new LongEventHandler());

            // Start the Disruptor, starts all threads running
            disruptor.start();

            // Get the ring buffer from the Disruptor to be used for publishing.
            RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();
            LongEventProducer producer = new LongEventProducer(ringBuffer);

            long start = System.nanoTime();
            long totalIterations = rotations * ringBufferSize;
            for (long i = 0; i < totalIterations; i++) {
                producer.onData();
            }
            double duration = (System.nanoTime()-start)/ONEBILLION;
            System.out.println(String.format("Buffersize: %s, rotations: %s, total iterations = %s, duration: %.2f seconds, rate: %.2f Mops/s",
                    ringBufferSize, rotations, totalIterations, duration, totalIterations/(ONEMILLION * duration)));
        }
}

And to run, you'll need the trivial Factory code

import com.lmax.disruptor.EventFactory;

public class LongEventFactory implements EventFactory<LongEvent>
{
    public LongEvent newInstance()
    {
        return new LongEvent();
    }
}

Running on core i5-2400, 12GB ram, windows 7

Sample Output

Buffersize: 1048576, rotations: 1, total iterations = 1048576, duration: 0.02 seconds, rate: 59.03 Mops/s

Buffersize: 64, rotations: 16384, total iterations = 1048576, duration: 2.01 seconds, rate: 0.52 Mops/s