问:
Get date for N days before
I found some problem with my bat script which is dedicated to find date in format YYYYMMDD, but still can't figure out reason of such behavior.

Script code:

```<code>@ECHO OFF
SetLocal EnableDelayedExpansion
SetLocal

SET CmdFile="C:\cmd.ini"
SET StartDate = ""

call:getDate %1 StartDate

IF EXIST %CmdFile% del %CmdFile%

(
    echo RangeBegin=20%StartDate%
) > %CmdFile%

:getDate
set day=%~1
echo >"%temp%\%~n0.vbs" s=DateAdd("d",%day%,now) : d=weekday(s)
echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^& right(100+month(s),2)^& right(100+day(s),2)
for /f %%a in ('cscript /nologo "%temp%\%~n0.vbs"') do set "result=%%a"
set "YYYY=%result:~0,4%"
set "MM=%result:~4,2%"
set "DD=%result:~6,2%"
set "data=%YYYY:~2,4%%mm%%dd%"
set "%~2=%data%"
goto:eof

endlocal
</code>```

So, I call a script like makecmd.bat -10 and expect to find a new file in C:\ drive named cmd.ini with following context:

```<code>RangeBegin=20170627
</code>```

But got this:

```<code>RangeBegin=20,4~4,2~6,2
</code>```

What am I doing wrong?

答:
There are some more errors in the code:

```<code>SET StartDate = ""
</code>```

Will assign "" (leading space) to a variable named StartDate
with a trailing space

TheIF EXIST %CmdFile% del %CmdFile% is superfluous as the following
echo will overwrite the file nevertheless.

As program flow will reach the label :getDate there should be a
goto :eof or an Exit /b placed before.

In the vbscript the variable d isn't used, why define it?

The vbscript already creates a date in the format yyyyMMdd why
split it up and then wrongly put together in the remaining batch part?

The last line endlocal can never be reached.

Albeit I'm in doubt if a batch should have write access to the root of drive c: this batch version should do:

```<code>@ECHO OFF
SetLocal EnableDelayedExpansion

SET CmdFile="C:\cmd.ini"
SET "StartDate="
call:getDate %1 StartDate

 > %CmdFile% echo RangeBegin=%StartDate%

Goto :Eof
:getDate
set day=%~1
echo >"%temp%\%~n0.vbs" s=DateAdd("d",%day%,now) : d=weekday(s)
echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^& right(100+month(s),2)^& right(100+day(s),2)
for /f %%a in ('cscript /nologo "%temp%\%~n0.vbs"') do set "%~2=%%a"
</code>```

Sample ouput:

```<code>> SO_44973476.cmd -10
> type cmd.ini
RangeBegin=20170627
</code>```

If you don't mind using PowerShell from batch, this will give the very same result:

```<code>@ECHO OFF
for /f %%a in (
  'powershell -NonI -NoP -C "(get-date).AddDays(%~1).ToString(\"yyyyMMdd\")"'
) Do >"C:\cmd.ini" Echo RangeBegin=%%a
</code>```

Title: Get date for N days before

Body:
I found some problem with my bat script which is dedicated to find date in format YYYYMMDD, but still can't figure out reason of such behavior.

Script code:

@ECHO OFF
SetLocal EnableDelayedExpansion
SetLocal

SET CmdFile="C:\cmd.ini"
SET StartDate = ""

call:getDate %1 StartDate

IF EXIST %CmdFile% del %CmdFile%

(
    echo RangeBegin=20%StartDate%
) > %CmdFile%

:getDate
set day=%~1
echo >"%temp%\%~n0.vbs" s=DateAdd("d",%day%,now) : d=weekday(s)
echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^& right(100+month(s),2)^& right(100+day(s),2)
for /f %%a in ('cscript /nologo "%temp%\%~n0.vbs"') do set "result=%%a"
set "YYYY=%result:~0,4%"
set "MM=%result:~4,2%"
set "DD=%result:~6,2%"
set "data=%YYYY:~2,4%%mm%%dd%"
set "%~2=%data%"
goto:eof

endlocal

So, I call a script like makecmd.bat -10 and expect to find a new file in C:\ drive named cmd.ini with following context:

RangeBegin=20170627

But got this:

RangeBegin=20,4~4,2~6,2

What am I doing wrong?

Body:
There are some more errors in the code:

SET StartDate = ""

Will assign "" (leading space) to a variable named StartDate
with a trailing space

TheIF EXIST %CmdFile% del %CmdFile% is superfluous as the following
echo will overwrite the file nevertheless.

As program flow will reach the label :getDate there should be a
goto :eof or an Exit /b placed before.

In the vbscript the variable d isn't used, why define it?

The vbscript already creates a date in the format yyyyMMdd why
split it up and then wrongly put together in the remaining batch part?

The last line endlocal can never be reached.

Albeit I'm in doubt if a batch should have write access to the root of drive c: this batch version should do:

@ECHO OFF
SetLocal EnableDelayedExpansion

SET CmdFile="C:\cmd.ini"
SET "StartDate="
call:getDate %1 StartDate

 > %CmdFile% echo RangeBegin=%StartDate%

Goto :Eof
:getDate
set day=%~1
echo >"%temp%\%~n0.vbs" s=DateAdd("d",%day%,now) : d=weekday(s)
echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^& right(100+month(s),2)^& right(100+day(s),2)
for /f %%a in ('cscript /nologo "%temp%\%~n0.vbs"') do set "%~2=%%a"

Sample ouput:

> SO_44973476.cmd -10
> type cmd.ini
RangeBegin=20170627

If you don't mind using PowerShell from batch, this will give the very same result:

@ECHO OFF
for /f %%a in (
  'powershell -NonI -NoP -C "(get-date).AddDays(%~1).ToString(\"yyyyMMdd\")"'
) Do >"C:\cmd.ini" Echo RangeBegin=%%a


来源: stackexchange

问:
With jwilder nginx-proxy, how to proxypass a subdirectory url to a specific container?
I use jwilder/nginx-proxy to make a reverse proxy. I try to redirect http://localhost:8000/api to a specific php service.

The directory structure:

```<code>.
+-- docker-compose.yml
+-- nginx
+-- nodejs
|   +-- index.js
|   +-- …
+-- php
|   +-- api
</code>```

docker-compose.yml:

```<code>version: "3.1"

services:

  nginx-proxy:
    image: jwilder/nginx-proxy:alpine
    ports:
      - "8000:80"
    volumes:
      - ./php:/srv/www
      - /var/run/docker.sock:/tmp/docker.sock:ro

  nodejs:
    image: node:alpine
    environment:
      - NODE_ENV=production
      - VIRTUAL_HOST=localhost
      - VIRTUAL_PORT=8080
    expose:
      - "8080"
    working_dir: /home/app
    restart: always
    volumes:
      - ./nodejs:/home/app
    command: ["node", "index.js"]

  php:
    image: php:apache
    environment:
      - VIRTUAL_HOST=localhost
    volumes:
      - ./php:/var/www/html
</code>```

This works fine for the nodejs service.

Now, I would like to redirect calls to http://localhost:8000/api to the php service. I imagine that I have to add to the nginx conf something like:

```<code>server {
  location /api {
    proxy_pass http://php:80/api;
    proxy_set_header Host $host;
  }
}
</code>```

This feature is not built into the lib.
So, how can I achieve that?

答:
One approach is to give the php app its own virtual host:

```<code>  php:
    image: php:apache
    environment:
      - VIRTUAL_HOST=api.localhost
    volumes:
      - ./php:/var/www/html
</code>```

Then, it will be accesible as this:

```<code>curl -H 'Host: api.localhost' http://localhost:8000/api
</code>```

Setting the header can be achieved in practically any language. Or to avoid setting custom header, you can add that DNS to your /etc/hosts file:

```<code>127.0.0.1 api.localhost
</code>```

So you can curl as this:

```<code>curl -H http://api.localhost:8000/api
</code>```

This is how set custom headers, for example in node:

```<code>var request = require('request')

var formData = {}

request({
    headers: {
      'Host': 'api.localhost'
    },
    uri: 'http://localhost:8080',
    method: 'POST'
  }, function (err, res, body) {
      console.log("it works")
      console.log(res)
    }
)
</code>```

But, I recommend you to go for the /etc/hosts approach, that should has an equivalent in production environment (a DNS server). So you don't need to touch node code.

ContentLicense: CC BY-SA 3.0

Body:
I use jwilder/nginx-proxy to make a reverse proxy. I try to redirect http://localhost:8000/api to a specific php service.

The directory structure:

.
+-- docker-compose.yml
+-- nginx
+-- nodejs
|   +-- index.js
|   +-- …
+-- php
|   +-- api

docker-compose.yml:

version: "3.1"

services:

  nginx-proxy:
    image: jwilder/nginx-proxy:alpine
    ports:
      - "8000:80"
    volumes:
      - ./php:/srv/www
      - /var/run/docker.sock:/tmp/docker.sock:ro

  nodejs:
    image: node:alpine
    environment:
      - NODE_ENV=production
      - VIRTUAL_HOST=localhost
      - VIRTUAL_PORT=8080
    expose:
      - "8080"
    working_dir: /home/app
    restart: always
    volumes:
      - ./nodejs:/home/app
    command: ["node", "index.js"]

  php:
    image: php:apache
    environment:
      - VIRTUAL_HOST=localhost
    volumes:
      - ./php:/var/www/html

This works fine for the nodejs service.

Now, I would like to redirect calls to http://localhost:8000/api to the php service. I imagine that I have to add to the nginx conf something like:

server {
  location /api {
    proxy_pass http://php:80/api;
    proxy_set_header Host $host;
  }
}

This feature is not built into the lib.
So, how can I achieve that?

Body:
One approach is to give the php app its own virtual host:

  php:
    image: php:apache
    environment:
      - VIRTUAL_HOST=api.localhost
    volumes:
      - ./php:/var/www/html

Then, it will be accesible as this:

curl -H 'Host: api.localhost' http://localhost:8000/api

Setting the header can be achieved in practically any language. Or to avoid setting custom header, you can add that DNS to your /etc/hosts file:

127.0.0.1 api.localhost

So you can curl as this:

curl -H http://api.localhost:8000/api

This is how set custom headers, for example in node:

var request = require('request')

var formData = {}

request({
    headers: {
      'Host': 'api.localhost'
    },
    uri: 'http://localhost:8080',
    method: 'POST'
  }, function (err, res, body) {
      console.log("it works")
      console.log(res)
    }
)

But, I recommend you to go for the /etc/hosts approach, that should has an equivalent in production environment (a DNS server). So you don't need to touch node code.


问:
How to access an element of a list using a variable in python
Given that I have a target location for a multi-dimensional list. I.e. an index stored in a variable.

```<code>list = [[1,2,3,4,5],
        [10,20,30,40,50],
        [5,4,3,2,1],
        [50,40,30,20,10]]
target = [3][4]
</code>```

How do I access list[target]?

```<code>  >>> list[target]
    10
</code>```

答:
If target is given as a list of indices like [3, 4, 1], you can use reduce:

```<code>from functools import reduce # not required in py2

result = reduce(list.__getitem__, target, my_list)
</code>```

Note that this won't work if you've used list as a name for your variable. Never use the names of builtins for your variables. Name it my_list or something more descriptive.

Body:
Given that I have a target location for a multi-dimensional list. I.e. an index stored in a variable.

list = [[1,2,3,4,5],
        [10,20,30,40,50],
        [5,4,3,2,1],
        [50,40,30,20,10]]
target = [3][4]

How do I access list[target]?

  >>> list[target]
    10

Body:
If target is given as a list of indices like [3, 4, 1], you can use reduce:

from functools import reduce # not required in py2

result = reduce(list.__getitem__, target, my_list)

Note that this won't work if you've used list as a name for your variable. Never use the names of builtins for your variables. Name it my_list or something more descriptive.


问:
Need to get value from DropDownListFor asp.net mvc
I have combobox in view and I need to get select value in combobox.

Code View:

```<code>@Html.DropDownListFor(model => model.servicesModel, (SelectList)ViewBag.serviceNames, new { @id = "listNames" })
</code>```

Code action that added values in combobox(I know, I missed the symbol in database when created table):

```<code>var servicesDetails = dbModel.SERVICES.ToList();

        ViewBag.serviceNames = new SelectList(servicesDetails, "iIdSevices", "vName");
</code>```

I have form, press button and after that thanks to @using (Html.BeginForm("SendApplication", "Home", FormMethod.Post)) I send data to My actionResult.

My ActionResult:

```<code> [HttpPost]
    public ActionResult SendApplication(App_AppTemp_Serv_PersInfModel appFile, int iIdServices)
    {
        int iIdService = 0;

        var serviceDetails = dbModel.SERVICES.Where(x => x.iIdSevices == iIdServices).FirstOrDefault();
        iIdService = serviceDetails.iIdSevices;

        if (bFile == true)
        {
            appFile.appModel.vFile = "Приклепленные файлы имеются";
        }
        else
        {
            appFile.appModel.vFile = "Приклепленных файлов нет";
        }

        appFile.appModel.vDate = Convert.ToString(DateTime.Now);

        try
        {
            dbModel.APPLICATIONS.Add(appFile.appModel);
            dbModel.SaveChanges();
            ModelState.Clear();
        }
        catch (Exception exc)
        {
            ViewBag.sErrorMessage = exc.Message;
        }

        return View("~/Views/Home/ProblemForm.cshtml", appFile);
    }
</code>```

But I can't to get the data from combobox, I don't know how?! Maybe use class and get class value, anyone have a idea for this?

答:
Hi you can get the data from dropdownlist using the name of that control. It seems that  in your example model.servicesModel will be the name of dropdownlist. so in your controller get data using that property .

for ex: Assuming App_AppTemp_Serv_PersInfModel is your model, if no, change it accordingly

```<code>[HttpPost]
    public ActionResult SendApplication(App_AppTemp_Serv_PersInfModel appFile, int iIdServices)
    {

            //dropdownlist selected value

            string selectedvalue =   appFile.servicesModel

           //other code
}
</code>```

Hope it was helpful

Thanks

Karthik

Body:
I have combobox in view and I need to get select value in combobox.

Code View:

@Html.DropDownListFor(model => model.servicesModel, (SelectList)ViewBag.serviceNames, new { @id = "listNames" })

Code action that added values in combobox(I know, I missed the symbol in database when created table):

var servicesDetails = dbModel.SERVICES.ToList();

        ViewBag.serviceNames = new SelectList(servicesDetails, "iIdSevices", "vName");

I have form, press button and after that thanks to @using (Html.BeginForm("SendApplication", "Home", FormMethod.Post)) I send data to My actionResult.

My ActionResult:

 [HttpPost]
    public ActionResult SendApplication(App_AppTemp_Serv_PersInfModel appFile, int iIdServices)
    {
        int iIdService = 0;

        var serviceDetails = dbModel.SERVICES.Where(x => x.iIdSevices == iIdServices).FirstOrDefault();
        iIdService = serviceDetails.iIdSevices;

        if (bFile == true)
        {
            appFile.appModel.vFile = "Приклепленные файлы имеются";
        }
        else
        {
            appFile.appModel.vFile = "Приклепленных файлов нет";
        }

        appFile.appModel.vDate = Convert.ToString(DateTime.Now);

        try
        {
            dbModel.APPLICATIONS.Add(appFile.appModel);
            dbModel.SaveChanges();
            ModelState.Clear();
        }
        catch (Exception exc)
        {
            ViewBag.sErrorMessage = exc.Message;
        }

        return View("~/Views/Home/ProblemForm.cshtml", appFile);
    }

But I can't to get the data from combobox, I don't know how?! Maybe use class and get class value, anyone have a idea for this?

Body:
Hi you can get the data from dropdownlist using the name of that control. It seems that  in your example model.servicesModel will be the name of dropdownlist. so in your controller get data using that property .

for ex: Assuming App_AppTemp_Serv_PersInfModel is your model, if no, change it accordingly

[HttpPost]
    public ActionResult SendApplication(App_AppTemp_Serv_PersInfModel appFile, int iIdServices)
    {

            //dropdownlist selected value

            string selectedvalue =   appFile.servicesModel

           //other code
}

Hope it was helpful

Thanks

Karthik


问:
How to format (really) big numbers in Javascript?
I want something like the library JavaScript BigNum and Numeral.js working together.

In Numeral.js, I can use strings like this:

```<code>var number = numeral('1110000000000000000000000000000000000000000000000000011100000000000000000011111111100');
</code>```

but the result of number.format(); is really disappointing:

```<code>"1.11e+84"
</code>```

Any way to format a (really) big number nicely?

EDIT: I don't want just avoid scientific notation, it was a wrong assumption. I want to "nicely" format, as I want, for example:

```<code>var number = numeral(1000);
numeral.defaultFormat('$0,0.00');

number.format();
// '$1,000.00'
</code>```

Well, if the number is big:

```<code>var number = numeral('100000000000000000000000000');
"$9.999999999999999e+25"
</code>```

This is a mess. I know JavaScript can't handle big numbers, but my question is exactly because that! I would like a library or a possible solution to this problem.

答:
You can use Intl.NumberFormat.prototype.format, String.prototype.slice(), String.prototype.concat()</p>

```<code>var number = 2.9364136545300044e+24;
var n = new Intl.NumberFormat().format(number);
var res = n.slice(0, 9).concat(".").concat(n.slice(10, 12));
console.log(res);
</code>```

Body:
I want something like the library JavaScript BigNum and Numeral.js working together.

In Numeral.js, I can use strings like this:

var number = numeral('1110000000000000000000000000000000000000000000000000011100000000000000000011111111100');

but the result of number.format(); is really disappointing:

"1.11e+84"

Any way to format a (really) big number nicely?

EDIT: I don't want just avoid scientific notation, it was a wrong assumption. I want to "nicely" format, as I want, for example:

var number = numeral(1000);
numeral.defaultFormat('$0,0.00');

number.format();
// '$1,000.00'

Well, if the number is big:

var number = numeral('100000000000000000000000000');
"$9.999999999999999e+25"

This is a mess. I know JavaScript can't handle big numbers, but my question is exactly because that! I would like a library or a possible solution to this problem.

Body:
You can use Intl.NumberFormat.prototype.format, String.prototype.slice(), String.prototype.concat()

var number = 2.9364136545300044e+24;
var n = new Intl.NumberFormat().format(number);
var res = n.slice(0, 9).concat(".").concat(n.slice(10, 12));
console.log(res);


问:
differentiate between instances of the same form with different prefixes in Django
I am passing two form with different prefix in the template and each form has own submit button but how can I get data from these two form in submit button is pressed in any one of them and how to differentiate which form button was pressed

```<code>return render(request,'part_details.html', {'part_stock_form': forms.part_stock_form(prefix='add'),'part_stock_edit':forms.part_stock_form(prefix='edit')})
</code>```

template: add_app form object

```<code><form id="add_app_form" method="post" action="{% url 'parts:part_app_model' part_temp.part_id %}">
    {% csrf_token %}
    {{ add_app.applicable }}
    <input type="submit">
</form>
</code>```

template: edit_app form object

```<code>  <form method="post"  action="{% url 'parts:part_app_model' part_temp.part_id %}">
    {{ edit_app.applicable }}
    <input type="submit">
</form>
</code>```

答:
since you have 2 submit button name them and check them, like </p>

```<code><input type="submit" name="fom1">sumbit formm 1

<input type="submit" name="fom2">sumbit formm 2

if 'fom1' in request.POST:
    #statements
elif 'fom2' in request.POST:
    #statements
</code>```

Body:
I am passing two form with different prefix in the template and each form has own submit button but how can I get data from these two form in submit button is pressed in any one of them and how to differentiate which form button was pressed

return render(request,'part_details.html', {'part_stock_form': forms.part_stock_form(prefix='add'),'part_stock_edit':forms.part_stock_form(prefix='edit')})

template: add_app form object

<form id="add_app_form" method="post" action="{% url 'parts:part_app_model' part_temp.part_id %}">
    {% csrf_token %}
    {{ add_app.applicable }}
    <input type="submit">
</form>

template: edit_app form object

  <form method="post"  action="{% url 'parts:part_app_model' part_temp.part_id %}">
    {{ edit_app.applicable }}
    <input type="submit">
</form>

Body:
since you have 2 submit button name them and check them, like

<input type="submit" name="fom1">sumbit formm 1

<input type="submit" name="fom2">sumbit formm 2

if 'fom1' in request.POST:
    #statements
elif 'fom2' in request.POST:
    #statements


问:
Why can't I debug/step-into FormsAuthentication.Authenticate?
I am having some trouble with active directory authentication using FormsAuthentication in ASP.NET MVC 2 (VS 2010).

As I understand it I should be able to step into/through the Microsoft source code for FormsAuthentication.Authenticate if I check 'Enable source server support' and 'Enable .Net Framework source stepping' in  Options->Debug->General and specify 'Microsoft Symbol Servers' in Options->Debug->Symbols.

I have done this and can step into a whole bunch of MS source code, but not FormsAuthentication.Authenticate. The debugger simple steps over it.

Can anyone tell me why this is? If I could step into FormsAuthentication.Authenticate it would make my life a whole lot easier.

Thanks.

答:
Ok, my stupid.

I should have been using Membership.ValidateUser NOT FormsAuthentication.Authenticate.

My problems are all solved :)

However, I never figured out why I could not step into FormsAuthentication.Authenticate. I guess it will remain a mystery...

ContentLicense: CC BY-SA 2.5


问:
C# Linq GroupBy and Select performance
I'm working with a third part service of my client that is providing me a list of products and services, which is a little bit of a mess.

The list will return all of the services for the product but the product repeats itself, for example:

The product A has the service A and the product A also has the service B so, when i receive the list i will get two products A with services A and B

What i need to do is to group all of the products to get only one with all of it's services and i have done so but i'm worried about performance because i think my solution isn't the 'best' one:

```<code>var productsNormalized = products.Data.AsEnumerable().Select(x => new ProdutoSSO
{
    CodigoServico = int.Parse(string.IsNullOrEmpty(x["CodigoServico"].ToString()) ? "0" : x["CodigoServico"].ToString()),
    CodigoPeca = int.Parse(string.IsNullOrEmpty(x["CodigoPeca"].ToString()) ? "0" : x["CodigoPeca"].ToString()),
    CodigoFamilia = int.Parse(string.IsNullOrEmpty(x["CodigoFamilia"].ToString()) ? "0" : x["CodigoFamilia"].ToString()),
    Familia = x["Familia"].ToString(),
    Servico = x["Servico"].ToString(),
    Peca = x["Peca"].ToString(),
    Hash = x["Hash"].ToString(),
    Valor = decimal.Parse(string.IsNullOrEmpty(x["Valor"].ToString()) ? "0" : x["Valor"].ToString())
})
.GroupBy(x => new { x.CodigoPeca, x.CodigoFamilia, x.Familia, x.Peca })
.Select(x => new ProdutoGroup
{
    Produto = new Produto
    {
        CodigoPeca = x.Key.CodigoPeca,
        CodigoFamilia = x.Key.CodigoFamilia,
        Familia = x.Key.Familia,
        Peca = x.Key.Peca
    },
    Servicos = x.Select(y => new ProdutoServico
    {
        CodigoServico = y.CodigoServico,
        Hash = y.Hash,
        Servico = y.Servico,
        Valor = y.Valor
    }).ToList()
});
</code>```

Is there a better way to achieve this or this is as good as it gets?

答:
Using Aggregate you could do something like this (assuming you are starting with a list of ProdutoSSO, which might not be entirely necessary):

```<code>var productsNormalized = productoSSOs
    .Aggregate(new Dictionary<Produto,List<ProdutoServico>>(ProductoComparer),
    (p,c) => {
    var product = new Produto
    {
        CodigoPeca = c.CodigoPeca,
        CodigoFamilia = c.CodigoFamilia,
        Familia = c.Familia,
        Peca = c.Peca
    };
    var service = new ProdutoServico
    {
        CodigoServico = c.CodigoServico,
        Hash = c.Hash,
        Servico = c.Servico,
        Valor = c.Valor
    };
    if (!p.ContainsKey(product))
    {
        p[product] = new List<ProductoServico>() { service };
    }
    else
    {
        p[product].Add(service);
    }
    return p;
});
</code>```

Where ProductoComparer is an IEqualityComparer<Producto> (or alternatively you could implement Equals and GetHashCode in Producto, or you could just generate a key some other way - concatenating fields together, for example).

This is obviously untested since I don't have the original classes or data.

This would give you a Dictionary<Producto, List<ProductoServico>> which might be all you need, or you can easily transform it into an IEnumerable<ProdutoGroup> if you want.

Title: C# Linq GroupBy and Select performance

Body:
I'm working with a third part service of my client that is providing me a list of products and services, which is a little bit of a mess.

The list will return all of the services for the product but the product repeats itself, for example:

The product A has the service A and the product A also has the service B so, when i receive the list i will get two products A with services A and B

What i need to do is to group all of the products to get only one with all of it's services and i have done so but i'm worried about performance because i think my solution isn't the 'best' one:

var productsNormalized = products.Data.AsEnumerable().Select(x => new ProdutoSSO
{
    CodigoServico = int.Parse(string.IsNullOrEmpty(x["CodigoServico"].ToString()) ? "0" : x["CodigoServico"].ToString()),
    CodigoPeca = int.Parse(string.IsNullOrEmpty(x["CodigoPeca"].ToString()) ? "0" : x["CodigoPeca"].ToString()),
    CodigoFamilia = int.Parse(string.IsNullOrEmpty(x["CodigoFamilia"].ToString()) ? "0" : x["CodigoFamilia"].ToString()),
    Familia = x["Familia"].ToString(),
    Servico = x["Servico"].ToString(),
    Peca = x["Peca"].ToString(),
    Hash = x["Hash"].ToString(),
    Valor = decimal.Parse(string.IsNullOrEmpty(x["Valor"].ToString()) ? "0" : x["Valor"].ToString())
})
.GroupBy(x => new { x.CodigoPeca, x.CodigoFamilia, x.Familia, x.Peca })
.Select(x => new ProdutoGroup
{
    Produto = new Produto
    {
        CodigoPeca = x.Key.CodigoPeca,
        CodigoFamilia = x.Key.CodigoFamilia,
        Familia = x.Key.Familia,
        Peca = x.Key.Peca
    },
    Servicos = x.Select(y => new ProdutoServico
    {
        CodigoServico = y.CodigoServico,
        Hash = y.Hash,
        Servico = y.Servico,
        Valor = y.Valor
    }).ToList()
});

Is there a better way to achieve this or this is as good as it gets?

Body:
Using Aggregate you could do something like this (assuming you are starting with a list of ProdutoSSO, which might not be entirely necessary):

var productsNormalized = productoSSOs
    .Aggregate(new Dictionary<Produto,List<ProdutoServico>>(ProductoComparer),
    (p,c) => {
    var product = new Produto
    {
        CodigoPeca = c.CodigoPeca,
        CodigoFamilia = c.CodigoFamilia,
        Familia = c.Familia,
        Peca = c.Peca
    };
    var service = new ProdutoServico
    {
        CodigoServico = c.CodigoServico,
        Hash = c.Hash,
        Servico = c.Servico,
        Valor = c.Valor
    };
    if (!p.ContainsKey(product))
    {
        p[product] = new List<ProductoServico>() { service };
    }
    else
    {
        p[product].Add(service);
    }
    return p;
});

Where ProductoComparer is an IEqualityComparer<Producto> (or alternatively you could implement Equals and GetHashCode in Producto, or you could just generate a key some other way - concatenating fields together, for example).

This is obviously untested since I don't have the original classes or data.

This would give you a Dictionary<Producto, List<ProductoServico>> which might be all you need, or you can easily transform it into an IEnumerable<ProdutoGroup> if you want.


问:
Replace Text/Image URL with CSS
I am trying to make a custom style for the stylish plugin to use for the Eve Online forums.  I am attempting to resize the avatar image because it was too small for my liking. However it's using a low-quality image and it looks too grainy when resized, so I am trying to figure out how to use the larger image by replacing part of the text, or replacing the url (whatever is easier).  In the image, the only difference a piece of text that shows the size.

See:

meta.eveonline.com/erika_mizune/45/2168_1.png
meta.eveonline.com/erika_mizune/90/2168_1.png

So essentially the 45 (original) needs to be replaced with the 90 in order to look less grainy.

URL to Post: https://meta.eveonline.com/t/avatar-size-category-adjustment/9032

Stylish Plugin: https://userstyles.org/styles/144974/avatar-category-adjustment

My code to resize the image is this:

 .topic-avatar img.avatar
  {
    height: 75px;
    width: 75px;
    border-radius: 0;
  }

  .topic-avatar
  {
    width: 75px !important;
  }```
</div>
</div>
</p>

<p>I tried to search before posting but I'm not finding anything that will work for what I need. </p>

<p>Thanks!</p>

<hr>

<p>Edit 1: I attempted to switch to tampermonkey to use JS as suggested but is not working.  Below is the origional code:</p>

```

```

<p>And the script I have in tampermonkey:</p>

```    var imagelist = document.getElementsByClassName("avatar");
    imagelist.foreach(function(element) {
        element.src = element.src.replace("/45/", "/90/");
    });
```

<hr>

<p>Edit 2: After trying to use debugging in the console I got the error that .foreach is not a function and attempted to try the following as well:</p>

<p>Try 1:</p>

```var imagelist = document.getElementsByTagName("img");
        imagelist.foreach(function(element) {
            element.src = element.src.replace("/45/", "/90/");
        });
```

<p>Try 2:</p>

```var imagelist = Array.from(document.getElementsByClassName('avatar'));
imagelist.foreach(function(element) {
    element.src = element.src.replace("/45/", "/90/");
});
```

<p>Try 3:</p>

```   var imagelist = Array.from(document.getElementsByTagName('img'));
imagelist.foreach(function(element) {
    element.src = element.src.replace("/45/", "/90/");
});
```

All of these attempts have returned the same error in console that .foreach is not a function.

答:
It isn't possible to change html content with CSS in the way you're describing. I'd recommend using Javascript to change the src of the  tag. Do something like

```<code>var imagelist = document.getElementsByClassName("forum_image_class");
imagelist.foreach(function(element){
    element.src = element.src.replace("/45/", "/90/");
}
</code>```

Title: Replace Text/Image URL with CSS

Body:
I am trying to make a custom style for the stylish plugin to use for the Eve Online forums.  I am attempting to resize the avatar image because it was too small for my liking. However it's using a low-quality image and it looks too grainy when resized, so I am trying to figure out how to use the larger image by replacing part of the text, or replacing the url (whatever is easier).  In the image, the only difference a piece of text that shows the size.

See:

meta.eveonline.com/erika_mizune/45/2168_1.png
meta.eveonline.com/erika_mizune/90/2168_1.png

So essentially the 45 (original) needs to be replaced with the 90 in order to look less grainy.

URL to Post: https://meta.eveonline.com/t/avatar-size-category-adjustment/9032

Stylish Plugin: https://userstyles.org/styles/144974/avatar-category-adjustment

My code to resize the image is this:

 .topic-avatar img.avatar
  {
    height: 75px;
    width: 75px;
    border-radius: 0;
  }

  .topic-avatar
  {
    width: 75px !important;
  }

I tried to search before posting but I'm not finding anything that will work for what I need.

Thanks!

Edit 1: I attempted to switch to tampermonkey to use JS as suggested but is not working.  Below is the origional code:

And the script I have in tampermonkey:

    var imagelist = document.getElementsByClassName("avatar");
    imagelist.foreach(function(element) {
        element.src = element.src.replace("/45/", "/90/");
    });

Edit 2: After trying to use debugging in the console I got the error that .foreach is not a function and attempted to try the following as well:

Try 1:

var imagelist = document.getElementsByTagName("img");
        imagelist.foreach(function(element) {
            element.src = element.src.replace("/45/", "/90/");
        });

Try 2:

var imagelist = Array.from(document.getElementsByClassName('avatar'));
imagelist.foreach(function(element) {
    element.src = element.src.replace("/45/", "/90/");
});

Try 3:

   var imagelist = Array.from(document.getElementsByTagName('img'));
imagelist.foreach(function(element) {
    element.src = element.src.replace("/45/", "/90/");
});

All of these attempts have returned the same error in console that .foreach is not a function.

Body:
It isn't possible to change html content with CSS in the way you're describing. I'd recommend using Javascript to change the src of the <img> tag. Do something like

var imagelist = document.getElementsByClassName("forum_image_class");
imagelist.foreach(function(element){
    element.src = element.src.replace("/45/", "/90/");
}


问:
Creating a box with SceneKit and ARKit
I am trying to create a primitive with SceneKit and ARKit. For whatever reason, it is not working.

```<code>let box = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0)

    let node = SCNNode(geometry: box)

    node.position = SCNVector3(0,0,0)

    sceneView.scene.rootNode.addChildNode(node)
</code>```

Do I need to take in the camera coordinates as well?

答:
You should get the location tapped and use the world coordinates to place the cube properly. I'm not sure (0,0,0) is a normal location for ARKit. You can try something like this:

Put this in your viewDidLoad:

```<code>let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapFrom))
tapGestureRecognizer.numberOfTapsRequired = 1
self.sceneView.addGestureRecognizer(tapGestureRecognizer)
</code>```

Then add this method:

```<code>@objc func handleTapFrom(recognizer: UITapGestureRecognizer) {
    let tapPoint = recognizer.location(in: self.sceneView)
    let result = self.sceneView.hitTest(tapPoint, types: ARHitTestResult.ResultType.existingPlaneUsingExtent)

    if result.count == 0 {
        return
    }

    let hitResult = result.first

    let box = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0)

    let node = SCNNode(geometry: box)
    node.physicsBody = SCNPhysicsBody(type: SCNPhysicsBodyType.static, shape: nil)
    node.position = SCNVector3Make(hitResult.worldTransform.columns.3.x, hitResult.worldTransform.columns.3.y, hitResult.worldTransform.columns.3.z)

    sceneView.scene.rootNode.addChildNode(node)
}
</code>```

Then when you tap on a plane surface detected, it will add a box on the plane where you tapped.

Title: Creating a box with SceneKit and ARKit

Body:
I am trying to create a primitive with SceneKit and ARKit. For whatever reason, it is not working.

let box = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0)

    let node = SCNNode(geometry: box)

    node.position = SCNVector3(0,0,0)

    sceneView.scene.rootNode.addChildNode(node)

Do I need to take in the camera coordinates as well?

Body:
You should get the location tapped and use the world coordinates to place the cube properly. I'm not sure (0,0,0) is a normal location for ARKit. You can try something like this:

Put this in your viewDidLoad:

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapFrom))
tapGestureRecognizer.numberOfTapsRequired = 1
self.sceneView.addGestureRecognizer(tapGestureRecognizer)

Then add this method:

@objc func handleTapFrom(recognizer: UITapGestureRecognizer) {
    let tapPoint = recognizer.location(in: self.sceneView)
    let result = self.sceneView.hitTest(tapPoint, types: ARHitTestResult.ResultType.existingPlaneUsingExtent)

    if result.count == 0 {
        return
    }

    let hitResult = result.first

    let box = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0)

    let node = SCNNode(geometry: box)
    node.physicsBody = SCNPhysicsBody(type: SCNPhysicsBodyType.static, shape: nil)
    node.position = SCNVector3Make(hitResult.worldTransform.columns.3.x, hitResult.worldTransform.columns.3.y, hitResult.worldTransform.columns.3.z)

    sceneView.scene.rootNode.addChildNode(node)
}

Then when you tap on a plane surface detected, it will add a box on the plane where you tapped.


问:
Where is best place to load data from redux-store ?
I use componentDidMount() method in my parent React component to fetch some data from API, which are then saved in redux-state.

In my render method, I have another component which should use data from the global redux-state.

I can send data to my child component via props or I can load them using mapStateToProps().

If I try to console.log or assign data to var from props in my child component constructor or in componentDidMount() method, I'm not getting my data as expected (I'm getting initial state).

Console.log in my render method will show me initial state at first rendering, on the second it will show correct data.

I need point where I'm sure that I have correct data.

...where var a = this.props.somethingFromState; will be assigned correctly.

Is render method best place and what is best practice for doing this in general. Thanks.

答:
There are a couple of questions here.

With respect to where to load data, componentDidMount is indeed the correct place to call ajax methods and load data as suggested by the facebook docs.

In terms of whether or not to then pass that data down to child components via props, I like to follow Dan Abramov's (the author of redux) guid on presentational vs container components. In short, try to have a container component that loads your data and does all the logic, and then pass whatever is necessary down to presentational components via props, making them pure functions if possible.

In terms of when you will have the correct data, check the React lifecycle docs above. You will see that the constructor fires, then componentWillMount, then render, then componentDidMount. So if your ajax call gets the data in componentDidMount, you will have called render first, resulting in no data being loaded on the already mounted component. Most people solve this by putting a spinner until the data has finished loading from ajax. A simple if statement should accomplish this


问:
iOS - How to read audio from a stream and play the audio
Thank you to everyone who takes the time to read the question!

So I've made a stream using MultipeerConnectivity. I am able to record audio into a CMSampleBuffer and convert that buffer into UInt8 data. Then send that data to a peer using the method:

```<code>outputStream!.write(u8ptr, maxLength: Int(buffer.mDataByteSize))
</code>```

Then when the data shows up on the inputStream the following method is called:

```<code>func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
</code>```

I have print statements, so this part is running fine. When data actually shows up, I call my function

```<code>func readFromStream() {
</code>```

I know that I need to call the inputStream.read method to actually read from the stream, but I'm not sure how to actually read the data and then convert it to NSData so that it can be played using AVAudioPlayer.

(Unless you're aware of a better, more efficient way)

This is what I have so far, but I haven't tested it and I assume there is going to be problems.

```<code>func readFromStream() {
    var buffer = [UInt8](repeating: 0, count: 1024)

    while (inputStream!.hasBytesAvailable) {
        let length = inputStream!.read(&buffer, maxLength: buffer.count)

        if (length > 0) {

            if (audioEngine!.isRunning) {
                audioEngine!.stop()
                audioEngine!.reset()
            }

            print("\(#file) > \(#function) > \(length) bytes read")

            let audioBuffer = bytesToAudioBuffer(buffer)
            let mainMixer = audioEngine!.mainMixerNode

            audioEngine!.connect(audioPlayer!, to: mainMixer, format: audioBuffer.format)

            audioPlayer!.scheduleBuffer(audioBuffer, completionHandler: nil)

            do {
                try audioEngine!.start()
            }
            catch let error as NSError {
                print("\(#file) > \(#function) > error: \(error.localizedDescription)")
            }

            audioPlayer!.play()
        }
    }
}
</code>```

Based on what I have, there is no audio playing. It is silence, but I can see that audio is being received by one of the devices.

So basically, my question is, how do I convert this buffer to the correct data type so that it can be played live?

Thank you for your help! If you need more information, please let me know.

答:
To convert UInt8 into NSData > NSData from UInt8

Once you've done that, just use AVAudioPlayer

```<code>let player = AVAudioPlayer(data: data)
player.play()
</code>```

Body:
Thank you to everyone who takes the time to read the question!

So I've made a stream using MultipeerConnectivity. I am able to record audio into a CMSampleBuffer and convert that buffer into UInt8 data. Then send that data to a peer using the method:

outputStream!.write(u8ptr, maxLength: Int(buffer.mDataByteSize))

Then when the data shows up on the inputStream the following method is called:

func stream(_ aStream: Stream, handle eventCode: Stream.Event) {

I have print statements, so this part is running fine. When data actually shows up, I call my function

func readFromStream() {

I know that I need to call the inputStream.read method to actually read from the stream, but I'm not sure how to actually read the data and then convert it to NSData so that it can be played using AVAudioPlayer.

(Unless you're aware of a better, more efficient way)

This is what I have so far, but I haven't tested it and I assume there is going to be problems.

func readFromStream() {
    var buffer = [UInt8](repeating: 0, count: 1024)

    while (inputStream!.hasBytesAvailable) {
        let length = inputStream!.read(&buffer, maxLength: buffer.count)

        if (length > 0) {

            if (audioEngine!.isRunning) {
                audioEngine!.stop()
                audioEngine!.reset()
            }

            print("\(#file) > \(#function) > \(length) bytes read")

            let audioBuffer = bytesToAudioBuffer(buffer)
            let mainMixer = audioEngine!.mainMixerNode

            audioEngine!.connect(audioPlayer!, to: mainMixer, format: audioBuffer.format)

            audioPlayer!.scheduleBuffer(audioBuffer, completionHandler: nil)

            do {
                try audioEngine!.start()
            }
            catch let error as NSError {
                print("\(#file) > \(#function) > error: \(error.localizedDescription)")
            }

            audioPlayer!.play()
        }
    }
}

Based on what I have, there is no audio playing. It is silence, but I can see that audio is being received by one of the devices.

So basically, my question is, how do I convert this buffer to the correct data type so that it can be played live?

Thank you for your help! If you need more information, please let me know.

Body:
To convert UInt8 into NSData > NSData from UInt8

Once you've done that, just use AVAudioPlayer

let player = AVAudioPlayer(data: data)
player.play()


问:
object-oriented shell for linux?
Is there anything similar to Microsoft Powershell (an object-oriented shell built on the .NET framework) for Linux (possibly built on Java, GObject, or its own object type/nothing)?

edit: especially if similar to bash or powershell or cmd etc. syntax (=''standard'' shell syntax)

答:
Perl, Python, and Ruby

Ok, I'm sure you already know that, but someone had to say it.

Perl is the oldest and most popular.

If you like objects, you will probably love Ruby. It has an elaborate object system inspired by Smalltalk.

Python has this cool block-structure-by-indent syntax.

Unix is a gold mine of advanced scripting tools...

Title: object-oriented shell for linux?


问:
GNUplot plot function doesn't save file
Ive installed GNUplot on OSX using

```<code>brew install gnuplot
</code>```

in terminal. I can open gnuplot using

```<code>gnuplot
</code>```

in terminal. I then use

```<code>set terminal png
</code>```

But then if I try to plot anything I just get random characters printed to the screen.

e.g

```<code>plot sin(x)/x
</code>```

returns

```<code>     Q%@??L?r??T?   89??? ?v?*?`"?Ө~???;???o.?/???jk??W}???f??C8???rR??2j??        GE?e.?fJ??zv!S?f]|???=?^<}?Bq?m??
    ^<??C&G{nR?Ũ?"~?(YA@?????ϱ??????yd?В->桮???o??~??*-R??m???Q??????Я??=?
    ң?9????(Z<?C]???߫???\?wH??Ѧ??(Z?C_???ww???w??ǣ??txE??y???F??q%?n??Q???ǁ|????(Z???X@???V??q3????Pӣ??y?y?e?p???EHK?y????xj?l7?{ݟ?g?1BG?Q?8???g/oD??k#g??h?1}=?n????:????<?????
           ??Ń'?IEND?B`?gnuplot>
</code>```

The same thing happens if I set the terminal to jpeg.

答:
gnuplot just prints the contents of a png file that you want to create. You should specify the file name:</p>

```<code>set output "myfile.png"
</code>```

ContentLicense: CC BY-SA 4.0

Title: GNUplot plot function doesn't save file

Body:
Ive installed GNUplot on OSX using

brew install gnuplot

in terminal. I can open gnuplot using

gnuplot

in terminal. I then use

set terminal png

But then if I try to plot anything I just get random characters printed to the screen.

e.g

plot sin(x)/x

returns

     Q%@??L?r??T?   89??? ?v?*?`"?Ө~???;???o.?/???jk??W}???f??C8???rR??2j??        GE?e.?fJ??zv!S?f]|???=?^<}?Bq?m??
    ^<??C&G{nR?Ũ?"~?(YA@?????ϱ??????yd?В->桮???o??~??*-R??m???Q??????Я??=?
    ң?9????(Z<?C]???߫???\?wH??Ѧ??(Z?C_???ww???w??ǣ??txE??y???F??q%?n??Q???ǁ|????(Z???X@???V??q3????Pӣ??y?y?e?p???EHK?y????xj?l7?{ݟ?g?1BG?Q?8???g/oD??k#g??h?1}=?n????:????<?????
           ??Ń'?IEND?B`?gnuplot>

The same thing happens if I set the terminal to jpeg.

Body:
gnuplot just prints the contents of a png file that you want to create. You should specify the file name:

set output "myfile.png"


问:
When to choose multiple loops over single loop with if-statements
I have to process each element of an array the same way once and have to modify each by an unpredictable pattern afterwards aswell.

Is there any difference in performance between these snippets and why, if so?

```<code>std::vector<int> nums;
//fill nums array

for(unsigned int i = 0; i < nums.size(); ++i){
    nums[i] *= nums[i];

    if(nums[i] < 10){
        nums[i] = 0;
    }
}
</code>```

```<code>std::vector<int> nums;
//fill nums array

for(unsigned int i = 0; i < nums.size(); ++i){
    nums[i] *= nums[i];
}

for(unsigned int i = 0; i < nums.size(); ++i){
    if(nums[i] < 10){
        nums[i] = 0;
    }
}
</code>```

Would a different approach like this improve anything?

```<code>std::vector<int> nums;
//fill nums array

std::vector<int> flags;
flags.resize(nums.size());

for(unsigned int i = 0; i < nums.size(); ++i){
    nums[i] *= nums[i];
    flags[i] = nums[i] < 10;
}

for(unsigned int i = 0; i < flags.size(); ++i){
   nums[i] = (!flags[i]) * nums[i]; //!flags[i] is 0 if nums[i] < 10
}
</code>```

答:
Test results on my machine (100 million ints in the array):

```<code>checkpoint
starting test: approach1
test took: 84ms
starting test: approach2
test took: 190ms
starting test: approach3
test took: 529ms
starting test: Bathsheba's idea
test took: 61ms
</code>```

Incidentally, writing idiomatic code is often the most efficient of all. clang, gcc et. al. optimisers are fantastic:

```<code>void approach5(std::vector<int> &nums) {

    auto filter = [](auto x) { return (x < 10) ? 0 : x; };

    auto grow = [filter](auto x) { return filter(x * x); };

    std::transform(begin(nums), end(nums), begin(nums), grow);
}
</code>```

Here's the code.

```<code>#include <iostream>
#include <chrono>
#include <random>
#include <array>
#include <vector>
#include <algorithm>

auto constexpr test_size = std::size_t(100'000'000);
using namespace std::literals;

void approach1(std::vector<int> &nums) {
    for (unsigned int i = 0; i < nums.size(); ++i) {
        nums[i] *= nums[i];

        if (nums[i] < 10) {
            nums[i] = 0;
        }
    }
}

void approach2(std::vector<int> &nums) {
    for (unsigned int i = 0; i < nums.size(); ++i) {
        nums[i] *= nums[i];
    }

    for (unsigned int i = 0; i < nums.size(); ++i) {
        if (nums[i] < 10) {
            nums[i] = 0;
        }
    }
}

void approach3(std::vector<int> &nums) {
    std::vector<int> flags;
    flags.resize(nums.size());

    for (unsigned int i = 0; i < nums.size(); ++i) {
        nums[i] *= nums[i];
        flags[i] = nums[i] < 10;
    }

    for (unsigned int i = 0; i < flags.size(); ++i) {
        nums[i] = (!flags[i]) * nums[i]; //!flags[i] is 0 if nums[i] < 10
    }
}

void approach4(std::vector<int> &nums) {
    for (std::size_t i = 0; i < nums.size(); ++i) {
        nums[i] *= (nums[i] <= 3 ? 0 : nums[i]);
    }
}

auto test = [](auto &&name, auto &&approach, auto &&data) {
    std::cout << "starting test: " << name << std::endl;
    auto my_data = std::vector<int>(data.begin(), data.end());
    auto now = std::chrono::high_resolution_clock::now();
    approach(my_data);
    auto then = std::chrono::high_resolution_clock::now();
    auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(then - now);
    std::cout << "test took: " << diff.count() << "ms" << std::endl;
};

std::array<int, test_size> test_data;

int main() {
    std::random_device rd;
    std::default_random_engine eng(rd());
    std::uniform_int_distribution<> dist(0, 100);

    std::generate(test_data.begin(), test_data.end(), [&]() { return dist(eng); });
    std::cout << "checkpoint" << std::endl;

    test("approach1", approach1, test_data);
    test("approach2", approach2, test_data);
    test("approach3", approach3, test_data);
    test("Bathsheba's idea", approach4, test_data);
}
</code>```

Body:
I have to process each element of an array the same way once and have to modify each by an unpredictable pattern afterwards aswell.

Is there any difference in performance between these snippets and why, if so?

std::vector<int> nums;
//fill nums array

for(unsigned int i = 0; i < nums.size(); ++i){
    nums[i] *= nums[i];

    if(nums[i] < 10){
        nums[i] = 0;
    }
}

std::vector<int> nums;
//fill nums array

for(unsigned int i = 0; i < nums.size(); ++i){
    nums[i] *= nums[i];
}

for(unsigned int i = 0; i < nums.size(); ++i){
    if(nums[i] < 10){
        nums[i] = 0;
    }
}

Would a different approach like this improve anything?

std::vector<int> nums;
//fill nums array

std::vector<int> flags;
flags.resize(nums.size());

for(unsigned int i = 0; i < nums.size(); ++i){
    nums[i] *= nums[i];
    flags[i] = nums[i] < 10;
}

for(unsigned int i = 0; i < flags.size(); ++i){
   nums[i] = (!flags[i]) * nums[i]; //!flags[i] is 0 if nums[i] < 10
}

Body:
Test results on my machine (100 million ints in the array):

checkpoint
starting test: approach1
test took: 84ms
starting test: approach2
test took: 190ms
starting test: approach3
test took: 529ms
starting test: Bathsheba's idea
test took: 61ms

Incidentally, writing idiomatic code is often the most efficient of all. clang, gcc et. al. optimisers are fantastic:

void approach5(std::vector<int> &nums) {

    auto filter = [](auto x) { return (x < 10) ? 0 : x; };

    auto grow = [filter](auto x) { return filter(x * x); };

    std::transform(begin(nums), end(nums), begin(nums), grow);
}

Here's the code.

#include <iostream>
#include <chrono>
#include <random>
#include <array>
#include <vector>
#include <algorithm>

auto constexpr test_size = std::size_t(100'000'000);
using namespace std::literals;

void approach1(std::vector<int> &nums) {
    for (unsigned int i = 0; i < nums.size(); ++i) {
        nums[i] *= nums[i];

        if (nums[i] < 10) {
            nums[i] = 0;
        }
    }
}

void approach2(std::vector<int> &nums) {
    for (unsigned int i = 0; i < nums.size(); ++i) {
        nums[i] *= nums[i];
    }

    for (unsigned int i = 0; i < nums.size(); ++i) {
        if (nums[i] < 10) {
            nums[i] = 0;
        }
    }
}

void approach3(std::vector<int> &nums) {
    std::vector<int> flags;
    flags.resize(nums.size());

    for (unsigned int i = 0; i < nums.size(); ++i) {
        nums[i] *= nums[i];
        flags[i] = nums[i] < 10;
    }

    for (unsigned int i = 0; i < flags.size(); ++i) {
        nums[i] = (!flags[i]) * nums[i]; //!flags[i] is 0 if nums[i] < 10
    }
}

void approach4(std::vector<int> &nums) {
    for (std::size_t i = 0; i < nums.size(); ++i) {
        nums[i] *= (nums[i] <= 3 ? 0 : nums[i]);
    }
}

auto test = [](auto &&name, auto &&approach, auto &&data) {
    std::cout << "starting test: " << name << std::endl;
    auto my_data = std::vector<int>(data.begin(), data.end());
    auto now = std::chrono::high_resolution_clock::now();
    approach(my_data);
    auto then = std::chrono::high_resolution_clock::now();
    auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(then - now);
    std::cout << "test took: " << diff.count() << "ms" << std::endl;
};

std::array<int, test_size> test_data;

int main() {
    std::random_device rd;
    std::default_random_engine eng(rd());
    std::uniform_int_distribution<> dist(0, 100);

    std::generate(test_data.begin(), test_data.end(), [&]() { return dist(eng); });
    std::cout << "checkpoint" << std::endl;

    test("approach1", approach1, test_data);
    test("approach2", approach2, test_data);
    test("approach3", approach3, test_data);
    test("Bathsheba's idea", approach4, test_data);
}


问:
How are values assigned to non-class types?
If non-class types, like pointers and int, do not have member functions like constructors, how are values assigned to them?
For instance:

```<code>int x = 1;
int p = x;
p = 2;
int a = int();
</code>```

When I did int p = x; would that simply perform a shallow copy, like an implicit copy constructor? Same goes for all other implicit member functions, since non-class types tend to work in the same way as with class types in those situations.

Also, when you have a class, that class would probably have an object that stores a certain value(if the class is supposed to represent a value), but is there some sort of buffer for these non-class types? Otherwise, how can a value be copied from one to another?

答:
In C++ primitive types, (bool, char, short, int, long, double, float) are values that can be directly stored in CPU registers.

When the CPU gets to the declaration of your variable, it acquires RAM to store the value. In C++11 and later the additional step of value-initialization is taken.

To break down your code:

int x = 1;

This will acquire enough RAM for an int (usually 4 bytes), associates the symbol x with the address of the acquired RAM and assigns the RAM at that address the value 1.

int p = x;

This will acquire enough RAM for another int, associate it with the symbol p, and copy the value stored at the address associated with the symbol x into the RAM at the new address.

p = 2;

This goes to the RAM address associated with the symbol p, and overwrites the value there with 2.

int a = int();

This acquires an another int-sized piece of RAM, associates the address of the RAM with a, calls the no-argument int conversion function, and assigns the return value (0) to the RAM at the address of a.

Enter pointers

To get deeper into the underlying mechanics, C++ allocates memory for variables in two locations in RAM: the stack and the heap.
When you declare a variable with the syntax int g;, the associated ram is a stack address, and is acquired for use when the scope (a section of code delimited by {}) the variable is declared in is entered, and remains allocated until the scope is exited, at which point it is deallocated.

Pointers operate similarly:
If you declare

int* k;

the space for a pointer is allocated on the stack, and the value at the address is either garbage, or with C++11 value-initialized to null. To assign an object to a pointer, you use the new operator,

k = new int(2)

which allocates enough heap RAM to hold an int, initializes that RAM with the value 2, and assigns the address of the allocated RAM as a value at the stack address of k.

Body:
If non-class types, like pointers and int, do not have member functions like constructors, how are values assigned to them?
For instance:

int x = 1;
int p = x;
p = 2;
int a = int();

When I did int p = x; would that simply perform a shallow copy, like an implicit copy constructor? Same goes for all other implicit member functions, since non-class types tend to work in the same way as with class types in those situations.

Also, when you have a class, that class would probably have an object that stores a certain value(if the class is supposed to represent a value), but is there some sort of buffer for these non-class types? Otherwise, how can a value be copied from one to another?


问:
fatal: pathspec 'https://user:pass@bitbucket.org/user/my_repo.git' did not match any files
I have a relatively complex git statement which reads as:

```<code>git -C /Users/user_name/s/f/f_start/ add https://user:pass@bitbucket.org/user/my_repo.git -A && git -C /Users/user_name/s/f/f_start/ commit  https://user:pass@bitbucket.org/user/my_repo.git -m "update 20170707"
</code>```

Which yields the following error:

```<code>fatal: pathspec 'https://user:pass@bitbucket.org/user/my_repo.git' did not match any files
</code>```

Now, if I locally cd to that path & git status I get:

```<code>On branch master
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   data_1.p

no changes added to commit (use "git add" and/or "git commit -a")
</code>```

So, it is a git repo.

Now, if I run:

```<code>git commit data_1.p -m "update"
</code>```

I get:

```<code>[master 377c61b] update
 1 file changed, 0 insertions(+), 0 deletions(-)
</code>```

and git push yields:

```<code>Counting objects: 3, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 1.12 KiB | 0 bytes/s, done.
Total 3 (delta 2), reused 0 (delta 0)
To https://user:pass@bitbucket.org/user/my_repo.git
   74ad924..377c61b  master -> master
</code>```

Yet, if I simplify my git command and run:

```<code>git -C /Users/user_name/s/f/f_start/ commit  https://user:pass@bitbucket.org/user/my_repo.git -m " 20170707"
</code>```

I get:

```<code>error: pathspec 'https://user:pass@bitbucket.org/user/my_repo.git' did not match any file(s) known to git.
</code>```

Could anyone help to diagnose what exactly I am doing wrong here?

I am providing username and password because this is distributed code.

答:
You do not need to give the remote repository URL in each command.

git add command only accepts pathspec as parameter, so your command is trying to add a file https://user:pass@bitbucket.org/user/my_repo.git, which does not exists!

Just remove the URL from you commands:

```<code>git -C /Users/user_name/s/f/f_start/ add -A
git -C /Users/user_name/s/f/f_start/ commit -m "update 20170707"

# Then simply publish
git -C /Users/user_name/s/f/f_start/ push
</code>```

The only git commands to set/change remote repository URL is git remote:

```<code>git remote origin --set-url https://user:pass@bitbucket.org/user/my_repo.git
git remote -v
</code>```

Body:
I have a relatively complex git statement which reads as:

git -C /Users/user_name/s/f/f_start/ add https://user:pass@bitbucket.org/user/my_repo.git -A && git -C /Users/user_name/s/f/f_start/ commit  https://user:pass@bitbucket.org/user/my_repo.git -m "update 20170707"

Which yields the following error:

fatal: pathspec 'https://user:pass@bitbucket.org/user/my_repo.git' did not match any files

Now, if I locally cd to that path & git status I get:

On branch master
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   data_1.p

no changes added to commit (use "git add" and/or "git commit -a")

So, it is a git repo.

Now, if I run:

git commit data_1.p -m "update"

I get:

[master 377c61b] update
 1 file changed, 0 insertions(+), 0 deletions(-)

and git push yields:

Counting objects: 3, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 1.12 KiB | 0 bytes/s, done.
Total 3 (delta 2), reused 0 (delta 0)
To https://user:pass@bitbucket.org/user/my_repo.git
   74ad924..377c61b  master -> master

Yet, if I simplify my git command and run:

git -C /Users/user_name/s/f/f_start/ commit  https://user:pass@bitbucket.org/user/my_repo.git -m " 20170707"

I get:

error: pathspec 'https://user:pass@bitbucket.org/user/my_repo.git' did not match any file(s) known to git.

Could anyone help to diagnose what exactly I am doing wrong here?

I am providing username and password because this is distributed code.

Body:
You do not need to give the remote repository URL in each command.

git add command only accepts pathspec as parameter, so your command is trying to add a file https://user:pass@bitbucket.org/user/my_repo.git, which does not exists!

Just remove the URL from you commands:

git -C /Users/user_name/s/f/f_start/ add -A
git -C /Users/user_name/s/f/f_start/ commit -m "update 20170707"

# Then simply publish
git -C /Users/user_name/s/f/f_start/ push

The only git commands to set/change remote repository URL is git remote:

git remote origin --set-url https://user:pass@bitbucket.org/user/my_repo.git
git remote -v


问:
Service cannot be started Access Denied

Service cannot be started. System.ServiceModel.CommunicationException:
  The service endpoint failed to listen on the URI
  'net.tcp://ssis01:9176/SSISService_v2_0/' because access was denied.
  Verify that the current user is granted access in the appropriate
  allowAccounts section of SMSvcHost.exe.config. --->
  System.ComponentModel.Win32Exception: Access is denied    at
  System.ServiceModel.Activation.SharedMemory.Read(String name, String&
  content)    at
  System.ServiceModel.Channels.SharedConnectionListener.SharedListenerProxy.ReadEndpoint(String
  sharedMemoryName, String& listenerEndpoint)    --- End of inner
  exception stack trace ---    at
  System.ServiceModel.Channels.SharedConnectionListener.SharedListenerProxy.ReadEndpoint(String
  sharedMemoryName, String& listenerEndpoint)    at
  System.ServiceModel.Channels.SharedConnectionListener.SharedListenerProxy.HandleServiceStart(Boolean
  isReconnecting)    at
  System.ServiceModel.Channels.SharedConnectionListener.SharedListenerProxy.Open(Boolean
  isReconnecting)    at System.Ser.

What i have tried
I am not a administrator maybe that is the issue , for that

1) added my user SID in SMSvcHost.exe.config in allowAccounts section .. Then restarted the service first NETSharing and then the SSISService

2) when starting ssis Service it throws an error "Service on local computer started and stopped. Some Services stops automatically if they are not in use by others services and programs. Above ERROR msg are from the Logs

Here is the config file for SMSvcHost.exe.config

```<code><?xml version="1.0" encoding="utf-8"?>
<!-- The configuration file for SMSvcHost.exe -->
<configuration>
    <runtime>
        <gcConcurrent enabled="false" />
    </runtime>
    <system.serviceModel>
        <!-- SMSvcHost ETW traces are redirected by default to an etwProviderId different from WCF's default.
             To trace to the default provider, remove the etwProviderId attribute below. -->
        <diagnostics performanceCounters="Off" etwProviderId="{f18839f5-27ff-4e66-bd2d-639b768cf18b}"/>
    </system.serviceModel>
    <system.serviceModel.activation>
        <net.tcp listenBacklog="10" maxPendingConnections="100" maxPendingAccepts="2" receiveTimeout="00:00:10" teredoEnabled="false">
        <allowAccounts>
            <add securityIdentifier="S-1-5-21-873128402-3342024598-2051005476-53521"/>
        </allowAccounts>
        </net.tcp>
    </system.serviceModel.activation>
</configuration>
</code>```

答:
Took me a while to fix this issue

Step1. In the Run command window regedit.exe

Step 2 : go to the Location ( path is at the bottom of screenshot) ,  to get the SID for the Adminstrator.

Step3: Copy the SID for the Admin , here you will see the SID for all the user that is logged in. But you only want it for ADMIN, how to know it is admin ?
     Right Click on service and go to Properties and click Log on Tab.
     If you see the screen shot 1 you will see the ProfileImagePath has the same name DataSVC.

Step 3: Main part Config changes
add this line of code with the ADMIN SID in SMSvcHost.exe.config .

```<code><system.serviceModel.activation>
        <net.tcp listenBacklog="10" maxPendingConnections="100" maxPendingAccepts="2" receiveTimeout="00:00:10" teredoEnabled="false">
        <allowAccounts>
            <add securityIdentifier="**ADMIN SID ID HERE** "/>
        </allowAccounts>
        </net.tcp>
    </system.serviceModel.activation>
</code>```

Step 5 : Restart NETTCP sharing first and then the other service. should fix the issue for this ERROR. thanks everyone

Title: Service cannot be started Access Denied

Body:
Service cannot be started. System.ServiceModel.CommunicationException:
  The service endpoint failed to listen on the URI
  'net.tcp://ssis01:9176/SSISService_v2_0/' because access was denied.
  Verify that the current user is granted access in the appropriate
  allowAccounts section of SMSvcHost.exe.config. --->
  System.ComponentModel.Win32Exception: Access is denied    at
  System.ServiceModel.Activation.SharedMemory.Read(String name, String&
  content)    at
  System.ServiceModel.Channels.SharedConnectionListener.SharedListenerProxy.ReadEndpoint(String
  sharedMemoryName, String& listenerEndpoint)    --- End of inner
  exception stack trace ---    at
  System.ServiceModel.Channels.SharedConnectionListener.SharedListenerProxy.ReadEndpoint(String
  sharedMemoryName, String& listenerEndpoint)    at
  System.ServiceModel.Channels.SharedConnectionListener.SharedListenerProxy.HandleServiceStart(Boolean
  isReconnecting)    at
  System.ServiceModel.Channels.SharedConnectionListener.SharedListenerProxy.Open(Boolean
  isReconnecting)    at System.Ser.

What i have tried
I am not a administrator maybe that is the issue , for that

1) added my user SID in SMSvcHost.exe.config in allowAccounts section .. Then restarted the service first NETSharing and then the SSISService

2) when starting ssis Service it throws an error "Service on local computer started and stopped. Some Services stops automatically if they are not in use by others services and programs. Above ERROR msg are from the Logs

Here is the config file for SMSvcHost.exe.config

<?xml version="1.0" encoding="utf-8"?>

<configuration>
    <runtime>
        <gcConcurrent enabled="false" />
    </runtime>
    <system.serviceModel>

        <diagnostics performanceCounters="Off" etwProviderId="{f18839f5-27ff-4e66-bd2d-639b768cf18b}"/>
    </system.serviceModel>
    <system.serviceModel.activation>
        <net.tcp listenBacklog="10" maxPendingConnections="100" maxPendingAccepts="2" receiveTimeout="00:00:10" teredoEnabled="false">
        <allowAccounts>
            <add securityIdentifier="S-1-5-21-873128402-3342024598-2051005476-53521"/>
        </allowAccounts>
        </net.tcp>
    </system.serviceModel.activation>
</configuration>

Body:
Took me a while to fix this issue

Step1. In the Run command window regedit.exe

Step 2 : go to the Location ( path is at the bottom of screenshot) ,  to get the SID for the Adminstrator.

Step3: Copy the SID for the Admin , here you will see the SID for all the user that is logged in. But you only want it for ADMIN, how to know it is admin ?
     Right Click on service and go to Properties and click Log on Tab.
     If you see the screen shot 1 you will see the ProfileImagePath has the same name DataSVC.

Step 3: Main part Config changes
add this line of code with the ADMIN SID in SMSvcHost.exe.config .

<system.serviceModel.activation>
        <net.tcp listenBacklog="10" maxPendingConnections="100" maxPendingAccepts="2" receiveTimeout="00:00:10" teredoEnabled="false">
        <allowAccounts>
            <add securityIdentifier="**ADMIN SID ID HERE** "/>
        </allowAccounts>
        </net.tcp>
    </system.serviceModel.activation>

Step 5 : Restart NETTCP sharing first and then the other service. should fix the issue for this ERROR. thanks everyone


问:
How do you synchronously resolve a chain of es6 promises?
I have a function from a library that returns a promise. I need to run this function multiple times, but each iteration must wait until the previous task is done.

My assumption was that I could do this:

```<code>promiseReturner(1)
  .then(promiseReturner(2)
  .then(promiseReturner(3)
  .then(...)
</code>```

Which could be simplified using a loop:

```<code>var p = Promise.resolve();
for (var i=1; i<=10; i++) {
  p = p.then(promiseReturner(i));
}
</code>```

However, when I do this each promise in the chain is executed at the same time, instead of one after the other as .then() seems to imply. Clearly I'm missing something fundamental about promises -- but after reading several tutorials and blog posts I'm still lost.

Here's a codepen I wrote up to demonstrate my attempt.

答:
You can run your code via nsynjs, it will pause execution on each function that returns promise, and will wait until promise is resolved:

var promiseReturner = function(i) {
    return new Promise(function(resolve, reject) {
        setTimeout(function(){
            resolve("result is "+i)
        }, 1000);
    });
};

function synchronousCode() {
    for (var i=1; i<=10; i++) {
        var p=promiseReturner(i); // nsynjs will pause here until promise is resolved
        console.log(p.data); // `data` will contain result of the promise
    }
};

nsynjs.run(synchronousCode, null, function(){
 console.log("finish");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://rawgit.com/amaksr/nsynjs/master/nsynjs.js"></script></code>```

Body:
I have a function from a library that returns a promise. I need to run this function multiple times, but each iteration must wait until the previous task is done.

My assumption was that I could do this:

promiseReturner(1)
  .then(promiseReturner(2)
  .then(promiseReturner(3)
  .then(...)

Which could be simplified using a loop:

var p = Promise.resolve();
for (var i=1; i<=10; i++) {
  p = p.then(promiseReturner(i));
}

However, when I do this each promise in the chain is executed at the same time, instead of one after the other as .then() seems to imply. Clearly I'm missing something fundamental about promises -- but after reading several tutorials and blog posts I'm still lost.

Here's a codepen I wrote up to demonstrate my attempt.

Body:
You can run your code via nsynjs, it will pause execution on each function that returns promise, and will wait until promise is resolved:

var promiseReturner = function(i) {
    return new Promise(function(resolve, reject) {
        setTimeout(function(){
            resolve("result is "+i)
        }, 1000);
    });
};

function synchronousCode() {
    for (var i=1; i<=10; i++) {
        var p=promiseReturner(i); // nsynjs will pause here until promise is resolved
        console.log(p.data); // `data` will contain result of the promise
    }
};

nsynjs.run(synchronousCode, null, function(){
 console.log("finish");
});

<script src="https://rawgit.com/amaksr/nsynjs/master/nsynjs.js"></script>


问:
php search script
i need some help to search property searching like on

Zameen

what i am unaware of is that how would i send the query to the next page? eg my query is like this

```<code>$query = select * from xyz where city='a' and location='b' and price between 'c' and 'd' and area between 'e' and 'f' and bedrooms='g' and addedwithin 'h';
</code>```

considering this query on the basis of form on the above mentioned website, what should be the scenario for searching property listings.

Also how should i get this query again when i use paging with this page. should it be like this

```<code><a href="<?php echo $_SERVER['PHP_SELF'] . '?q=' . $query; ?>" > nextpage </a>
</code>```

or is there any other simpler solution?

Thanks

答:
You could do a few things. One solution would be to pass all the parameters you need in the query string along with a page number, and then do paging in your SQL. This might be fine for smaller things but issues might arise if something was inserted into your table after the search, so the search results can increase/decrease and seem odd to the user. There is also a problem if a spider started crawling your site by increasing the page parameter - it would be very easy to overload your database.

Another solution, which would be my favourite, would be to save all your results from the initial search into a cache solution using some unique ID as the key. Then your paging can be passed the ID of cache item and page number and you can read off from the array of results the page that you want.

Title: php search script

Body:
i need some help to search property searching like on

Zameen

what i am unaware of is that how would i send the query to the next page? eg my query is like this

$query = select * from xyz where city='a' and location='b' and price between 'c' and 'd' and area between 'e' and 'f' and bedrooms='g' and addedwithin 'h';

considering this query on the basis of form on the above mentioned website, what should be the scenario for searching property listings.

Also how should i get this query again when i use paging with this page. should it be like this

<a href="<?php echo $_SERVER['PHP_SELF'] . '?q=' . $query; ?>" > nextpage

or is there any other simpler solution?

Thanks


问:
Comparing two integer arrays without sorting in java
I am working on a piece of code which is used to create a multiple choice question exam. The purpose of the code I am working on is to enable a question to have multiple correct answers.

The way a user inputs an answer is choosing an integer corresponding to the choice they would like to submit.

The actual correct integer(s) is/are stored in an array called "correctedIndex" and the user stored responses are stored in an array called "response".

The error I am having is checking to see whether the user's answers are correct, regardless of the order he or she submitted them in. My current idea was to created a nested for loop to cycle through both arrays and check for matches, and if the matches equal to the amount of correct answers, then the student would be correct. This does not work when I run it.

Everything before that point works properly, I have made sure a user cannot enter invalid responses, duplicate responses, and automatically mark them incorrect if they submit more responses than there are correct responses.

Here is the part of the code which does not work:

```<code>for(int i = 0; i < correctIndex.length; i++){
            for(int j = 0; j < response.length; j++){
                if(correctIndex[i] == response[j]){
                    matches++;
                }
            }
        }
        if(matches == correctIndex.length){
            System.out.println("Correct, answer was: ");
            for(int i = 0; i < correctIndex.length; i++){
                System.out.println((correctIndex[i] + 1) + ": " + choices[correctIndex[i]]);
            }
        }
        else{
            System.out.println("Your answer: ");
            for(int i = 0; i < response.length; i++){
                System.out.println(response[i] + ": " + choices[response[i]-1]);
            }
            System.out.println();
            System.out.println();
            System.out.println("Is incorrect, the correct answer is: ");
            for(int i = 0; i < correctIndex.length; i++){
                System.out.println((correctIndex[i] + 1) +": " + choices[correctIndex[i]]);
            }
        }
</code>```

Here is an example of an output I get:

```<code>Please input the correct choice using its corresponding number

Which of these are visibilities?

1: Public
2: Private
3: Void
4: Protected
5: Int
6: String
7: Package-Protected

Please enter how many answers you would like to select:
4
Enter your number for answer 1
1
Enter your number for answer 2
2
Enter your number for answer 3
4
Enter your number for answer 4
7
</code>```

And here are the results after using the result method (The one in question):

```<code>Question:
Which of these are visibilities?

Choices:
1: Public
2: Private
3: Void
4: Protected
5: Int
6: String
7: Package-Protected

Your answer:
1: Public
2: Private
4: Protected
7: Package-Protected

Is incorrect, the correct answer is:
1: Public
2: Private
4: Protected
7: Package-Protected
</code>```

答:
Something like this should do it:    </p>

```<code>for(int i = 0;i<correctIndex.length;i++){
  int answer = correctIndex[i];
  boolean contained = false;
  for(int i = 0;i<response.length;i++){
    if(response[i]==answer){
      contained =true;
    }
  }
  if(contained = false){
    return false; // response is incorrect, add code to handle
  }
}
return true; // if it makes it through, response is correct
</code>```

Body:
I am working on a piece of code which is used to create a multiple choice question exam. The purpose of the code I am working on is to enable a question to have multiple correct answers.

The way a user inputs an answer is choosing an integer corresponding to the choice they would like to submit.

The actual correct integer(s) is/are stored in an array called "correctedIndex" and the user stored responses are stored in an array called "response".

The error I am having is checking to see whether the user's answers are correct, regardless of the order he or she submitted them in. My current idea was to created a nested for loop to cycle through both arrays and check for matches, and if the matches equal to the amount of correct answers, then the student would be correct. This does not work when I run it.

Everything before that point works properly, I have made sure a user cannot enter invalid responses, duplicate responses, and automatically mark them incorrect if they submit more responses than there are correct responses.

Here is the part of the code which does not work:

for(int i = 0; i < correctIndex.length; i++){
            for(int j = 0; j < response.length; j++){
                if(correctIndex[i] == response[j]){
                    matches++;
                }
            }
        }
        if(matches == correctIndex.length){
            System.out.println("Correct, answer was: ");
            for(int i = 0; i < correctIndex.length; i++){
                System.out.println((correctIndex[i] + 1) + ": " + choices[correctIndex[i]]);
            }
        }
        else{
            System.out.println("Your answer: ");
            for(int i = 0; i < response.length; i++){
                System.out.println(response[i] + ": " + choices[response[i]-1]);
            }
            System.out.println();
            System.out.println();
            System.out.println("Is incorrect, the correct answer is: ");
            for(int i = 0; i < correctIndex.length; i++){
                System.out.println((correctIndex[i] + 1) +": " + choices[correctIndex[i]]);
            }
        }

Here is an example of an output I get:

Please input the correct choice using its corresponding number

Which of these are visibilities?

1: Public
2: Private
3: Void
4: Protected
5: Int
6: String
7: Package-Protected

Please enter how many answers you would like to select:
4
Enter your number for answer 1
1
Enter your number for answer 2
2
Enter your number for answer 3
4
Enter your number for answer 4
7

And here are the results after using the result method (The one in question):

Question:
Which of these are visibilities?

Choices:
1: Public
2: Private
3: Void
4: Protected
5: Int
6: String
7: Package-Protected

Your answer:
1: Public
2: Private
4: Protected
7: Package-Protected

Is incorrect, the correct answer is:
1: Public
2: Private
4: Protected
7: Package-Protected

Body:
Something like this should do it:

for(int i = 0;i<correctIndex.length;i++){
  int answer = correctIndex[i];
  boolean contained = false;
  for(int i = 0;i<response.length;i++){
    if(response[i]==answer){
      contained =true;
    }
  }
  if(contained = false){
    return false; // response is incorrect, add code to handle
  }
}
return true; // if it makes it through, response is correct


问:
Python: How to send file to hipchat?
How can I send a file from my local computer to hipchat using a python API? I am currently using Hypchat but it is not well documented.

Here is my code so far:

```<code>import hypchat

hc = hypchat.HypChat("myKey")

room = hc.get_room('bigRoom')
</code>```

I'm not sure how to proceed. I tried other methods such as this one but I keep getting the error:

```<code>[ERROR] HipChat file failed: '405 Client Error: Method Not Allowed for url: https://api.hipchat.com/v2/room/bigRoom/share/file'
</code>```

答:
This code allows me to send any file to a hipchat room:

```<code># do this:
#     pip install requests_toolbelt

from os                import path
from sys               import exit, stderr
from requests          import post
from requests_toolbelt import MultipartEncoder

class MultipartRelatedEncoder(MultipartEncoder):
    """A multipart/related encoder"""
    @property
    def content_type(self):
        return str('multipart/related; boundary={0}'.format(self.boundary_value))

    def _iter_fields(self):
        # change content-disposition from form-data to attachment
        for field in super(MultipartRelatedEncoder, self)._iter_fields():
            content_type = field.headers['Content-Type']
            field.make_multipart(content_disposition = 'attachment',
                                 content_type        = content_type)
            yield field

def hipchat_file(token, room, filepath, host='api.hipchat.com'):

    if not path.isfile(filepath):
        raise ValueError("File '{0}' does not exist".format(filepath))

    url                      = "https://{0}/v2/room/{1}/share/file".format(host, room)
    headers                  = {'Content-type': 'multipart/related; boundary=boundary123456'}
    headers['Authorization'] = "Bearer " + token

    m = MultipartRelatedEncoder(fields={'metadata' : (None, '', 'application/json; charset=UTF-8'),
                                        'file'     : (path.basename(filepath), open(filepath, 'rb'), 'text/csv')})

    headers['Content-type'] = m.content_type

    r = post(url, data=m, headers=headers)

if __name__ == '__main__:

    my_token = <my token>
    my_room  = <room name>
    my_file  = <filepath>

    try:
        hipchat_file(my_token, my_room, my_file)
    except Exception as e:
        msg = "[ERROR] HipChat file failed: '{0}'".format(e)
        print(msg, file=stderr)
        exit(1)
</code>```

Shout out to @Martijn Pieters

Title: Python: How to send file to hipchat?

Body:
How can I send a file from my local computer to hipchat using a python API? I am currently using Hypchat but it is not well documented.

Here is my code so far:

import hypchat

hc = hypchat.HypChat("myKey")

room = hc.get_room('bigRoom')

I'm not sure how to proceed. I tried other methods such as this one but I keep getting the error:

[ERROR] HipChat file failed: '405 Client Error: Method Not Allowed for url: https://api.hipchat.com/v2/room/bigRoom/share/file'

Body:
This code allows me to send any file to a hipchat room:

# do this:
#     pip install requests_toolbelt

from os                import path
from sys               import exit, stderr
from requests          import post
from requests_toolbelt import MultipartEncoder

class MultipartRelatedEncoder(MultipartEncoder):
    """A multipart/related encoder"""
    @property
    def content_type(self):
        return str('multipart/related; boundary={0}'.format(self.boundary_value))

    def _iter_fields(self):
        # change content-disposition from form-data to attachment
        for field in super(MultipartRelatedEncoder, self)._iter_fields():
            content_type = field.headers['Content-Type']
            field.make_multipart(content_disposition = 'attachment',
                                 content_type        = content_type)
            yield field

def hipchat_file(token, room, filepath, host='api.hipchat.com'):

    if not path.isfile(filepath):
        raise ValueError("File '{0}' does not exist".format(filepath))

    url                      = "https://{0}/v2/room/{1}/share/file".format(host, room)
    headers                  = {'Content-type': 'multipart/related; boundary=boundary123456'}
    headers['Authorization'] = "Bearer " + token

    m = MultipartRelatedEncoder(fields={'metadata' : (None, '', 'application/json; charset=UTF-8'),
                                        'file'     : (path.basename(filepath), open(filepath, 'rb'), 'text/csv')})

    headers['Content-type'] = m.content_type

    r = post(url, data=m, headers=headers)

if __name__ == '__main__:

    my_token = <my token>
    my_room  = <room name>
    my_file  = <filepath>

    try:
        hipchat_file(my_token, my_room, my_file)
    except Exception as e:
        msg = "[ERROR] HipChat file failed: '{0}'".format(e)
        print(msg, file=stderr)
        exit(1)

Shout out to @Martijn Pieters


问:
Searching a tree using LINQ
I have a tree created from this class.

```<code>class Node
{
    public string Key { get; }
    public List<Node> Children { get; }
}
</code>```

I want to search in all children and all their children to get the ones matching a condition:

```<code>node.Key == SomeSpecialKey
</code>```

How can I implement it?

答:
I use the following implementations for enumerating Tree items

```<code>    public static IEnumerable<Node> DepthFirstUnfold(this Node root) =>
        ObjectAsEnumerable(root).Concat(root.Children.SelectMany(DepthFirstUnfold));

    public static IEnumerable<Node> BreadthFirstUnfold(this Node root) {
        var queue = new Queue<IEnumerable<Node>>();
        queue.Enqueue(ObjectAsEnumerable(root));

        while (queue.Count != 0)
            foreach (var node in queue.Dequeue()) {
                yield return node;
                queue.Enqueue(node.Children);
            }
    }

    private static IEnumerable<T> ObjectAsEnumerable<T>(T obj) {
        yield return obj;
    }
</code>```

BreadthFirstUnfold in implementation above uses queue of node sequences instead of nodes queue. This is not classic BFS algorithm way.

Title: Searching a tree using LINQ

Body:
I have a tree created from this class.

class Node
{
    public string Key { get; }
    public List<Node> Children { get; }
}

I want to search in all children and all their children to get the ones matching a condition:

node.Key == SomeSpecialKey

How can I implement it?

Body:
I use the following implementations for enumerating Tree items

    public static IEnumerable<Node> DepthFirstUnfold(this Node root) =>
        ObjectAsEnumerable(root).Concat(root.Children.SelectMany(DepthFirstUnfold));

    public static IEnumerable<Node> BreadthFirstUnfold(this Node root) {
        var queue = new Queue<IEnumerable<Node>>();
        queue.Enqueue(ObjectAsEnumerable(root));

        while (queue.Count != 0)
            foreach (var node in queue.Dequeue()) {
                yield return node;
                queue.Enqueue(node.Children);
            }
    }

    private static IEnumerable<T> ObjectAsEnumerable<T>(T obj) {
        yield return obj;
    }

BreadthFirstUnfold in implementation above uses queue of node sequences instead of nodes queue. This is not classic BFS algorithm way.


问:
Using Azure AD B2C and MSAL to authenticate a windows service
Is it possible to use MSAL to allow a windows service to access a web api protected by Azure AD B2C?  If not, what is the best way to allow a autonomous service to access an API protected by B2C.</p>

答:
This scenario should be addressed with the Client Credentials OAuth flow.
This is possible in Azure AD B2C, however, the experience isn't ideal.

To do achieve this, use "App Registration" blade in the Azure Portal to register a apps that define application permissions and then register apps that use client credentials to request these. You would effectively be using the same mechanism that you use in regular Azure AD, see Azure AD's "Daemon or Server Application to Web API" documentation

Important note: Make sure you are not using the Azure AD B2C blades for this.

You can support the ask for a first class experience by voting for this entry in the Azure AD B2C feedback forum: Support OAuth 2.0 Client Credential Flow


问:
Weird error when trying to install a module using cpan on a RedHat
When I am trying to install any module on a RedHat 7.3 using cpan, I am getting this weird message - "make: execvp: true: Permission denied":

```<code>sudo cpan
cpan[1]> install Log::Log4perl
...
(tests run ok)
...
Running make install
make: execvp: true: Permission denied
make: *** [blibdirs] Error 127
  MSCHILLI/Log-Log4perl-1.49.tar.gz
  sudo /bin/make install  -- NOT OK
Failed during this command:
 MSCHILLI/Log-Log4perl-1.49.tar.gz            : install NO
</code>```

Then, if I navigate to the cpans build_dir (from MyConfig.pm), find the folder with this module, and run make test; sudo make install there - everything runs fine.

What is wrong with cpan there? How this could be fixed?

答: make: execvp: foo: Permission denied happens when foo is some program that does not have execute permission. Find the true program in your $PATH (typically /bin/true or /usr/bin/true, but maybe there's another one if you have an idiosyncratic $PATH) and make sure you have execute permission for it.

Body:
When I am trying to install any module on a RedHat 7.3 using cpan, I am getting this weird message - "make: execvp: true: Permission denied":

sudo cpan
cpan[1]> install Log::Log4perl
...
(tests run ok)
...
Running make install
make: execvp: true: Permission denied
make: *** [blibdirs] Error 127
  MSCHILLI/Log-Log4perl-1.49.tar.gz
  sudo /bin/make install  -- NOT OK
Failed during this command:
 MSCHILLI/Log-Log4perl-1.49.tar.gz            : install NO

Then, if I navigate to the cpans build_dir (from MyConfig.pm), find the folder with this module, and run make test; sudo make install there - everything runs fine.

What is wrong with cpan there? How this could be fixed?


问:
tomcat and grpc both upgrade to ssl
i have a web application which deploy on tomcat 8 and this app also provide grpc service to other module, now i want to make the http service update to https and also the grpc should use ssl, but i have some issue on this job, the tcnative-1.dll is supported by tomcat to https, but grpc not use this, i used netty-tcnatice but it does't work in my tomcat, seems the two things can't work together,if i use tomcat's dll the grpc will pop up an error for not find the openssl install lib error:Jetty ALPN/NPN has not been properly configured.
how could i do? please give some help, thanks.

答: The Tomcat incompatibility is fixed with netty-tcnative 2. At the moment, you should use grpc-java 1.4.0 which is compatible with netty-tcnative v2.0.5.</p>

Title: tomcat and grpc both upgrade to ssl


问:
How to write a CSV file so it is read by csv.DictReader() as string/int?
I use pandas.DataFrame.to_csv() to write a DataFrame to a CSV file. In this file, one of the columns represents "Year". The problem is that, when the CSV file is loaded by using csv.DictReader(), this column is apparently being read as a float number and, hence, .0 is added to its value!! The following is the exact reading line:

csvfile = csv.DictReader(of, delimiter="|")

I double checked the saved CSV file and there is not decimal points there at all!

How to properly write a CSV file so certain columns are read by csv.DictReader() as string or at least as intergers?

Note: I have no control on how the csv.DictReader() will be called.

答:
First, check what type is Year column with:

```<code>df['Year'].dtype
</code>```

if it's of type float64 than you should convert it to integers:

```<code>df['Year'] = df['Year'].astype(int)
</code>```

Unless you have empty cells in that row, then you need to fill them in first (because you cannot have NaN's in integer columns):

```<code>df['Year'].fillna(1234)
</code>```

Alternatively, play with parameter float_format for to_csv() method.

Body:
First, check what type is Year column with:

df['Year'].dtype

if it's of type float64 than you should convert it to integers:

df['Year'] = df['Year'].astype(int)

Unless you have empty cells in that row, then you need to fill them in first (because you cannot have NaN's in integer columns):

df['Year'].fillna(1234)

Alternatively, play with parameter float_format for to_csv() method.