问:
List of valid operations in Tensorflow
I am using (learning) Tensorflow through the eager C API, or to be even more precise through a FreePascal wrapper around it.
When I want to do e.g. a matrix multiplication, I call

TFE_Execute(Op, @OutTensH, @NumOutVals, Status);

where Op.Op_Name is 'MatMul'. I have a couple of other instructions figured out, e.g. 'Transpose', 'Softmax', 'Inv', etc., but I do not have a complete list. In particular I want to get the determinant of a matrix, but cannot find it (assume it exists). I tried to find it on the web, as well as in the source on GitHub, but no success.
In Python there is tf.linalg.det, but already in C++ API I do not find it.

Could someone direct me to a place where I can find a complete list of supported operations?

Can someone tell me how to calculate the determinant with Tensorflow?

Edit: On Gaurav's request I attach a small program. As said above, it is in Pascal, and calls the C API through a wrapper. I therefore copied also the relevant part of the wrapper here (full version: https://macpgmr.github.io/). The set-up works, the "only" question is that I do not find a list of supported operations.

```<code>// A minimal program to transpose a matrix

program test;
uses
  SysUtils,
  TF;
var
  Tensor:TTensor;
begin
  Tensor:=TTensor.CreateSingle([2,1],[1.0,2.0]);
  writeln('Before transpose ',Tensor.Dim[0],' x ',Tensor.Dim[1]);         // 2 x 1
  Tensor:=Tensor.Temp.ExecOp('Transpose',TTensor.CreateInt32([1,0]).Temp);
  writeln('After transpose  ',Tensor.Dim[0],' x ',Tensor.Dim[1]);         // 1 x 2
  FreeAndNil(Tensor);
end.

// extract from TF.pas ( (C) Phil Hess ). It basically re-packages the operation
// and calls the relevant C TFE_Execute, with the same operation name passed on:
// in our case 'Transpose'.
// I am looking for a complete list of supported operations.

function TTensor.ExecOp(const OpName  : string;
                              Tensor2 : TTensor = nil;
                              Tensor3 : TTensor = nil;
                              Tensor4 : TTensor = nil) : TTensor;
var
  Status     : TF_StatusPtr;
  Op         : TFE_OpPtr;
  NumOutVals : cint;
  OutTensH   : TFE_TensorHandlePtr;
begin
  Result := nil;
  Status := TF_NewStatus();
  Op := TFE_NewOp(Context, PAnsiChar(OpName), Status);
  try
    if not CheckStatus(Status) then
      Exit;
     {Add operation input tensors}
    TFE_OpAddInput(Op, TensorH, Status);
    if not CheckStatus(Status) then
      Exit;
    if Assigned(Tensor2) then  {Operation has 2nd tensor input?}
      begin
      TFE_OpAddInput(Op, Tensor2.TensorH, Status);
      if not CheckStatus(Status) then
        Exit;
      end;
    if Assigned(Tensor3) then  {Operation has 3rd tensor input?}
      begin
      TFE_OpAddInput(Op, Tensor3.TensorH, Status);
      if not CheckStatus(Status) then
        Exit;
      end;
    if Assigned(Tensor4) then  {Operation has 4th tensor input?}
      begin
      TFE_OpAddInput(Op, Tensor4.TensorH, Status);
      if not CheckStatus(Status) then
        Exit;
      end;
     {Set operation attributes}
    TFE_OpSetAttrType(Op, 'T', DataType);  //typically result type same as input's
    if OpName = 'MatMul' then
      begin
      TFE_OpSetAttrBool(Op, 'transpose_a', #0);  //default (False)
      TFE_OpSetAttrBool(Op, 'transpose_b', #0);  //default (False)
      end
    else if OpName = 'Transpose' then
      TFE_OpSetAttrType(Op, 'Tperm', Tensor2.DataType)  //permutations type
    else if OpName = 'Sum' then
      begin
      TFE_OpSetAttrType(Op, 'Tidx', Tensor2.DataType);  //reduction_indices type
      TFE_OpSetAttrBool(Op, 'keep_dims', #0);          //default (False)
      end
    else if (OpName = 'RandomUniform') or (OpName = 'RandomStandardNormal') then
      begin
      TFE_OpSetAttrInt(Op, 'seed', 0);           //default
      TFE_OpSetAttrInt(Op, 'seed2', 0);          //default
      TFE_OpSetAttrType(Op, 'dtype', TF_FLOAT);  //for now, use this as result type
      end
    else if OpName = 'OneHot' then
      begin
      TFE_OpSetAttrType(Op, 'T', Tensor3.DataType);  //result type must be same as on/off
      TFE_OpSetAttrInt(Op, 'axis', -1);              //default
      TFE_OpSetAttrType(Op, 'TI', DataType);         //indices type
      end;
    NumOutVals := 1;
    try

      // **** THIS IS THE ACTUAL CALL TO THE C API, WHERE Op HAS THE OPNAME

      TFE_Execute(Op, @OutTensH, @NumOutVals, Status);

      // ***********************************************************************

    except on e:Exception do
      raise Exception.Create('TensorFlow unable to execute ' + OpName +
                             ' operation: ' + e.Message);
    end;
    if not CheckStatus(Status) then
      Exit;
    Result := TTensor.CreateWithHandle(OutTensH);
  finally
    if Assigned(Op) then
      TFE_DeleteOp(Op);
    TF_DeleteStatus(Status);
     {Even if exception occurred, don't want to leave any temps dangling}
    if Assigned(Tensor2) and Tensor2.IsTemp then
      Tensor2.Free;
    if Assigned(Tensor3) and Tensor3.IsTemp then
      Tensor3.Free;
    if Assigned(Tensor4) and Tensor4.IsTemp then
      Tensor4.Free;
    if IsTemp then
      Free;
  end;
end;
</code>```

答:
In the meantime, I found the description file of TensorFlow at: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/ops/ops.pbtxt. This includes all the operations and their detailed specification.
If someone is interested in a pascal interface to TF, I created one at https://github.com/zsoltszakaly/tensorflowforpascal.</p>

Title: List of valid operations in Tensorflow

Body:
I am using (learning) Tensorflow through the eager C API, or to be even more precise through a FreePascal wrapper around it.
When I want to do e.g. a matrix multiplication, I call

TFE_Execute(Op, @OutTensH, @NumOutVals, Status);

where Op.Op_Name is 'MatMul'. I have a couple of other instructions figured out, e.g. 'Transpose', 'Softmax', 'Inv', etc., but I do not have a complete list. In particular I want to get the determinant of a matrix, but cannot find it (assume it exists). I tried to find it on the web, as well as in the source on GitHub, but no success.
In Python there is tf.linalg.det, but already in C++ API I do not find it.

Could someone direct me to a place where I can find a complete list of supported operations?

Can someone tell me how to calculate the determinant with Tensorflow?

Edit: On Gaurav's request I attach a small program. As said above, it is in Pascal, and calls the C API through a wrapper. I therefore copied also the relevant part of the wrapper here (full version: https://macpgmr.github.io/). The set-up works, the "only" question is that I do not find a list of supported operations.

// A minimal program to transpose a matrix

program test;
uses
  SysUtils,
  TF;
var
  Tensor:TTensor;
begin
  Tensor:=TTensor.CreateSingle([2,1],[1.0,2.0]);
  writeln('Before transpose ',Tensor.Dim[0],' x ',Tensor.Dim[1]);         // 2 x 1
  Tensor:=Tensor.Temp.ExecOp('Transpose',TTensor.CreateInt32([1,0]).Temp);
  writeln('After transpose  ',Tensor.Dim[0],' x ',Tensor.Dim[1]);         // 1 x 2
  FreeAndNil(Tensor);
end.

// extract from TF.pas ( (C) Phil Hess ). It basically re-packages the operation
// and calls the relevant C TFE_Execute, with the same operation name passed on:
// in our case 'Transpose'.
// I am looking for a complete list of supported operations.

function TTensor.ExecOp(const OpName  : string;
                              Tensor2 : TTensor = nil;
                              Tensor3 : TTensor = nil;
                              Tensor4 : TTensor = nil) : TTensor;
var
  Status     : TF_StatusPtr;
  Op         : TFE_OpPtr;
  NumOutVals : cint;
  OutTensH   : TFE_TensorHandlePtr;
begin
  Result := nil;
  Status := TF_NewStatus();
  Op := TFE_NewOp(Context, PAnsiChar(OpName), Status);
  try
    if not CheckStatus(Status) then
      Exit;
     {Add operation input tensors}
    TFE_OpAddInput(Op, TensorH, Status);
    if not CheckStatus(Status) then
      Exit;
    if Assigned(Tensor2) then  {Operation has 2nd tensor input?}
      begin
      TFE_OpAddInput(Op, Tensor2.TensorH, Status);
      if not CheckStatus(Status) then
        Exit;
      end;
    if Assigned(Tensor3) then  {Operation has 3rd tensor input?}
      begin
      TFE_OpAddInput(Op, Tensor3.TensorH, Status);
      if not CheckStatus(Status) then
        Exit;
      end;
    if Assigned(Tensor4) then  {Operation has 4th tensor input?}
      begin
      TFE_OpAddInput(Op, Tensor4.TensorH, Status);
      if not CheckStatus(Status) then
        Exit;
      end;
     {Set operation attributes}
    TFE_OpSetAttrType(Op, 'T', DataType);  //typically result type same as input's
    if OpName = 'MatMul' then
      begin
      TFE_OpSetAttrBool(Op, 'transpose_a', #0);  //default (False)
      TFE_OpSetAttrBool(Op, 'transpose_b', #0);  //default (False)
      end
    else if OpName = 'Transpose' then
      TFE_OpSetAttrType(Op, 'Tperm', Tensor2.DataType)  //permutations type
    else if OpName = 'Sum' then
      begin
      TFE_OpSetAttrType(Op, 'Tidx', Tensor2.DataType);  //reduction_indices type
      TFE_OpSetAttrBool(Op, 'keep_dims', #0);          //default (False)
      end
    else if (OpName = 'RandomUniform') or (OpName = 'RandomStandardNormal') then
      begin
      TFE_OpSetAttrInt(Op, 'seed', 0);           //default
      TFE_OpSetAttrInt(Op, 'seed2', 0);          //default
      TFE_OpSetAttrType(Op, 'dtype', TF_FLOAT);  //for now, use this as result type
      end
    else if OpName = 'OneHot' then
      begin
      TFE_OpSetAttrType(Op, 'T', Tensor3.DataType);  //result type must be same as on/off
      TFE_OpSetAttrInt(Op, 'axis', -1);              //default
      TFE_OpSetAttrType(Op, 'TI', DataType);         //indices type
      end;
    NumOutVals := 1;
    try

      // **** THIS IS THE ACTUAL CALL TO THE C API, WHERE Op HAS THE OPNAME

      TFE_Execute(Op, @OutTensH, @NumOutVals, Status);

      // ***********************************************************************

    except on e:Exception do
      raise Exception.Create('TensorFlow unable to execute ' + OpName +
                             ' operation: ' + e.Message);
    end;
    if not CheckStatus(Status) then
      Exit;
    Result := TTensor.CreateWithHandle(OutTensH);
  finally
    if Assigned(Op) then
      TFE_DeleteOp(Op);
    TF_DeleteStatus(Status);
     {Even if exception occurred, don't want to leave any temps dangling}
    if Assigned(Tensor2) and Tensor2.IsTemp then
      Tensor2.Free;
    if Assigned(Tensor3) and Tensor3.IsTemp then
      Tensor3.Free;
    if Assigned(Tensor4) and Tensor4.IsTemp then
      Tensor4.Free;
    if IsTemp then
      Free;
  end;
end;


来源: stackexchange

问:
.net core 3.1 cert authentication returns 403 when deployed on Azure
I have followed this documentation (https://learn.microsoft.com/en-us/aspnet/core/security/authentication/certauth?view=aspnetcore-3.1) to implement an authentication by certificat in my .net core 3.1 API. Everything works fine when I call my API on localhost, but I continously get an error 403 once the API is deployed on Azure.
I have no idea of what happens as there is no additional information on logs. I just don't understand what causes the 403

As I understand, when I call my API routes I have to provide the certificate inside the "X-ARR-ClientCert" header, which is working fine locally, but seems not being interpreted on Azure.

Am I missing something ? Do I need to set a specific setting on my App Service ?

答:
As the article said, if the correct certificate is sent to the server, the data is returned. If no certificate or the wrong certificate is sent, an HTTP 403 status code is returned.

So, as Bhushan said, confirm your certificate has uploaded to azure app service.

When you enable mutual auth for your application, all paths under the root of your app will require a client certificate for access. Exclusion paths can be configured by selecting Configuration > General Settings and defining an exclusion path.

For more details, you could refer to this article.

ContentLicense: CC BY-SA 4.0


问:
Counter in double loop with counting in both internal and external for
I would like to know if there is a well-known formula for the following way of counting:

```<code>count = 0
for i in range(n):
   for j in range(m):
      count = count + 1
   count = count + 10
</code>```

Many thanks in advance,

Cayo

EDIT 1:

Thanks Ernest, you are right, but that is not really the problem. Sorry, I was not clear enough, let me explain better my problem. I don't just want to count, I need use this counter inside the inner loop. I have a 2D flatten array and I want to access just a sub-2D-region of this array. So, actually, what I am doing is:

```<code>count = 0
for i in range(n):
   for j in range(m):
      big_flatten_array(count) = value
      count = count + 1
   count = count + 10
</code>```

EDIT 2:
It doesn't work just using

```<code>count = i * 10 + j
</code>```

Try checking the values:

```<code>count = 0
for i in range(3):
   for j in range():
      k = i * 2 + j
      vec[k] = count
      vec2[k] = i * 10 + j
      count = count + 1
   count = count + 10
</code>```

And you will see the vec and vec2 are not the same...

答:
Let's consider that the line count = count + 10 didn't exist, then it would simply be:

```<code>count = i*m + j
</code>```

Consider n = 3, and m = 3
So the count values are like 0, 1, 2, 3, 4 ..
once you add the line count += 10, you're simply adding multiples of 10 to the count value each time the outer loop finishes.

0, 1, 12, 13, 24, 25... or 0, 1, 10 + 2, 10 + 3, 20 + 4, 20 + 5...

so the expression becomes

```<code>count = (10*i) + (i*m+j)
</code>```

And you can get all the count values like so:

```<code>count = [(10 * i) + (i * m + j) for i in range(n) for j in range(m)]
</code>```

Body:
I would like to know if there is a well-known formula for the following way of counting:

count = 0
for i in range(n):
   for j in range(m):
      count = count + 1
   count = count + 10

Many thanks in advance,

Cayo

EDIT 1:

Thanks Ernest, you are right, but that is not really the problem. Sorry, I was not clear enough, let me explain better my problem. I don't just want to count, I need use this counter inside the inner loop. I have a 2D flatten array and I want to access just a sub-2D-region of this array. So, actually, what I am doing is:

count = 0
for i in range(n):
   for j in range(m):
      big_flatten_array(count) = value
      count = count + 1
   count = count + 10

EDIT 2:
It doesn't work just using

count = i * 10 + j

Try checking the values:

count = 0
for i in range(3):
   for j in range():
      k = i * 2 + j
      vec[k] = count
      vec2[k] = i * 10 + j
      count = count + 1
   count = count + 10

And you will see the vec and vec2 are not the same...

Body:
Let's consider that the line count = count + 10 didn't exist, then it would simply be:

count = i*m + j

Consider n = 3, and m = 3
So the count values are like 0, 1, 2, 3, 4 ..
once you add the line count += 10, you're simply adding multiples of 10 to the count value each time the outer loop finishes.

0, 1, 12, 13, 24, 25... or 0, 1, 10 + 2, 10 + 3, 20 + 4, 20 + 5...

so the expression becomes

count = (10*i) + (i*m+j)

And you can get all the count values like so:

count = [(10 * i) + (i * m + j) for i in range(n) for j in range(m)]


问:
My css code in Word Press is working for every other page in the website when i only want it to work for 1 page
I have currently made a code in CSS, which I wanted for a particular page but unfortunately, it is working for every other page as well and it makes the other pages look quite broken since the formatting of them goes very odd.

The solutions I have tried so far are:

Using the unique code of the page and making it something like this - * .post-id-17 .stop {code here}
But I got no results from using this solution.

Here is the HTML code:

```<code><!DOCTYPE html>
<html>
<head>
    <title>CountDown</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet">
</head>
<body>
    <header>
        <h1>CountDown</h1>
    </header>
    <div class="content">
        <div class="counter"></div>
        <input type="number" id="seconds" placeholder="Seconds">
        <div class="buttons">
            <button class="btn start" id="start" value="1" onclick="check(this)">Start</button>
            <button class="btn start" id="continue" value="1" onclick="check(this)">Continue</button>
            <button class="btn stop" id="stop" value="0" onclick="check(this)">Stop</button>
            <button class="btn start" id="ok" onclick="toSubmit()">Submit</button>
        </div>
    </div>
    <script type="text/javascript" src="main.js"></script>

</body>
</html>
</code>```

Here is the CSS code:

```<code>* .post-id-706 .stop {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}

html, body{
    height: 100%;
}
body{
    width: 100%;
    height: 100%;
    background: linear-gradient(to left top, #0045D6, #00A9f6);
}

header{
    width: 100%;
    height: 13vh;
    background-color: #fff;
    color: #0045F6;
    display: flex;
    justify-content: center;
    align-items: center;
}

.content{
    width: 100%;
    height: 60vh;
    font-size: 3rem;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}

.content #seconds{
    width: 250px;
    font-size: 2rem;
    padding: 1rem;
    outline: none;
    background: none;
    border: none;
    border-bottom: 3px solid #fff;
    color: #000000;
}

#seconds::placeholder{
    color: #ddd;
    font-size: 1.7rem;
}

.btn{
    background-color: #fff;
    border-radius: 4px;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 0.8rem 1.7rem;
    font-size: 1.2rem;
    font-weight: 700;
}

.start{
    color: #1f0;
}

.stop{
    color: #E00;
}

#start, #stop, #continue{
    display: none;
}

.counter{
    color: #000000;
}
</code>```

Here is the javascript code:

```<code>const container = document.querySelector('.counter');
const buttonsDiv = document.querySelector('.buttons');
const secInput = document.getElementById('seconds');

var seconds;
var remseconds;
var minuts;
var toCount = false;

function toSubmit(){
    display('start');
    remove('seconds');
    remove('ok');
    seconds = Number(secInput.value);
    counting();
}

function display(e){
    document.getElementById(e).style.display = 'block';
}

function remove(e){
    document.getElementById(e).style.display = 'none';
}

function check(stat){
    if(stat.id == "start"){
        display("stop");
        remove("start");
        toCount = true;
    }
    else if(stat.id == "stop"){
        display("continue");
        remove("stop");
        toCount = false
    }
    else{
        display("stop");
        remove("continue");
        toCount =true;
    }
}

function count(){
    if(seconds > 0){
        if(toCount == true){
            seconds--;
            remseconds = seconds % 60;
            minuts = Math.floor(seconds / 60);

            if(minuts < 10){
                minuts = "0" + minuts;
            }

            if(remseconds < 10){
                remseconds = "0" + remseconds;
            }

            container.innerHTML = minuts + " : " + remseconds;
        }
    }
    else{
        container.innerHTML = "DONE!";
        buttonsDiv.style.opacity = "0";
    }
}

function counting(){
    remseconds = seconds % 60;
    minuts = Math.floor(seconds / 60);

    if(remseconds < 10){
        remseconds = "0" + remseconds;
    }

    container.innerHTML = minuts + " : " + remseconds;
    setInterval(count, 1000);
}
</code>```

If you have any ideas in order to solve this issue please let me know.

答:
Here is the HTML code:

```<code><!DOCTYPE html>
<html class="class2">
<head>
    <title>CountDown</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet">
</head>
<body>
    <header>
        <h1>CountDown</h1>
    </header>
    <div class="content">
        <div class="counter"></div>
        <input type="number" id="seconds" placeholder="Seconds">
        <div class="buttons">
            <button class="btn start" id="start" value="1" onclick="check(this)">Start</button>
            <button class="btn start" id="continue" value="1" onclick="check(this)">Continue</button>
            <button class="btn stop" id="stop" value="0" onclick="check(this)">Stop</button>
            <button class="btn start" id="ok" onclick="toSubmit()">Submit</button>
        </div>
    </div>
    <script type="text/javascript" src="main.js"></script>

</body>
</html>
</code>```

Here is the CSS code:

```<code>.class2 .content{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}

.class2 html, body{
    height: 100%;
}
.class2 body{
    width: 100%;
    height: 100%;
    background: linear-gradient(to left top, #0045D6, #00A9f6);
}

.class2 header{
    width: 100%;
    height: 13vh;
    background-color: #fff;
    color: #0045F6;
    display: flex;
    justify-content: center;
    align-items: center;
}

.class2 .content{
    width: 100%;
    height: 60vh;
    font-size: 3rem;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}

.class2 .content #seconds{
    width: 250px;
    font-size: 2rem;
    padding: 1rem;
    outline: none;
    background: none;
    border: none;
    border-bottom: 3px solid #fff;
    color: #000000;
}

#seconds::placeholder{
    color: #ddd;
    font-size: 1.7rem;
}

.class2 .btn{
    background-color: #fff;
    border-radius: 4px;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 0.8rem 1.7rem;
    font-size: 1.2rem;
    font-weight: 700;
}

.start{
    color: #1f0;
}

.stop{
    color: #E00;
}

#start, #stop, #continue{
    display: none;
}

.counter{
    color: #000000;
}
</code>```

Body:
I have currently made a code in CSS, which I wanted for a particular page but unfortunately, it is working for every other page as well and it makes the other pages look quite broken since the formatting of them goes very odd.

The solutions I have tried so far are:

Using the unique code of the page and making it something like this - * .post-id-17 .stop {code here}
But I got no results from using this solution.

Here is the HTML code:

<!DOCTYPE html>

    <title>CountDown</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet">

CountDown

        <input type="number" id="seconds" placeholder="Seconds">

            <button class="btn start" id="start" value="1" onclick="check(this)">Start</button>
            <button class="btn start" id="continue" value="1" onclick="check(this)">Continue</button>
            <button class="btn stop" id="stop" value="0" onclick="check(this)">Stop</button>
            <button class="btn start" id="ok" onclick="toSubmit()">Submit</button>

Here is the CSS code:

* .post-id-706 .stop {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}

html, body{
    height: 100%;
}
body{
    width: 100%;
    height: 100%;
    background: linear-gradient(to left top, #0045D6, #00A9f6);
}

header{
    width: 100%;
    height: 13vh;
    background-color: #fff;
    color: #0045F6;
    display: flex;
    justify-content: center;
    align-items: center;
}

.content{
    width: 100%;
    height: 60vh;
    font-size: 3rem;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}

.content #seconds{
    width: 250px;
    font-size: 2rem;
    padding: 1rem;
    outline: none;
    background: none;
    border: none;
    border-bottom: 3px solid #fff;
    color: #000000;
}

#seconds::placeholder{
    color: #ddd;
    font-size: 1.7rem;
}

.btn{
    background-color: #fff;
    border-radius: 4px;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 0.8rem 1.7rem;
    font-size: 1.2rem;
    font-weight: 700;
}

.start{
    color: #1f0;
}

.stop{
    color: #E00;
}

#start, #stop, #continue{
    display: none;
}

.counter{
    color: #000000;
}

Here is the javascript code:

const container = document.querySelector('.counter');
const buttonsDiv = document.querySelector('.buttons');
const secInput = document.getElementById('seconds');

var seconds;
var remseconds;
var minuts;
var toCount = false;

function toSubmit(){
    display('start');
    remove('seconds');
    remove('ok');
    seconds = Number(secInput.value);
    counting();
}

function display(e){
    document.getElementById(e).style.display = 'block';
}

function remove(e){
    document.getElementById(e).style.display = 'none';
}

function check(stat){
    if(stat.id == "start"){
        display("stop");
        remove("start");
        toCount = true;
    }
    else if(stat.id == "stop"){
        display("continue");
        remove("stop");
        toCount = false
    }
    else{
        display("stop");
        remove("continue");
        toCount =true;
    }
}

function count(){
    if(seconds > 0){
        if(toCount == true){
            seconds--;
            remseconds = seconds % 60;
            minuts = Math.floor(seconds / 60);

            if(minuts < 10){
                minuts = "0" + minuts;
            }

            if(remseconds < 10){
                remseconds = "0" + remseconds;
            }

            container.innerHTML = minuts + " : " + remseconds;
        }
    }
    else{
        container.innerHTML = "DONE!";
        buttonsDiv.style.opacity = "0";
    }
}

function counting(){
    remseconds = seconds % 60;
    minuts = Math.floor(seconds / 60);

    if(remseconds < 10){
        remseconds = "0" + remseconds;
    }

    container.innerHTML = minuts + " : " + remseconds;
    setInterval(count, 1000);
}

If you have any ideas in order to solve this issue please let me know.

Body:
Here is the HTML code:

<!DOCTYPE html>
<html class="class2">
<head>
    <title>CountDown</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet">
</head>
<body>
    <header>
        <h1>CountDown</h1>
    </header>
    <div class="content">
        <div class="counter"></div>
        <input type="number" id="seconds" placeholder="Seconds">
        <div class="buttons">
            <button class="btn start" id="start" value="1" onclick="check(this)">Start</button>
            <button class="btn start" id="continue" value="1" onclick="check(this)">Continue</button>
            <button class="btn stop" id="stop" value="0" onclick="check(this)">Stop</button>
            <button class="btn start" id="ok" onclick="toSubmit()">Submit</button>
        </div>
    </div>
    <script type="text/javascript" src="main.js"></script>

</body>
</html>

Here is the CSS code:

.class2 .content{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}

.class2 html, body{
    height: 100%;
}
.class2 body{
    width: 100%;
    height: 100%;
    background: linear-gradient(to left top, #0045D6, #00A9f6);
}

.class2 header{
    width: 100%;
    height: 13vh;
    background-color: #fff;
    color: #0045F6;
    display: flex;
    justify-content: center;
    align-items: center;
}

.class2 .content{
    width: 100%;
    height: 60vh;
    font-size: 3rem;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}

.class2 .content #seconds{
    width: 250px;
    font-size: 2rem;
    padding: 1rem;
    outline: none;
    background: none;
    border: none;
    border-bottom: 3px solid #fff;
    color: #000000;
}

#seconds::placeholder{
    color: #ddd;
    font-size: 1.7rem;
}

.class2 .btn{
    background-color: #fff;
    border-radius: 4px;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 0.8rem 1.7rem;
    font-size: 1.2rem;
    font-weight: 700;
}

.start{
    color: #1f0;
}

.stop{
    color: #E00;
}

#start, #stop, #continue{
    display: none;
}

.counter{
    color: #000000;
}


问:
How do I return an object from a document stored in Firestore (Swift)
I have a users collection in firebase and a user struct. I need to write a function that takes in the user's id and returns the corresponding user object:

```<code>struct AppUser: Codable {

    var id: String
    var displayName: String
    var photoURL: String
    var points: Int?
    var knownLanguageCodes: Set<String>?

}
</code>```

This is my function that I have so far.

```<code>func getUser(id: String) -> AppUser? {

    let db = Firestore.firestore()
    let userRef = db.collection("users").document(id)

    userRef.getDocument { (document, error) in
         if let document = document, document.exists {
            let userID = document.data()?["id"] as! String
            let userDisplayName = document.data()?["displayName"] as! String
            let userPhotoURL = document.data()?["photoURL"] as! String
            let userPoints = document.data()?["points"] as! Int?
            let userKnownLanguageCodes = document.data()?["knownLanguageCode"] as! Set<String>?
            let user = AppUser(id: userID,
                               displayName: userDisplayName,
                               photoURL: userPhotoURL,
                               points: userPoints,
                               knownLanguageCodes: userKnownLanguageCodes)
            return user
         } else {
            print("Error getting user")
            return nil
        }
    }
}
</code>```

Both of the return statements above give the error: Unexpected non-void return value in void function

I have looked at the code here https://cloud.google.com/firestore/docs/query-data/get-data under the heading 'Custom objects' and it doesn't seem to work for me. I get the error: Value of type 'NSObject' has no member 'data'. This is produced on line 6 of the code in the link.

答:
You can't return inside a closure use a completion like

```<code>func getUser(id: String,completion:@escaping((AppUser?) -> ())) {

    let db = Firestore.firestore()
    let userRef = db.collection("users").document(id)
    userRef.getDocument { (document, error) in
         if let document = document, document.exists {
            let userID = document.data()?["id"] as! String
            let userDisplayName = document.data()?["displayName"] as! String
            let userPhotoURL = document.data()?["photoURL"] as! String
            let userPoints = document.data()?["points"] as! Int?
            let userKnownLanguageCodes = document.data()?["knownLanguageCode"] as! Set<String>?
            let user = AppUser(id: userID,
                               displayName: userDisplayName,
                               photoURL: userPhotoURL,
                               points: userPoints,
                               knownLanguageCodes: userKnownLanguageCodes)
            completion(user)
         } else {
            print("Error getting user")
            completion(nil)
        }
    }
}
</code>```

Call

```<code>getUser(id:<#str#>) { user in
  print(user)
}
</code>```

Body:
I have a users collection in firebase and a user struct. I need to write a function that takes in the user's id and returns the corresponding user object:

struct AppUser: Codable {

    var id: String
    var displayName: String
    var photoURL: String
    var points: Int?
    var knownLanguageCodes: Set<String>?

}

This is my function that I have so far.

func getUser(id: String) -> AppUser? {

    let db = Firestore.firestore()
    let userRef = db.collection("users").document(id)

    userRef.getDocument { (document, error) in
         if let document = document, document.exists {
            let userID = document.data()?["id"] as! String
            let userDisplayName = document.data()?["displayName"] as! String
            let userPhotoURL = document.data()?["photoURL"] as! String
            let userPoints = document.data()?["points"] as! Int?
            let userKnownLanguageCodes = document.data()?["knownLanguageCode"] as! Set<String>?
            let user = AppUser(id: userID,
                               displayName: userDisplayName,
                               photoURL: userPhotoURL,
                               points: userPoints,
                               knownLanguageCodes: userKnownLanguageCodes)
            return user
         } else {
            print("Error getting user")
            return nil
        }
    }
}

Both of the return statements above give the error: Unexpected non-void return value in void function

I have looked at the code here https://cloud.google.com/firestore/docs/query-data/get-data under the heading 'Custom objects' and it doesn't seem to work for me. I get the error: Value of type 'NSObject' has no member 'data'. This is produced on line 6 of the code in the link.

Body:
You can't return inside a closure use a completion like

func getUser(id: String,completion:@escaping((AppUser?) -> ())) {

    let db = Firestore.firestore()
    let userRef = db.collection("users").document(id)
    userRef.getDocument { (document, error) in
         if let document = document, document.exists {
            let userID = document.data()?["id"] as! String
            let userDisplayName = document.data()?["displayName"] as! String
            let userPhotoURL = document.data()?["photoURL"] as! String
            let userPoints = document.data()?["points"] as! Int?
            let userKnownLanguageCodes = document.data()?["knownLanguageCode"] as! Set<String>?
            let user = AppUser(id: userID,
                               displayName: userDisplayName,
                               photoURL: userPhotoURL,
                               points: userPoints,
                               knownLanguageCodes: userKnownLanguageCodes)
            completion(user)
         } else {
            print("Error getting user")
            completion(nil)
        }
    }
}

Call

getUser(id:<#str#>) { user in
  print(user)
}


问:
Partial empty POST or QueryDict when working with Ajax and Jquery
I have a django form which I'm using to post the data of the item, status and id

```<code>class TemplateDataForm(forms.ModelForm):
item = forms.CharField(widget=forms.TextInput(attrs={'id':'temp_item'}))
status = forms.ChoiceField(label='', choices=CHOICES, widget=forms.Select(attrs={'id':'status'}))

class Meta:
    model = TempData
    fields = ['item','status']
</code>```

I"m passing the attrs like id to the fields in the forms

```<code>        <form method='post' id='js-temp-data'>
        {% csrf_token %}
        {% for hidden_field in temp_data_form.hidden_fields %}
            {{hidden_field.errors}}
            {{hidden_field}}
        {% endfor %}
        <div class="form-row align-items-center">
        {% for field in temp_data_form.visible_fields %}

            <div class="col-auto">
                {{field.label_tag}}
                {{field.errors}}
                {{field}}
                {{field.help_text}}
            </div>

        {% endfor %}
            <div class="col-auto">
            <input type="hidden" id='js_template_id_new' name="" value="{{temp_obj_for_template.id}}">
            <!-- <input type="image" src="{% static 'components/plus1.png'%}" width=15 heigth=15 name="submit" alt='Submit' value="Add"> -->
            <input type="submit" id='js-temp-data-submit' value="submit" name="">
            </div>
        </div>
    </form>
</code>```

I"m using the css id of the input tags in below Jquery but it's not picking up the input values and posting empty response for title and id

```<code>    <script type="text/javascript">
    $(document).ready(function(){
        $('#js-temp-data-submit').click(function(e) {
        e.preventDefault();
        $.ajax({
            type:'POST',
            url:'{% url "checklist" %}',
            data:{
                item:$('#temp_item').val(), //not working
                id:$("#js_template_id_new").val(), //I'm passing the object to template from view which is working for other form but not for this
                status:$('#status').val(), //working
                csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), //working
                action:'post'
            },
            success: function(response){
                $("#js-temp-data").trigger('reset');
                $('#js-temp-data').focus();
            },
            error: function(response){
                alert(response["responseJSON"]["error"])
            }
        });
    });
});
</script>
</code>```

The below is the output of the request.POST, where I'm able to get the values of the status and csrf token but not title value

```<code><QueryDict: {'item': [''], 'id': [''], 'status': ['Y'], 'csrfmiddlewaretoken': ['k8QOiu89labeDNQupX6Zw5fEwUyf1KylPayf3xisYTLX6dseBXsGaVeAdLYLgGH0'], 'action': ['post']}>
</code>```

where I'm doing wrong, I have tried using the form-id which resulted the same and then using the input submit id which is also giving the same result

答:
Finally I was able to fix the above issue, in my script I was using the submit id to perform click action so I modified with the below code

```<code>    <script type="text/javascript">
    $(document).ready(function(){
       //using the form id and checking on submit action of it
        $('#js-temp-data-form').on('submit', function(e) {
        e.preventDefault();
        //storing the item in a variable and assign to the item in data dict
        var item = $('#js_temp_item').val();
        var id = $('#js_template_id').val();
        // console.log($("#js_template_id").val());
        $.ajax({
            type:'POST',
            url:'{% url "checklist" %}',
            data:{
                item:item,
                temp_id:id,
                status:$('#status').val(),
                csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
                action:'post'
            },
            success: function(response){
                $("#js-temp-data").trigger('reset');
                $('#js-temp-data').focus();
            },
            error: function(response){
                alert(response["responseJSON"]["error"])
            }
        });
    });
});
</script>
</code>```

after modifying the script I could see the request.POST data with details i'm looking for

```<code><QueryDict: {'item': ['Paste'], 'temp_id': ['120'], 'status': ['I'], 'csrfmiddlewaretoken': ['nmvCsEpLqMwtH0xdooZPfyWbBq2NORuT5pO2ZOLiJZIQA11RSGLNtKxblBL7BmiF'], 'action': ['post']}>
</code>```

Body:
I have a django form which I'm using to post the data of the item, status and id

class TemplateDataForm(forms.ModelForm):
item = forms.CharField(widget=forms.TextInput(attrs={'id':'temp_item'}))
status = forms.ChoiceField(label='', choices=CHOICES, widget=forms.Select(attrs={'id':'status'}))

class Meta:
    model = TempData
    fields = ['item','status']

I"m passing the attrs like id to the fields in the forms

        <form method='post' id='js-temp-data'>
        {% csrf_token %}
        {% for hidden_field in temp_data_form.hidden_fields %}
            {{hidden_field.errors}}
            {{hidden_field}}
        {% endfor %}

        {% for field in temp_data_form.visible_fields %}

                {{field.label_tag}}
                {{field.errors}}
                {{field}}
                {{field.help_text}}

        {% endfor %}

            <input type="hidden" id='js_template_id_new' name="" value="{{temp_obj_for_template.id}}">

            <input type="submit" id='js-temp-data-submit' value="submit" name="">

    </form>

I"m using the css id of the input tags in below Jquery but it's not picking up the input values and posting empty response for title and id

The below is the output of the request.POST, where I'm able to get the values of the status and csrf token but not title value

<QueryDict: {'item': [''], 'id': [''], 'status': ['Y'], 'csrfmiddlewaretoken': ['k8QOiu89labeDNQupX6Zw5fEwUyf1KylPayf3xisYTLX6dseBXsGaVeAdLYLgGH0'], 'action': ['post']}>

where I'm doing wrong, I have tried using the form-id which resulted the same and then using the input submit id which is also giving the same result

Body:
Finally I was able to fix the above issue, in my script I was using the submit id to perform click action so I modified with the below code

    <script type="text/javascript">
    $(document).ready(function(){
       //using the form id and checking on submit action of it
        $('#js-temp-data-form').on('submit', function(e) {
        e.preventDefault();
        //storing the item in a variable and assign to the item in data dict
        var item = $('#js_temp_item').val();
        var id = $('#js_template_id').val();
        // console.log($("#js_template_id").val());
        $.ajax({
            type:'POST',
            url:'{% url "checklist" %}',
            data:{
                item:item,
                temp_id:id,
                status:$('#status').val(),
                csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
                action:'post'
            },
            success: function(response){
                $("#js-temp-data").trigger('reset');
                $('#js-temp-data').focus();
            },
            error: function(response){
                alert(response["responseJSON"]["error"])
            }
        });
    });
});
</script>

after modifying the script I could see the request.POST data with details i'm looking for

<QueryDict: {'item': ['Paste'], 'temp_id': ['120'], 'status': ['I'], 'csrfmiddlewaretoken': ['nmvCsEpLqMwtH0xdooZPfyWbBq2NORuT5pO2ZOLiJZIQA11RSGLNtKxblBL7BmiF'], 'action': ['post']}>


问:
Merging list of dictionaries into a smaller list of dictionaries dependent on recurring values
I have a question regarding a list of dictionaries. Let me demonstrate my problem. Here is a sample list of dictionaries:

```<code>[{'a' : '1'}, {'b' : 'something'}, {'c' : 'else'},
 {'a' : '2'}, {'b' : 'anything'}, {'c' : 'if'},
 {'a' : '3'}, {'b' : 'nothing'}, {'c' : 'matters'}]
</code>```

As you can see I have separated dictionaries, however I want to merge them. The condition is that when the dictionary name reoccurs, that should be a separate dictionary. Something like this:

```<code>list_of_dict =
[{'a' : '1', 'b' : 'something', 'c' : 'else'},
 {'a' : '2', 'b' : 'anything', 'c' : 'if'},
 {'a' : '3', 'b' : 'nothing', 'c' : 'matters'}]
</code>```

I have been trying to use dict(ChainMap(*list_of_dict), however that will only return:

```<code>{'c': 'else', 'b': 'something', 'a': '1'}
</code>```

I was thinking of maybe using a for loop to solve my problem, but I don't know how to start. Do you guys have any idea?

答:
This could be done with a for-loop, iterating over list_of_dict and checking if the key from the dictionary is in the latest dictionary in the return list. If not, append it to the latest dictionary using the ** operator to merge the dictionaries, otherwise start a new dictionary in the return list.

Code:

```<code>list_of_dict = [{'a' : '1'}, {'b' : 'something'}, {'c' : 'else'},
                {'a' : '2'}, {'b' : 'anything'}, {'c' : 'if'},
                {'a' : '3'}, {'b' : 'nothing'}, {'c' : 'matters'}]

rv = [{}]

for d in list_of_dict:
    if list(d)[0] not in rv[-1]:
        rv[-1] = {**rv[-1], **d}
    else:
        rv.append(d)
</code>```

Output:

```<code>>>> rv
[{'a': '1', 'b': 'something', 'c': 'else'},
 {'a': '2', 'b': 'anything', 'c': 'if'},
 {'a': '3', 'b': 'nothing', 'c': 'matters'}]
</code>```

Body:
I have a question regarding a list of dictionaries. Let me demonstrate my problem. Here is a sample list of dictionaries:

[{'a' : '1'}, {'b' : 'something'}, {'c' : 'else'},
 {'a' : '2'}, {'b' : 'anything'}, {'c' : 'if'},
 {'a' : '3'}, {'b' : 'nothing'}, {'c' : 'matters'}]

As you can see I have separated dictionaries, however I want to merge them. The condition is that when the dictionary name reoccurs, that should be a separate dictionary. Something like this:

list_of_dict =
[{'a' : '1', 'b' : 'something', 'c' : 'else'},
 {'a' : '2', 'b' : 'anything', 'c' : 'if'},
 {'a' : '3', 'b' : 'nothing', 'c' : 'matters'}]

I have been trying to use dict(ChainMap(*list_of_dict), however that will only return:

{'c': 'else', 'b': 'something', 'a': '1'}

I was thinking of maybe using a for loop to solve my problem, but I don't know how to start. Do you guys have any idea?

Body:
This could be done with a for-loop, iterating over list_of_dict and checking if the key from the dictionary is in the latest dictionary in the return list. If not, append it to the latest dictionary using the ** operator to merge the dictionaries, otherwise start a new dictionary in the return list.

Code:

list_of_dict = [{'a' : '1'}, {'b' : 'something'}, {'c' : 'else'},
                {'a' : '2'}, {'b' : 'anything'}, {'c' : 'if'},
                {'a' : '3'}, {'b' : 'nothing'}, {'c' : 'matters'}]

rv = [{}]

for d in list_of_dict:
    if list(d)[0] not in rv[-1]:
        rv[-1] = {**rv[-1], **d}
    else:
        rv.append(d)

Output:

>>> rv
[{'a': '1', 'b': 'something', 'c': 'else'},
 {'a': '2', 'b': 'anything', 'c': 'if'},
 {'a': '3', 'b': 'nothing', 'c': 'matters'}]


问:
c# find if whether the number is happy or not
Im trying to understund how do I find whether the number is Happy Number or not,
I know that i need to check if the unit digit and the digit in the highest number location are greater
then the numbers in the middele.
`example:
given number: 63240
the unit: 6
the number in the highest location:0
are both of them greater then 3 and 2 and4(middle) ? yes
result: true (for that case)

the quation is:
write a program that get a number from user, the program will print if the given number from the user is a happy number or not

I know how to find the units and the highest number location, but got stack figure it out how to
how to use the digits in the middle in order to find the answer for that..

notice that the only class we've learned so fat is Math,(not even string yes)
we also learned while and for but nothing so far..

I also know that in order to go through all digit in given number i need to use the while loop,
but I dont know how do I use it in order to use them to get to the answer..

my code so far:

```<code>int number;
int units;
int highestDigitLoc;

bool isHappyNumber = true;
int count = 0;

Console.WriteLine("enter a number:");
number = int.Parse(Console.ReadLine());

while(number > 0)
{
    count++;

    units = number % 10;
    highestDigitLoc = number / 10;
}
</code>```

thanks

答:
This link explains what Happy Number's are in a simple way. Basically you have to keep suming the square of each digit present in the number, until the result equals 1. This proccess can go on indefinitely, but fortunately we know for certain that if the sum equals 4, it will never result in a Happy Number. Therefore, we can do the following:

```<code>private static bool IsHappy(int n)
{
    if (n == 1)
        return true;
    else if (n == 0 || n == 4)
        return false;
    else
        return IsHappy(SumDigitSquares(n));
}

private static int SumDigitSquares(int n)
{
    if (n < 10)
        return n * n;
    else
        return SumDigitSquares(n % 10) + SumDigitSquares(n / 10);
}
</code>```

Usage:

```<code>bool result = IsHappy(63240); //false
</code>```

Body:
Im trying to understund how do I find whether the number is Happy Number or not,
I know that i need to check if the unit digit and the digit in the highest number location are greater
then the numbers in the middele.
`example:
given number: 63240
the unit: 6
the number in the highest location:0
are both of them greater then 3 and 2 and4(middle) ? yes
result: true (for that case)

the quation is:
write a program that get a number from user, the program will print if the given number from the user is a happy number or not

I know how to find the units and the highest number location, but got stack figure it out how to
how to use the digits in the middle in order to find the answer for that..

notice that the only class we've learned so fat is Math,(not even string yes)
we also learned while and for but nothing so far..

I also know that in order to go through all digit in given number i need to use the while loop,
but I dont know how do I use it in order to use them to get to the answer..

my code so far:

int number;
int units;
int highestDigitLoc;

bool isHappyNumber = true;
int count = 0;

Console.WriteLine("enter a number:");
number = int.Parse(Console.ReadLine());

while(number > 0)
{
    count++;

    units = number % 10;
    highestDigitLoc = number / 10;
}

thanks

Body:
This link explains what Happy Number's are in a simple way. Basically you have to keep suming the square of each digit present in the number, until the result equals 1. This proccess can go on indefinitely, but fortunately we know for certain that if the sum equals 4, it will never result in a Happy Number. Therefore, we can do the following:

private static bool IsHappy(int n)
{
    if (n == 1)
        return true;
    else if (n == 0 || n == 4)
        return false;
    else
        return IsHappy(SumDigitSquares(n));
}

private static int SumDigitSquares(int n)
{
    if (n < 10)
        return n * n;
    else
        return SumDigitSquares(n % 10) + SumDigitSquares(n / 10);
}

Usage:

bool result = IsHappy(63240); //false


问:
How to display A B C D E if a input 5 numbers 1 2 3 4 5

import random
ltr =" ABCDEFGHIJKLMNOPQRSTUVWXYZ"
print(ltr.strip())
a = input('')
b = input('')
c = input('')
d = input('')
e = input('')
print(a,b,c,d,e)
var1 = random.randrange(1,26)
var2 = random.randrange(1,26)
var3 = random.randrange(1,26)
var4 = random.randrange(1,26)
var5 = random.randrange(1,26)
print(var1,var2,var3,var4,var5)
```

What I want to do is when I input numbers from 1 to 26 it should display a corresponding result. As you can see, the user must input 5 numbers. For example, if we input 1 2 3 4 5 the result must be A B C D E. Also, we have random numbers. For example, if our random numbers are 4 5 3 1 2 the result must be D E C A B.
I don't know what to do to display the result.

答:
```<code>random.randrange(1,26)
</code>```

This is wrong. Random's second parameter is non-inclusive, meaning you'll get numbers from 1 to 25.

You should use:

```<code>random.randrange(1, len(ltr))
</code>```

Then your result letter is just accessing the correct index in your ltr string - simply doing ltr(var1)

As for user input, you need to invert it to integer values like this:

```<code>a = int(input(''))
</code>```

Body:
import random
ltr =" ABCDEFGHIJKLMNOPQRSTUVWXYZ"
print(ltr.strip())
a = input('')
b = input('')
c = input('')
d = input('')
e = input('')
print(a,b,c,d,e)
var1 = random.randrange(1,26)
var2 = random.randrange(1,26)
var3 = random.randrange(1,26)
var4 = random.randrange(1,26)
var5 = random.randrange(1,26)
print(var1,var2,var3,var4,var5)

What I want to do is when I input numbers from 1 to 26 it should display a corresponding result. As you can see, the user must input 5 numbers. For example, if we input 1 2 3 4 5 the result must be A B C D E. Also, we have random numbers. For example, if our random numbers are 4 5 3 1 2 the result must be D E C A B.
I don't know what to do to display the result.

Body:
random.randrange(1,26)

This is wrong. Random's second parameter is non-inclusive, meaning you'll get numbers from 1 to 25.

You should use:

random.randrange(1, len(ltr))

Then your result letter is just accessing the correct index in your ltr string - simply doing ltr(var1)

As for user input, you need to invert it to integer values like this:

a = int(input(''))


问:
Authenticate users when login
I'm a beginner and I'm doing a Rails Tuturial https://www.learnenough.com/ruby-on-rails-6th-edition-tutorial/basic_login#sec-finding_and_authenticating_a_user>

Last lesson i create a new user and I'm verifying in the rails``console using booleans to prove if users email and password match to login session.

This is my code in the session controller file:

```<code>class SessionsController < ApplicationController

  def new
  end

  def create
     user = User.find_by(email: params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
    else
      render 'new'
    end
  end

  def destroy
  end
end
</code>```

And to verify in the rails console:

user = User.first

    => User id: 1, name: "Rails Tutorial", email: "example@railstutorial.org", created_at: "2020-02-13 01:04:12", updated_at: "2020-02-13 01:04:12", password_digest: [FILTERED]

!!(user && user.authenticate('railst1234'))

    => false

The question here is why returns FALSE if the email and password info. suppose to be right?

答:
I think that's because you are trying to authenticate an encrypted password but creating without given password_confirmation to user model. Here is a good link for understanding passwords on user.

This could also help you if you don't want encrypted passwords for user.

Title: Authenticate users when login

Body:
I'm a beginner and I'm doing a Rails Tuturial https://www.learnenough.com/ruby-on-rails-6th-edition-tutorial/basic_login#sec-finding_and_authenticating_a_user>

Last lesson i create a new user and I'm verifying in the rails``console using booleans to prove if users email and password match to login session.

This is my code in the session controller file:

class SessionsController < ApplicationController

  def new
  end

  def create
     user = User.find_by(email: params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
    else
      render 'new'
    end
  end

  def destroy
  end
end

And to verify in the rails console:

user = User.first

    => User id: 1, name: "Rails Tutorial", email: "example@railstutorial.org", created_at: "2020-02-13 01:04:12", updated_at: "2020-02-13 01:04:12", password_digest: [FILTERED]

!!(user && user.authenticate('railst1234'))

    => false

The question here is why returns FALSE if the email and password info. suppose to be right?


问:
Can CSS default font-size be changed by the user
mozilla says that
xx-small, x-small, small, medium, large, x-large, xx-large, xxx-large
Absolute-size keywords, based on the user's default font size (which is medium).

and medium is 16px by many sources

My question is: can this medium = 16px mapping be changed by the user? and what is the increment between these values? i.e. if medium is 16px and small is 14px?

答:
Medium is 16px, yes, that's the default, but can be changed, and the CSS keywords will be based on that new value. Here are a few examples (non-exhaustive):

On Firefox, go to about:preferences in General, you can adjust the font size in "Language and Appearance".

In Chrome, head to chrome://settings/, and in Appearance you have a "Font size" option.

Not too sure about Safari, probably linked to OS-level settings.

Mr Lister pointed out MS Edge doesn't have that option. Maybe that's OS-level as well. (I am able to set it in the new MS Edge though, released for Mac, since it now works pretty much like Chrome).


问:
How to fix npm installation CXX=clang++ --unsafe-perm
On an OSX machine - currently running Mojave - and I have a node and npm installation (or maybe more than one) where -i install can predictably not run unless CXX=clang++ is prefixed to the npm or npx command, and --unsafe-perm is suffixed to the command, and sometimes sudo is a further prefix

pretty much every instruction that should be as simple as npm install <package> turns into sudo CXX=clang++ npm install <package> --unsafe-perm and everything I've read suggests this is a last resort and is conceptually unsafe

Its a deep rabbit hole to understanding how I got to this point, but at this point I have many notes that remind me to do this. I've upgraded npm and node multiple times, as they evolve very quickly, I don't think their specific versions are important here, but instead an OSX nuance that I'm not convinced is actually relevant, or hope isn't really relevant.

also I have a hunch that yarn is a part of the problem, or maybe its because of some old installation instructions for npm or node? beats me!

but not really sure how to start, but I saw similar questions on stackoverflow, but not specifically how to fix this

I want to get back to the place where simply copying and pasting npm install instructions from readme's actually works without any other jerry rigging

答:
It's hard to know what it happening on your system. However, I prefer to install node.js in my $HOME

```<code>> mkdir -p ~/opt/usr/local/node
> cd ~/opt/usr/local/node
> curl -O https://nodejs.org/dist/v12.16.0/node-v12.16.0-darwin-x64.tar.gz
> tar zxf node-v12.16.0-darwin-x64.tar.gz
> export PATH=$HOME/opt/usr/local/node/node-v12.16.0-darwin-x64/bin:${PATH}
</code>```

and then, all node.js related activities are happening in my $HOME. This way I can avoid all the sudo, etc. stuff. I haven't (at least so far) noticed any major issues with this approach.

Body:
It's hard to know what it happening on your system. However, I prefer to install node.js in my $HOME

> mkdir -p ~/opt/usr/local/node
> cd ~/opt/usr/local/node
> curl -O https://nodejs.org/dist/v12.16.0/node-v12.16.0-darwin-x64.tar.gz
> tar zxf node-v12.16.0-darwin-x64.tar.gz
> export PATH=$HOME/opt/usr/local/node/node-v12.16.0-darwin-x64/bin:${PATH}

and then, all node.js related activities are happening in my $HOME. This way I can avoid all the sudo, etc. stuff. I haven't (at least so far) noticed any major issues with this approach.


问:
How to animate the command line?
I have always wondered how people update a previous line in a command line. a great example of this is when using the wget command in linux. It creates an ASCII loading bar of sorts that looks like this:

[======>                    ] 37%

and of course the loading bar moves and the percent changes, But it doesn't make a new line. I cannot figure out how to do this. Can someone point me in the right direction?

答:
There are two ways I know of to do this:

Use the backspace escape character ('\b') to erase your line

Use the curses package, if your programming language of choice has bindings for it.

And a Google revealed ANSI Escape Codes, which appear to be a good way. For reference, here is a function in C++ to do this:

```<code>void DrawProgressBar(int len, double percent) {
  cout << "\x1B[2K"; // Erase the entire current line.
  cout << "\x1B[0E"; // Move to the beginning of the current line.
  string progress;
  for (int i = 0; i < len; ++i) {
    if (i < static_cast<int>(len * percent)) {
      progress += "=";
    } else {
      progress += " ";
    }
  }
  cout << "[" << progress << "] " << (static_cast<int>(100 * percent)) << "%";
  flush(cout); // Required.
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to animate the command line?

Body:
There are two ways I know of to do this:

Use the backspace escape character ('\b') to erase your line

Use the curses package, if your programming language of choice has bindings for it.

And a Google revealed ANSI Escape Codes, which appear to be a good way. For reference, here is a function in C++ to do this:

void DrawProgressBar(int len, double percent) {
  cout << "\x1B[2K"; // Erase the entire current line.
  cout << "\x1B[0E"; // Move to the beginning of the current line.
  string progress;
  for (int i = 0; i < len; ++i) {
    if (i < static_cast<int>(len * percent)) {
      progress += "=";
    } else {
      progress += " ";
    }
  }
  cout << "[" << progress << "] " << (static_cast<int>(100 * percent)) << "%";
  flush(cout); // Required.
}

OwnerDisplayName: hazzen

LastEditorDisplayName: hazzen


问:
Which is best free distributable code to html converter
In my application, I have a requirement to convert Java/VB/VB.net/etc program to HTML, and then use that HTML page (to insert in Word doc).

Sure we can write code for this, but this will entail programming for this too, and from more than one programming languages, and dealing with bugs. Whereas it needs to be released ASAP. Using 3rd party tool for this HTML generation is not an issue.

However this 3rd party tool, code to html formatter, should be free, robust, and should convert upto Java 1.5, and other language's recent version.

Do you know of any such converter (code to html converter/formatter) which is free, distributable, robust, and converts upto recent versions of more than one languages (including Java)?

To elaborate further, I am interested in a utility which will take source code file as input, and will generate HTML file as output. The HTML file should not use javascript to color the code, because then inserting in Word the coloring will be lost.

答:
Pygments

Java example: http://pygments.org/demo/1476/

OwnerDisplayName: vikramsjn

LastEditorDisplayName: vikramsjn


问:
How to check root access in android?
I created a method for checking whether the android phone is rooted or not. This is done as follows

```<code>public int checkrootcommand(String string) {
    // TODO Auto-generated method stub
    Process exec;
    try {

        exec = Runtime.getRuntime().exec(new String[]{"su","-c"});

        final OutputStreamWriter out = new OutputStreamWriter(exec.getOutputStream());
        out.write("exit");
        out.flush();

        Log.i(SUPER_USER_COMMAND, "su command executed successfully");
        return 0; // returns zero when the command is executed successfully
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return 1; //returns one when the command execution fails
}
</code>```

But the problem is that the method checkrootcommand() is executed first it works perfectly, but when the same method called again the superuser session is still running. Is there any way to end the superuser session once the method is executed??

答:
You can achieve this from a terminal command and you can run terminal commands within an app.

```<code>if [ ! -z "$(/system/bin/ps -A | grep -v grep | grep -c daemonsu)" ]; then echo "device is rooted"; else echo "device is not rooted"; fi
</code>```

Your application also doesn't require root access this way.

ContentLicense: CC BY-SA 3.0

Title: How to check root access in android?

Body:
I created a method for checking whether the android phone is rooted or not. This is done as follows

public int checkrootcommand(String string) {
    // TODO Auto-generated method stub
    Process exec;
    try {

        exec = Runtime.getRuntime().exec(new String[]{"su","-c"});

        final OutputStreamWriter out = new OutputStreamWriter(exec.getOutputStream());
        out.write("exit");
        out.flush();

        Log.i(SUPER_USER_COMMAND, "su command executed successfully");
        return 0; // returns zero when the command is executed successfully
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return 1; //returns one when the command execution fails
}

But the problem is that the method checkrootcommand() is executed first it works perfectly, but when the same method called again the superuser session is still running. Is there any way to end the superuser session once the method is executed??

Body:
You can achieve this from a terminal command and you can run terminal commands within an app.

if [ ! -z "$(/system/bin/ps -A | grep -v grep | grep -c daemonsu)" ]; then echo "device is rooted"; else echo "device is not rooted"; fi

Your application also doesn't require root access this way.


问:
Dynamic load content with tooltip not working
I am beginner in JS. I have dynamic html load from php (jquery).
In result from php I have this html:

```<code><img title="Mleko" class="info-tooltip" style="max-height:15px" src="assets/ikonki/mleko.png">
<img title="Jaja" class="info-tooltip" style="max-height:15px" src="assets/ikonki/jajka.png">
</code>```

This is my tooltip code:

```<code><script type="text/javascript">
    $(document).ready(function () {
        $(".info-tooltip").tooltip({
            tooltipClass: "tooltip-styling",
            position: {
                my: "left bottom",
                at: "center top-10",
                collision: "none"
            }
        });
    });
</script>
</code>```

And tooltip is not working :( It's not showing.
I have in my page Bootstrap and jquery.

When I add this images normally, in html code - this work fine.

Problem is only with images (tooltip)  dynamic load from php.

How can I repair it?

答:
You say the first HTML example is dynamically loaded - I assume you mean that you're doing this using AJAX. As such you need to call .tooltip() on the new content after the AJAX request completes and the new HTML is added to the DOM.

To do this use a promise or the success callback, something like this:

$.ajax({
  url: '/yourpage',
  data: { foo: bar },
  success: function(html) {
    $('#container').append(html);

    // instantiate tooltips here...
    $("#container .info-tooltip").tooltip({
      tooltipClass: "tooltip-styling",
      position: {
        my: "left bottom",
        at: "center top-10",
        collision: "none"
      }
    });
  }
});```

Body:
I am beginner in JS. I have dynamic html load from php (jquery).
In result from php I have this html:

This is my tooltip code:

And tooltip is not working :( It's not showing.
I have in my page Bootstrap and jquery.

When I add this images normally, in html code - this work fine.

Problem is only with images (tooltip)  dynamic load from php.

How can I repair it?


答:
What you want to do is to print the letter in the alphabet which is at the position the user entered. In other words, the user enters the index of that letter inside the alphabet. Since you can access a character inside a string using its index in python using letter = string[index] you can do this:

```<code>ltr =" ABCDEFGHIJKLMNOPQRSTUVWXYZ"

a = input('')
b = input('')
c = input('')
d = input('')
e = input('')
print(a,b,c,d,e)
print(ltr[a], ltr[b], ltr[c], ltr[d], ltr[e])
</code>```

Note that due to the space at the start of ltr, A will be output when entering 1.

Edit: Update according to question in comments.
You can sort the inputs if you put them in a list and sort() them. Then you can get the characters at the positions from the input list:

```<code>ltr =" ABCDEFGHIJKLMNOPQRSTUVWXYZ"

inputs = []
for _ in range(5):
    inputs.append(int(input("Enter a number:")))

inputs.sort()
print(', '.join(map(str, inputs)))
print(', '.join(ltr[i] for i in inputs))
</code>```

Title: How to display A B C D E if a input 5 numbers 1 2 3 4 5

Body:
What you want to do is to print the letter in the alphabet which is at the position the user entered. In other words, the user enters the index of that letter inside the alphabet. Since you can access a character inside a string using its index in python using letter = string[index] you can do this:

ltr =" ABCDEFGHIJKLMNOPQRSTUVWXYZ"

a = input('')
b = input('')
c = input('')
d = input('')
e = input('')
print(a,b,c,d,e)
print(ltr[a], ltr[b], ltr[c], ltr[d], ltr[e])

Note that due to the space at the start of ltr, A will be output when entering 1.

Edit: Update according to question in comments.
You can sort the inputs if you put them in a list and sort() them. Then you can get the characters at the positions from the input list:

ltr =" ABCDEFGHIJKLMNOPQRSTUVWXYZ"

inputs = []
for _ in range(5):
    inputs.append(int(input("Enter a number:")))

inputs.sort()
print(', '.join(map(str, inputs)))
print(', '.join(ltr[i] for i in inputs))


问:
Linq (or SQL): Get a search query and sort it order by best result
I want to create a search page for my website. The logic is the user enters some keywords and I should search those words then sort the result by best matches.
i.e:
The user enters: "MVC Microsoft WPF ASP.Net".
I want to show those results which contain most matches, such as:

Best Matches:

Learning Microsoft ASP.Net MVC

How to host a WPF form in Microsoft ASP.Net

Partial matches:

Microsoft MVC

Microsoft WPF

Microsoft ASP.Net

ASP.Net MVC

Keyword Matches:

MVC

Microsoft

WPF

ASP.Net

答: Try out Lucene.NET, it sorts search results by relevance by default</p>


问:
Listenerconfigurations in the observation module of magnolia - best practices question
I would like to trigger a custom command that extends BaseRepositoryCommand when someone adds, removes or changes a node or property for mgnl:page, mgnl:area and mgnl:component node types.
I was thinking of using the magnolia observation module for this. Do I have to create separate listenerConfigurations for each node type and event type? In my case it would be 6 event-types for 3 node-types or 18 different
listenerConfigurations. Does that have implications on performance?

答:
Please have a look at: info.magnolia.cms.util.WorkspaceObservingManager

There you can use the method #registerChangeListener which you can specify the workspace you want to observe as well as the list of node types you wish.

Performance-wise, it should be smooth since it uses directly JCR observation mechanism under its hood.


问:
AutoMapper ProjectTo with DbContext multi level Include()
I need to perform multi level Include() query during EF Core select. I use AutoMapper with ProjectTo<>().

I have specified in mappings ExplicitExpansion() which means navigation properties will not be populated automatically, because I want to have possibility to execute the same query multiple times and
one time Include() navigation property but second time ignore it.

ProjectTo<>() method has params which allows me to include navigation properties into my select, but I need to perform multi level include. Is this possible? Such syntax like Include(e => e.Collection.Select(sc => sc.MyProperty)) not working in this case.

I tried to use Include().ThenInclude() for DbContext and then perform ProjectTo, but in that case ProjectTo overrides my includes and they are ignored.

Now I'm not sure if that's possible at all to have ProjectTo, ExplicitExpansion() specified in mapping and have multi level include?

答:
Did you try?

dbContext.Entities.ProjectTo<EntityDto>(dest => dest.Collection.Select(item => item.MyProperty));
```


问:
How to check current number of instances for Azure Application Gateway
I currently have an Azure Application Gateway that is configured for a minimum of 2 instances and a maximum of 10 instances. It's Tier is "WAF V2" and autoscaling is enabled.

If autoscaling is enabled, then theoretically there should be somewhere between 2 and 10 instances. So where can I go to check the current number of instances that the gateway has scaled up to? This seems like important information if you want to figure out if your gateway is overloaded.

答:
I've tried to obtain this value with Logs analytics.
Enable it and use this query:

```<code>AzureDiagnostics
| where TimeGenerated > ago(30m)
    | summarize dcount(instanceId_s) by bin(TimeGenerated, 1m)
</code>```

You will have the different request grouped by the distinct instance name every minute. Consider adding some additional filter to the query, since you may only be interested in certain types of events.

I think it can be a good approximation

Body:
I've tried to obtain this value with Logs analytics.
Enable it and use this query:

AzureDiagnostics
| where TimeGenerated > ago(30m)
    | summarize dcount(instanceId_s) by bin(TimeGenerated, 1m)

You will have the different request grouped by the distinct instance name every minute. Consider adding some additional filter to the query, since you may only be interested in certain types of events.

I think it can be a good approximation


问:
What's the name of the part of the URL before the query string?
Take the following URL: http://3.chart.apis.google.com/chart?cht=p&chd=t:1,2,3&chl=a|b|c&chs=300x100

It can be broken down as follows:

Protocol: http

Hostname: 3.chart.apis.google.com

Path: chart

Query: cht=p&chd=t:1,2,3&chl=a|b|c&chs=300x100

I'm looking for the name of the protocol, hostname and path? i.e. everything up to the query string.

答:
In terms of URI as specified by RFC 3986, the URI http://3.chart.apis.google.com/chart?cht=p&chd=t:1,2,3&chl=a|b|c&chs=300x100 consists of the following components:

http – scheme

//3.chart.apis.google.com/chart – hierarchical part

3.chart.apis.google.com – authority

3.chart.apis.google.com – host

/chart – path

cht=p&chd=t:1,2,3&chl=a|b|c&chs=300x100 – query


问:
Fetch all columns into one column oracle
How do i achieve to fetch all columns into one column.

I have below sample query

```<code>WITH da AS(
SELECT 'a' col1, 'b' col2, 'c' col3 FROM dual UNION ALL
SELECT '1' col1, '2' col1, '3' col1 FROM dual UNION ALL
SELECT 'x' col1, 'y' col1, 'z' col1 FROM dual
)
SELECT * FROM da;

//RESULTS

COL1|COL2|COL3|
----|----|----|
a   |b   |c   |
1   |2   |3   |
x   |y   |z   |
</code>```

But what i want is the result to be as below with | as the delimiter.

```<code>ONE_COL|
-------|
a|b|c  |
1|2|3  |
x|y|z  |
</code>```

My biggest problem is i don't know the column names, therefore i cant do as:

```<code>SELECT  col1||'|'||col2||'|'||col3 AS ONE_COL  FROM da;
</code>```

how can i do this.

答:
Concat the dual columns within the with clause, that way you don't need know what the da columns are called.</p>

```<code>WITH da AS(
SELECT 'a' || '|' || 'b' || '|' || 'c' AS one_col FROM dual UNION ALL
SELECT '1' || '|' || '2' || '|' || '3' AS one_col FROM dual UNION ALL
SELECT 'x' || '|' || 'y' || '|' || 'z' AS one_col FROM dual
)
SELECT * FROM da;
</code>```

Body:
How do i achieve to fetch all columns into one column.

I have below sample query

WITH da AS(
SELECT 'a' col1, 'b' col2, 'c' col3 FROM dual UNION ALL
SELECT '1' col1, '2' col1, '3' col1 FROM dual UNION ALL
SELECT 'x' col1, 'y' col1, 'z' col1 FROM dual
)
SELECT * FROM da;

//RESULTS

COL1|COL2|COL3|
----|----|----|
a   |b   |c   |
1   |2   |3   |
x   |y   |z   |

But what i want is the result to be as below with | as the delimiter.

ONE_COL|
-------|
a|b|c  |
1|2|3  |
x|y|z  |

My biggest problem is i don't know the column names, therefore i cant do as:

SELECT  col1||'|'||col2||'|'||col3 AS ONE_COL  FROM da;

how can i do this.

Body:
Concat the dual columns within the with clause, that way you don't need know what the da columns are called.

WITH da AS(
SELECT 'a' || '|' || 'b' || '|' || 'c' AS one_col FROM dual UNION ALL
SELECT '1' || '|' || '2' || '|' || '3' AS one_col FROM dual UNION ALL
SELECT 'x' || '|' || 'y' || '|' || 'z' AS one_col FROM dual
)
SELECT * FROM da;


问:
Save ID in variable and add style to it
I want to highlight randomly a word which is inside a
 tag with the id=JShighlight. It should blink one time and then another randomly chosen word should blink.** I can't add the css style needed to the ID.

The words are nested in a span with an unique id like id="one" oder id="two".
Like:

```<code><p id="JShighlight"> <span id="one">Lorem </span><span id="two">Ipsum </span><span id="three">Dolores</span></p>
</code>```

To chose a word randomly, I build an array with the child-nodes of JShighlight. And call it childNodeArray

```<code>let childNodeArray = document.getElementById('JShighlight').children;
</code>```

Then I randomly chose an index:

```<code>  let i = Math.floor(Math.random() * childNodeArray.length);
</code>```

The variable name saves the randomly chosen ID.

```<code>let name = childNodeArray[i].id;
</code>```

To this randomly chosen word /Id I want to add a certain style so that this word blinks one time.
I tried:

```<code>name.classList.add("blinking");
</code>```

(.blinking is the css-class:

```<code>.blinking {
    animation: blinkingText 0.6s 1;
    /* animation-iteration-count: 1; */
}
</code>```

)

But it does not work.
What "works" is:

```<code>document.getElementById(name).style.color = "red";
</code>```

Why can I pass a variable as an argument in the latter case and not in the former case?
How can I append a css class to an variable ID?

答:
In the first case, name is a string not an element.

what you can do is:

```<code>name = document.getElementById(name);
name.classList.add("blinking");
</code>```

Title: Save ID in variable and add style to it

Body:
I want to highlight randomly a word which is inside a
 tag with the id=JShighlight. It should blink one time and then another randomly chosen word should blink.** I can't add the css style needed to the ID.

The words are nested in a span with an unique id like id="one" oder id="two".
Like:

 Lorem Ipsum Dolores

To chose a word randomly, I build an array with the child-nodes of JShighlight. And call it childNodeArray

let childNodeArray = document.getElementById('JShighlight').children;

Then I randomly chose an index:

  let i = Math.floor(Math.random() * childNodeArray.length);

The variable name saves the randomly chosen ID.

let name = childNodeArray[i].id;

To this randomly chosen word /Id I want to add a certain style so that this word blinks one time.
I tried:

name.classList.add("blinking");

(.blinking is the css-class:

.blinking {
    animation: blinkingText 0.6s 1;
    /* animation-iteration-count: 1; */
}

)

But it does not work.
What "works" is:

document.getElementById(name).style.color = "red";

Why can I pass a variable as an argument in the latter case and not in the former case?
How can I append a css class to an variable ID?

Body:
In the first case, name is a string not an element.

what you can do is:

name = document.getElementById(name);
name.classList.add("blinking");


问:
Dollar prefixed field not valid for storage
I got this error:

```<code>panic: multiple write errors: [{write errors: [{The dollar ($) prefixed field '$set' in 'conversations.newest_message.$set' is not valid for storage.}]}, {<nil>}]
</code>```

Here is the data I want to update, and I want to update newest_message inside conversations:

```<code>{
    "_id" : "iNIXU8dgLgg-KdC3FE1hX8qBpY44hTF-2m-h-RG1",
    "conversations" : [
        {
            "conversation_id" : "VOoHg7nY4xBcrQtzxokbM9aStSSqei44",
            "newest_message" : {
                "user_name" : "",
                "data" : {
                    "description" : "",
                },
            }
        }
    ]
}
</code>```

Here is the mongoldb query:

```<code>db.collectionA.update(
    {
        _id: "iNIXU8dgLgg-KdC3FE1hX8qBpY44hTF-2m-h-RG1",
        "conversations.conversation_id": "VOoHg7nY4xBcrQtzxokbM9aStSSqei44"
    },
    {
        "$set": {
            "conversations.$.newest_message": {new_update_data_here}
    }
)
</code>```

and here is the Golang code, I'm using mongodb driver not mgo:

```<code>filter = bson.M{
                    "_id":                           id,
                    "conversations.conversation_id": messageReceived.ConversationID,
                }
update = bson.M{
                    "$set": bson.M{
                        "conversations": bson.M{
                            "newest_message": newestMessage,
                        },
                    },
                }

_, err = d.DB.Collection(collectionUserInformation).UpdateOne(ctx, filter, update)
            if err != nil {
                panic(err)
            }
</code>```

答:
Using as initial document the one from the example:

```<code>{
        "_id" : "iNIXU8dgLgg-KdC3FE1hX8qBpY44hTF-2m-h-RG1",
        "settings" : {
                "general" : {
                        "languages" : [
                                {
                                        "label" : "English",
                                        "value" : "eng"
                                }
                        ],
                        "contact" : "No one",
                        "language" : [
                                {
                                        "label" : "English",
                                        "value" : "eng"
                                },
                                {
                                        "label" : "English",
                                        "value" : "eng"
                                }
                        ]
                },
                "block_list" : [
                        "qGXVFjeZeFwrZjURfcZHqkCbgO91Gbu87KXx3Ba5",
                        "hFkF7DjPwBB6G2qbNT0J1ZROd3rxNLrZ5zt-HmMK"
                ],
                "auto_reply" : {
                        "set_auto_reply" : false,
                        "auto_reply_messages" : [ ]
                }
        },
        "conversations" : [
                {
                        "conversation_id" : "VOoHg7nY4xBcrQtzxokbM9aStSSqei44",
                        "people" : [
                                {
                                        "user_id" : "iNIXU8dgLgg-KdC3FE1hX8qBpY44hTF-2m-h-RG1",
                                        "user_name" : "Dat Vo"
                                },
                                {
                                        "user_id" : "qGXVFjeZeFwrZjURfcZHqkCbgO91Gbu87KXx3Ba5",
                                        "user_name" : "An Son"
                                }
                        ],
                        "newest_message" : {
                                "user_name" : "",
                                "data" : {
                                        "description" : "",
                                        "host" : "",
                                        "image" : "",
                                        "title" : "",
                                        "type" : "",
                                        "url" : "",
                                        "youtube_video_id" : ""
                                },
                                "seen" : false
                        }
                }
        ]
}
</code>```

you can replace newest_message element inside the conversations array using $set and the $ positional operator:

update := bson.M{ "$set": bson.M{
          "conversations.$.newest_message": bson.M{...

```<code>ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()

filter := bson.M{
    "_id":                           "iNIXU8dgLgg-KdC3FE1hX8qBpY44hTF-2m-h-RG1",
    "conversations.conversation_id": "VOoHg7nY4xBcrQtzxokbM9aStSSqei44",
}
update := bson.M{
    "$set": bson.M{
        "conversations.$.newest_message": bson.M{
            "message_id": "saisa",
            "user_id":    "iNIXU8dgLgg-KdC3FE1hX8qBpY44hTF-2m-h-RG1",
            "user_name":  "Dat Vo",
            "content":    "this is the new msg",
            "created_at": "12345678",
            "seen":       false,
        },
    },
}

_, err2 := d.DB.Collection(collectionUserInformation).UpdateOne(ctx, filter, update)
if err2 != nil {
    panic(err2)
}
</code>```

It will return the following updated document:

```<code>{
        "_id" : "iNIXU8dgLgg-KdC3FE1hX8qBpY44hTF-2m-h-RG1",
        "settings" : {
                "general" : {
                        "languages" : [
                                {
                                        "label" : "English",
                                        "value" : "eng"
                                }
                        ],
                        "contact" : "No one",
                        "language" : [
                                {
                                        "label" : "English",
                                        "value" : "eng"
                                },
                                {
                                        "label" : "English",
                                        "value" : "eng"
                                }
                        ]
                },
                "block_list" : [
                        "qGXVFjeZeFwrZjURfcZHqkCbgO91Gbu87KXx3Ba5",
                        "hFkF7DjPwBB6G2qbNT0J1ZROd3rxNLrZ5zt-HmMK"
                ],
                "auto_reply" : {
                        "set_auto_reply" : false,
                        "auto_reply_messages" : [ ]
                }
        },
        "conversations" : [
                {
                        "conversation_id" : "VOoHg7nY4xBcrQtzxokbM9aStSSqei44",
                        "people" : [
                                {
                                        "user_id" : "iNIXU8dgLgg-KdC3FE1hX8qBpY44hTF-2m-h-RG1",
                                        "user_name" : "Dat Vo"
                                },
                                {
                                        "user_id" : "qGXVFjeZeFwrZjURfcZHqkCbgO91Gbu87KXx3Ba5",
                                        "user_name" : "An Son"
                                }
                        ],
                        "newest_message" : {
                                "created_at" : "12345678",
                                "seen" : false,
                                "message_id" : "saisa",
                                "user_id" : "iNIXU8dgLgg-KdC3FE1hX8qBpY44hTF-2m-h-RG1",
                                "user_name" : "Dat Vo",
                                "content" : "this is the new msg"
                        }
                }
        ]
}
</code>```

Your previous attempt was replacing the conversations array for a document with one doc conversations that contained just newest_message. You want to use the $set operator with the positional $ operator providing the full path so it just replaces the sub-document you want.

Body:
I got this error:

panic: multiple write errors: [{write errors: [{The dollar ($) prefixed field '$set' in 'conversations.newest_message.$set' is not valid for storage.}]}, {<nil>}]

Here is the data I want to update, and I want to update newest_message inside conversations:

{
    "_id" : "iNIXU8dgLgg-KdC3FE1hX8qBpY44hTF-2m-h-RG1",
    "conversations" : [
        {
            "conversation_id" : "VOoHg7nY4xBcrQtzxokbM9aStSSqei44",
            "newest_message" : {
                "user_name" : "",
                "data" : {
                    "description" : "",
                },
            }
        }
    ]
}

Here is the mongoldb query:

db.collectionA.update(
    {
        _id: "iNIXU8dgLgg-KdC3FE1hX8qBpY44hTF-2m-h-RG1",
        "conversations.conversation_id": "VOoHg7nY4xBcrQtzxokbM9aStSSqei44"
    },
    {
        "$set": {
            "conversations.$.newest_message": {new_update_data_here}
    }
)

and here is the Golang code, I'm using mongodb driver not mgo:

filter = bson.M{
                    "_id":                           id,
                    "conversations.conversation_id": messageReceived.ConversationID,
                }
update = bson.M{
                    "$set": bson.M{
                        "conversations": bson.M{
                            "newest_message": newestMessage,
                        },
                    },
                }

_, err = d.DB.Collection(collectionUserInformation).UpdateOne(ctx, filter, update)
            if err != nil {
                panic(err)
            }

Body:
Using as initial document the one from the example:

{
        "_id" : "iNIXU8dgLgg-KdC3FE1hX8qBpY44hTF-2m-h-RG1",
        "settings" : {
                "general" : {
                        "languages" : [
                                {
                                        "label" : "English",
                                        "value" : "eng"
                                }
                        ],
                        "contact" : "No one",
                        "language" : [
                                {
                                        "label" : "English",
                                        "value" : "eng"
                                },
                                {
                                        "label" : "English",
                                        "value" : "eng"
                                }
                        ]
                },
                "block_list" : [
                        "qGXVFjeZeFwrZjURfcZHqkCbgO91Gbu87KXx3Ba5",
                        "hFkF7DjPwBB6G2qbNT0J1ZROd3rxNLrZ5zt-HmMK"
                ],
                "auto_reply" : {
                        "set_auto_reply" : false,
                        "auto_reply_messages" : [ ]
                }
        },
        "conversations" : [
                {
                        "conversation_id" : "VOoHg7nY4xBcrQtzxokbM9aStSSqei44",
                        "people" : [
                                {
                                        "user_id" : "iNIXU8dgLgg-KdC3FE1hX8qBpY44hTF-2m-h-RG1",
                                        "user_name" : "Dat Vo"
                                },
                                {
                                        "user_id" : "qGXVFjeZeFwrZjURfcZHqkCbgO91Gbu87KXx3Ba5",
                                        "user_name" : "An Son"
                                }
                        ],
                        "newest_message" : {
                                "user_name" : "",
                                "data" : {
                                        "description" : "",
                                        "host" : "",
                                        "image" : "",
                                        "title" : "",
                                        "type" : "",
                                        "url" : "",
                                        "youtube_video_id" : ""
                                },
                                "seen" : false
                        }
                }
        ]
}

you can replace newest_message element inside the conversations array using $set and the $ positional operator:

update := bson.M{ "$set": bson.M{
          "conversations.$.newest_message": bson.M{...

ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()

filter := bson.M{
    "_id":                           "iNIXU8dgLgg-KdC3FE1hX8qBpY44hTF-2m-h-RG1",
    "conversations.conversation_id": "VOoHg7nY4xBcrQtzxokbM9aStSSqei44",
}
update := bson.M{
    "$set": bson.M{
        "conversations.$.newest_message": bson.M{
            "message_id": "saisa",
            "user_id":    "iNIXU8dgLgg-KdC3FE1hX8qBpY44hTF-2m-h-RG1",
            "user_name":  "Dat Vo",
            "content":    "this is the new msg",
            "created_at": "12345678",
            "seen":       false,
        },
    },
}

_, err2 := d.DB.Collection(collectionUserInformation).UpdateOne(ctx, filter, update)
if err2 != nil {
    panic(err2)
}

It will return the following updated document:

{
        "_id" : "iNIXU8dgLgg-KdC3FE1hX8qBpY44hTF-2m-h-RG1",
        "settings" : {
                "general" : {
                        "languages" : [
                                {
                                        "label" : "English",
                                        "value" : "eng"
                                }
                        ],
                        "contact" : "No one",
                        "language" : [
                                {
                                        "label" : "English",
                                        "value" : "eng"
                                },
                                {
                                        "label" : "English",
                                        "value" : "eng"
                                }
                        ]
                },
                "block_list" : [
                        "qGXVFjeZeFwrZjURfcZHqkCbgO91Gbu87KXx3Ba5",
                        "hFkF7DjPwBB6G2qbNT0J1ZROd3rxNLrZ5zt-HmMK"
                ],
                "auto_reply" : {
                        "set_auto_reply" : false,
                        "auto_reply_messages" : [ ]
                }
        },
        "conversations" : [
                {
                        "conversation_id" : "VOoHg7nY4xBcrQtzxokbM9aStSSqei44",
                        "people" : [
                                {
                                        "user_id" : "iNIXU8dgLgg-KdC3FE1hX8qBpY44hTF-2m-h-RG1",
                                        "user_name" : "Dat Vo"
                                },
                                {
                                        "user_id" : "qGXVFjeZeFwrZjURfcZHqkCbgO91Gbu87KXx3Ba5",
                                        "user_name" : "An Son"
                                }
                        ],
                        "newest_message" : {
                                "created_at" : "12345678",
                                "seen" : false,
                                "message_id" : "saisa",
                                "user_id" : "iNIXU8dgLgg-KdC3FE1hX8qBpY44hTF-2m-h-RG1",
                                "user_name" : "Dat Vo",
                                "content" : "this is the new msg"
                        }
                }
        ]
}

Your previous attempt was replacing the conversations array for a document with one doc conversations that contained just newest_message. You want to use the $set operator with the positional $ operator providing the full path so it just replaces the sub-document you want.


问:
can't write dockerfile with installations of ubuntu, numpy, opencv
the plan is to deploy pretrained face recog-n model. But before i need to install some libs.

The idea behind docker is that it brings all the needed libs and builds entire 'env' without much overhead. One can just start dockerfile and it runs all other scripts in turn.

libs to install:

Ubuntu 16.04.6 LTS

Python 3.6.10 (3.5.x should be fine also)

OpenCV 3.3.

NumPy

imutils https://github.com/jrosebr1/imutils

dlib http://dlib.net/

face_recognition https://github.com/ageitgey/face_recognition

i m trying to use curl to download pkgs from URLs, but it's not working.

my dockerfile:

```<code>FROM ubuntu:16.04.6

RUN apt-get update && apt-get install -y curl bzip2
    curl -o numpy
    && sudo apt-get install numpy
    && curl install imutils https://github.com/jrosebr1/imutils
    && curl install dlib https://dlib.net
    && sudo git clone https://github.com/ageitgey/face_recognition.git
    && curl python-opencv https://opencv.org/
    && echo 'export PATH="~/anaconda3/bin:$PATH"' >> ~/.bashrc \
    &&  ~/anaconda3/bin/conda update -n base conda \
    &&  rm miniconda_install.sh \
    &&  rm -rf /var/lib/apt/lists/* \
    &&  /bin/bash -c "source ~/.bashrc"

ENV PATH="~/anaconda3/bin:${PATH}"

##################################################
#    Setup env for current project:
##################################################

EXPOSE 8000

RUN /bin/bash -c "conda create -y -n PYMODEL3.6"

ADD requirements.txt /tmp/setup/requirements.txt

RUN /bin/bash -c "source activate PYMODEL3.6 && pip install -r /tmp/setup/requirements.txt"

WORKDIR /Service

ADD Service /Service

ENTRYPOINT ["/bin/bash", "-c", "source activate PYMODEL3.6 && ./run.sh"]
</code>```

the face model is pretrained.
there are 2 python files that do actual detection, 128d encoding and recognition.
the usage is like this:

```<code>#detect face, if there is face - encode it, return pickle
python3 encode.py --dataset dataset_id --encodings encodings.pickle
--confidence 0.9

#recognize using pickle
python3 face_recognizer.py --encodings encodings.pickle --image
dataset_webcam/3_1.jpg --confidence 0.9 --tolerance 0.5
</code>```

should I include them in the dockerfile?

答:
I would propose you to use a Dockerfile like the following, assuming you have all your requirements (numpy, imutils, etc...) inside your requirements.txt file, and your encode.py and face_recognizer.py files in your Service folder:

```<code>FROM python:3.6.10

RUN mkdir /tmp/setup

ADD requirements.txt /tmp/setup/requirements.txt

RUN pip install --no-cache-dir --upgrade setuptools && \
    pip install --no-cache-dir --upgrade pip && \
    pip install --no-cache-dir -r /tmp/setup/requirements.txt

WORKDIR /Service

ADD Service /Service/

CMD ["./run.sh"]

EXPOSE 8000
</code>```

Body:
the plan is to deploy pretrained face recog-n model. But before i need to install some libs.

The idea behind docker is that it brings all the needed libs and builds entire 'env' without much overhead. One can just start dockerfile and it runs all other scripts in turn.

libs to install:

Ubuntu 16.04.6 LTS

Python 3.6.10 (3.5.x should be fine also)

OpenCV 3.3.

NumPy

imutils https://github.com/jrosebr1/imutils

dlib http://dlib.net/

face_recognition https://github.com/ageitgey/face_recognition

i m trying to use curl to download pkgs from URLs, but it's not working.

my dockerfile:

FROM ubuntu:16.04.6

RUN apt-get update && apt-get install -y curl bzip2
    curl -o numpy
    && sudo apt-get install numpy
    && curl install imutils https://github.com/jrosebr1/imutils
    && curl install dlib https://dlib.net
    && sudo git clone https://github.com/ageitgey/face_recognition.git
    && curl python-opencv https://opencv.org/
    && echo 'export PATH="~/anaconda3/bin:$PATH"' >> ~/.bashrc \
    &&  ~/anaconda3/bin/conda update -n base conda \
    &&  rm miniconda_install.sh \
    &&  rm -rf /var/lib/apt/lists/* \
    &&  /bin/bash -c "source ~/.bashrc"

ENV PATH="~/anaconda3/bin:${PATH}"

##################################################
#    Setup env for current project:
##################################################

EXPOSE 8000

RUN /bin/bash -c "conda create -y -n PYMODEL3.6"

ADD requirements.txt /tmp/setup/requirements.txt

RUN /bin/bash -c "source activate PYMODEL3.6 && pip install -r /tmp/setup/requirements.txt"

WORKDIR /Service

ADD Service /Service

ENTRYPOINT ["/bin/bash", "-c", "source activate PYMODEL3.6 && ./run.sh"]

the face model is pretrained.
there are 2 python files that do actual detection, 128d encoding and recognition.
the usage is like this:

#detect face, if there is face - encode it, return pickle
python3 encode.py --dataset dataset_id --encodings encodings.pickle
--confidence 0.9

#recognize using pickle
python3 face_recognizer.py --encodings encodings.pickle --image
dataset_webcam/3_1.jpg --confidence 0.9 --tolerance 0.5

should I include them in the dockerfile?

Body:
I would propose you to use a Dockerfile like the following, assuming you have all your requirements (numpy, imutils, etc...) inside your requirements.txt file, and your encode.py and face_recognizer.py files in your Service folder:

FROM python:3.6.10

RUN mkdir /tmp/setup

ADD requirements.txt /tmp/setup/requirements.txt

RUN pip install --no-cache-dir --upgrade setuptools && \
    pip install --no-cache-dir --upgrade pip && \
    pip install --no-cache-dir -r /tmp/setup/requirements.txt

WORKDIR /Service

ADD Service /Service/

CMD ["./run.sh"]

EXPOSE 8000