问:
Why am I getting a NaN error when multiplying two numbers?
My getPercentage function works perfectly, but my getPayment function doesn't even though it's written exactly the same. When I click the "Get Payment" button it returns "NaN" on my HTML.

var taxes = {
  getPercentage: function(total, payment) {
   var percentage = (payment / total) * 100;
   return percentage;
   },
  getPayment: function(total, rate) {
    var payment = (total*rate);
    return payment;
    }
  };

var handlers = {
  getPercentage: function() {
    var totalInput = document.getElementById('totalInput');
    var paymentInput = document.getElementById('paymentInput');
    var answer = taxes.getPercentage(totalInput.value, paymentInput.value);
    getPercentageAnswer.innerHTML = answer;
  },
  getPayment: function() {
    var totalInputTwo = document.getElementById('totalInputTwo');
    var rateInput = document.getElementById("rateInput");
    var answer = taxes.getPayment(totalInputTwo.value, rateInput.value);
    getPaymentAnswer.innerHTML = answer;
  }
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="getPayment">
  <div id="totalTwo">
        Total owed:
    <input id="totalInputTwo" type="text">
  </div>
<div id="rateInput">
      Your tax rate (as a decimal):
  <input id="rateInput" type="text">
  </div>
  <button onclick="handlers.getPayment()">Get payment</button>
  <p id="getPaymentAnswer"></p>
</div></code>```

答:
You should add some validation to your input before doing some calculations.
Validations like:

Checking if input is number and if not number then what to show to the user in such cases.

If input is empty and then user clicks button to calculate result.

You should handle these situations first, then your code will work better.

The bug in code is solved by @adiga, but I am providing one of the ways t validate input:

var taxes = {
  getPayment: function(total, rate) {
    var payment = (total * rate);
    return payment;
  }
};

var isNumber = function(value) {
  return /^\d+$/.test(value.trim())
}

var handlers = {
  getPayment: function() {
    var totalInputTwo = document.getElementById('totalInputTwo');
    var rateInput = document.getElementById("rateInput");

    // validating code
    var totalInputTwo_value = totalInputTwo.value.trim()
    if(isNumber(totalInputTwo.value) && isNumber(rateInput.value)) {
        var answer = taxes.getPayment(totalInputTwo.value, rateInput.value);
       getPaymentAnswer.innerHTML = answer;
    } else {
      alert("Input is not number of empty. Please check!");
    }
    // console.log(typeof totalInputTwo.value);

  }
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div id="getPayment">
  <div id="totalTwo">
    Total owed:
    <input id="totalInputTwo" type="text">
  </div>
  <div id="rate">
    Your tax rate (as a decimal):
    <input id="rateInput" type="text">
  </div>
  <button onclick="handlers.getPayment()">Get payment</button>
  <p id="getPaymentAnswer"></p>
</div></code>```

Body:
My getPercentage function works perfectly, but my getPayment function doesn't even though it's written exactly the same. When I click the "Get Payment" button it returns "NaN" on my HTML.

var taxes = {
  getPercentage: function(total, payment) {
   var percentage = (payment / total) * 100;
   return percentage;
   },
  getPayment: function(total, rate) {
    var payment = (total*rate);
    return payment;
    }
  };

var handlers = {
  getPercentage: function() {
    var totalInput = document.getElementById('totalInput');
    var paymentInput = document.getElementById('paymentInput');
    var answer = taxes.getPercentage(totalInput.value, paymentInput.value);
    getPercentageAnswer.innerHTML = answer;
  },
  getPayment: function() {
    var totalInputTwo = document.getElementById('totalInputTwo');
    var rateInput = document.getElementById("rateInput");
    var answer = taxes.getPayment(totalInputTwo.value, rateInput.value);
    getPaymentAnswer.innerHTML = answer;
  }
};

        Total owed:
    <input id="totalInputTwo" type="text">

      Your tax rate (as a decimal):
  <input id="rateInput" type="text">

  <button onclick="handlers.getPayment()">Get payment</button>

Body:
You should add some validation to your input before doing some calculations.
Validations like:

Checking if input is number and if not number then what to show to the user in such cases.

If input is empty and then user clicks button to calculate result.

You should handle these situations first, then your code will work better.

The bug in code is solved by @adiga, but I am providing one of the ways t validate input:

var taxes = {
  getPayment: function(total, rate) {
    var payment = (total * rate);
    return payment;
  }
};

var isNumber = function(value) {
  return /^\d+$/.test(value.trim())
}

var handlers = {
  getPayment: function() {
    var totalInputTwo = document.getElementById('totalInputTwo');
    var rateInput = document.getElementById("rateInput");

    // validating code
    var totalInputTwo_value = totalInputTwo.value.trim()
    if(isNumber(totalInputTwo.value) && isNumber(rateInput.value)) {
        var answer = taxes.getPayment(totalInputTwo.value, rateInput.value);
       getPaymentAnswer.innerHTML = answer;
    } else {
      alert("Input is not number of empty. Please check!");
    }
    // console.log(typeof totalInputTwo.value);

  }
};

  <div id="getPayment">
  <div id="totalTwo">
    Total owed:
    <input id="totalInputTwo" type="text">
  </div>
  <div id="rate">
    Your tax rate (as a decimal):
    <input id="rateInput" type="text">
  </div>
  <button onclick="handlers.getPayment()">Get payment</button>
  <p id="getPaymentAnswer"></p>
</div>


来源: stackexchange

问:
How to validate only part of a value I'm getting through a get request?
I want to get two values from a get request, and then I'll use explode to retrieve each of them separately. However, this means that the value I'm getting before using explode isn't unique to the table (since it's a compound, and therefore it's not an existing value in the table). How can use validate to avoid duplicate of it ?

I tried making the column unique using an SQL constraint, however this means I get an exception page when a user enters a duplicate. I would like to use validation instead so I get an error message.

```<code>public function store(Request $request)
    {
        $this->validate($request, [
            'idProduit' => 'unique:stocks',
            'produit' => 'required|unique:stocks',
            'quantite' => 'required'
        ]);
        $produit = explode("|",$request->get('produit'));
        $stock = new Stock;
        $stock->idProduit = $produit[0];
        $stock->produit = $produit[1];
        $stock->quantite = $request->input('quantite');
        $stock->save();

        return redirect('/stocks/')->with('success', 'Entrée de stock ajoutée à la base de données');
    }
</code>```

I don't actually get any error message, but it is allowing me to add duplicates in the database, which I know why : the value is a compound that doesn't exist in the database, and so the unique validation I wrote cannot catch duplicate on just a part of it.

答:
Easy way : Explode before validation and make new $request with 2 more fields . Thats Over !!

```<code>public function store(Request $request)
{
    $produit = explode("|",$request->get('produit'));
    $request->request->add(['idProduit' => $produit[0]]);
    $request->request->add(['produit' => $produit[1]]);

    $this->validate($request, [
        'idProduit' => 'unique:stocks',
        'produit' => 'required|unique:stocks',
        'quantite' => 'required'
    ]);

    $stock = new Stock;
    $stock->idProduit = $produit[0];
    $stock->produit = $produit[1];
    $stock->quantite = $request->input('quantite');
    $stock->save();

    return redirect('/stocks/')->with('success', 'Entrée de stock ajoutée à la base de données');
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to get two values from a get request, and then I'll use explode to retrieve each of them separately. However, this means that the value I'm getting before using explode isn't unique to the table (since it's a compound, and therefore it's not an existing value in the table). How can use validate to avoid duplicate of it ?

I tried making the column unique using an SQL constraint, however this means I get an exception page when a user enters a duplicate. I would like to use validation instead so I get an error message.

public function store(Request $request)
    {
        $this->validate($request, [
            'idProduit' => 'unique:stocks',
            'produit' => 'required|unique:stocks',
            'quantite' => 'required'
        ]);
        $produit = explode("|",$request->get('produit'));
        $stock = new Stock;
        $stock->idProduit = $produit[0];
        $stock->produit = $produit[1];
        $stock->quantite = $request->input('quantite');
        $stock->save();

        return redirect('/stocks/')->with('success', 'Entrée de stock ajoutée à la base de données');
    }

I don't actually get any error message, but it is allowing me to add duplicates in the database, which I know why : the value is a compound that doesn't exist in the database, and so the unique validation I wrote cannot catch duplicate on just a part of it.

Body:
Easy way : Explode before validation and make new $request with 2 more fields . Thats Over !!

public function store(Request $request)
{
    $produit = explode("|",$request->get('produit'));
    $request->request->add(['idProduit' => $produit[0]]);
    $request->request->add(['produit' => $produit[1]]);

    $this->validate($request, [
        'idProduit' => 'unique:stocks',
        'produit' => 'required|unique:stocks',
        'quantite' => 'required'
    ]);

    $stock = new Stock;
    $stock->idProduit = $produit[0];
    $stock->produit = $produit[1];
    $stock->quantite = $request->input('quantite');
    $stock->save();

    return redirect('/stocks/')->with('success', 'Entrée de stock ajoutée à la base de données');
}


问:
How do I get the IP address of the server a request is coming from?
How do I get the IP address of the server a request is coming from. Here's a scenario;

I have two servers - client|server. How can I detect the IP of the client server in perl

答: You need getpeername. Please look up your perldoc.

ContentLicense: CC BY-SA 3.0


问:
Can jhipster export-jdl export entire application?
I have a jhipster app that I created with various specific options e.g. monolith, mysql etc etc, can I export this entire stack for someone else to use or is it just able to export the entity relationships ?</p>

答: Check the .yo-rc.json file in your project root. There are stored options that you mentioned, like application or DB type


问:
Indenting HTML tags on multiple lines
I can't find a guideline on how to indent HTML tags on multiple line, and the solution I am currently using doesn't really satisfy me.

Imagine we have an extremely long div declaration, such as:

```<code><div data-something data-something-else data-is-html="true" class="html-class another-html-class yet-another-html-class a-class-that-makes-this-declaration-extremely-long" id="just-a-regular-id">
</code>```

In order to avoid scrolling horizontally when I find these huge lines, I usually indent them in the following way:

```<code><div
    data-something
    data-something-else
    data-is-html="true"
    class="html-class another-html-class yet-another-html-class a-class-that-makes-
    this-declaration-extremely-long"
    id="just-a-regular-id"
>
    <p>Some element inside the DIV</p>
</div>
</code>```

Which I think works pretty well in terms of readability, but I have some concern.

Is this way considered a good practice?

Would you find more readable to leave the closing > in the opening HTML Tag inline with the last element, or on a new line as I did in the example above?

Do you have any other preferred way to deal with extremely long HTML declaration?

Feel free to share if you know some good resource about style guidelines for HTML that cover this special case, because I didn't find anything specific online.

答:
The Google HTML/CSS Style Guide suggests wrapping long lines when it significantly improves readability, and offers three techniques, each of which include the closing > with the last line of attributes:

Break long lines into multiple lines of acceptable length:

```<code><div class="my-class" id="my-id" data-a="my value for data attribute a"
    data-b="my value for data attribute b" data-c="my value for data attribute c">
    The content of my div.
</div>
</code>```

Break long lines by placing each attribute on its own indented line:

```<code><div
    class="my-class"
    id="my-id"
    data-a="my value for data attribute a"
    data-b="my value for data attribute b"
    data-c="my value for data attribute c">
    The content of my div.
</div>
</code>```

Similar to #2 except the first attribute is on the initial line, and subsequent attributes are indented to match the first attribute:

```<code><element-with-long-name class="my-class"
                        id="my-id"
                        data-a="my value for data attribute a"
                        data-b="my value for data attribute b"
                        data-c="my value for data attribute c">
</element-with-long-name>
</code>```

In my opinion, #3 would not improve readability when the element contains content.

Title: Indenting HTML tags on multiple lines

Body:
I can't find a guideline on how to indent HTML tags on multiple line, and the solution I am currently using doesn't really satisfy me.

Imagine we have an extremely long div declaration, such as:

In order to avoid scrolling horizontally when I find these huge lines, I usually indent them in the following way:

Some element inside the DIV

Which I think works pretty well in terms of readability, but I have some concern.

Is this way considered a good practice?

Would you find more readable to leave the closing > in the opening HTML Tag inline with the last element, or on a new line as I did in the example above?

Do you have any other preferred way to deal with extremely long HTML declaration?

Feel free to share if you know some good resource about style guidelines for HTML that cover this special case, because I didn't find anything specific online.

Body:
The Google HTML/CSS Style Guide suggests wrapping long lines when it significantly improves readability, and offers three techniques, each of which include the closing > with the last line of attributes:

Break long lines into multiple lines of acceptable length:

<div class="my-class" id="my-id" data-a="my value for data attribute a"
    data-b="my value for data attribute b" data-c="my value for data attribute c">
    The content of my div.
</div>

Break long lines by placing each attribute on its own indented line:

<div
    class="my-class"
    id="my-id"
    data-a="my value for data attribute a"
    data-b="my value for data attribute b"
    data-c="my value for data attribute c">
    The content of my div.
</div>

Similar to #2 except the first attribute is on the initial line, and subsequent attributes are indented to match the first attribute:

<element-with-long-name class="my-class"
                        id="my-id"
                        data-a="my value for data attribute a"
                        data-b="my value for data attribute b"
                        data-c="my value for data attribute c">
</element-with-long-name>

In my opinion, #3 would not improve readability when the element contains content.


问:
PivotFilters.add no longer working in my spreadsheet
This code has always worked in the past. Nothing has changed in the workbook and I have verified that all referenced data is formatted correctly.  Any idea what would have "broken" this?  It no longer applies the "between" filter to the dates in the pivot tables.

Verified pivot tables work when manually altered.  Checked fields in data table to make sure nothing has changed and there is no corrupt data entered.

```<code>    StartDate = Sheet17.Range("D5").Value
    EndDate = Sheet17.Range("D6").Value

    Set pt = Sheet6.PivotTables(1)
    Set ptF1 = pt.PivotFields("Est closing Date")

    ptF1.ClearAllFilters
    ptF1.PivotFilters.Add _
        Type:=xlDateBetween, Value1:=StartDate, Value2:=EndDate

    Sheet17.Range("M10:Q999").ClearContents
    pt.TableRange1.Offset(4, 0).Copy
    Sheet17.Cells(10, 13).PasteSpecial xlPasteValues

    Set pt = Sheet6.PivotTables(2)
    Set ptF1 = pt.PivotFields("Funds Date")

    ptF1.ClearAllFilters
    ptF1.PivotFilters.Add _
        Type:=xlDateBetween, Value1:=StartDate, Value2:=EndDate

    Sheet17.Range("A10:E999").ClearContents
    'omit copying the top row of the PivotTable:
    pt.TableRange2.Offset(4, 0).Copy
    Sheet17.Cells(10, 1).PasteSpecial xlPasteValues

    'Fill in dates
    For ii = 11 To 100
        If (Me.Cells(ii, 1) = "" And Me.Cells(ii, 2) <> "") Then
            Me.Cells(ii, 1) = Me.Cells(ii - 1, 1)
        End If
    Next

    'Fill in dates
    For ii = 11 To 100
        If (Me.Cells(ii, 8) = "" And Me.Cells(ii, 9) <> "") Then
            Me.Cells(ii, 8) = Me.Cells(ii - 1, 8)
        End If
    Next
End Sub
</code>```

答:
I guess it's about date formatting. Please try to ensure, that the dates are formatted correctly, e. g. by this:</p>

```<code>ptF1.PivotFilters.Add2 _
    Type:=xlDateBetween, _
    Value1:=CStr(CDate(StartDate)), Value2:=CStr(CDate(EndDate)), _
    WholeDayFilter:=True
</code>```

Body:
This code has always worked in the past. Nothing has changed in the workbook and I have verified that all referenced data is formatted correctly.  Any idea what would have "broken" this?  It no longer applies the "between" filter to the dates in the pivot tables.

Verified pivot tables work when manually altered.  Checked fields in data table to make sure nothing has changed and there is no corrupt data entered.

    StartDate = Sheet17.Range("D5").Value
    EndDate = Sheet17.Range("D6").Value

    Set pt = Sheet6.PivotTables(1)
    Set ptF1 = pt.PivotFields("Est closing Date")

    ptF1.ClearAllFilters
    ptF1.PivotFilters.Add _
        Type:=xlDateBetween, Value1:=StartDate, Value2:=EndDate

    Sheet17.Range("M10:Q999").ClearContents
    pt.TableRange1.Offset(4, 0).Copy
    Sheet17.Cells(10, 13).PasteSpecial xlPasteValues

    Set pt = Sheet6.PivotTables(2)
    Set ptF1 = pt.PivotFields("Funds Date")

    ptF1.ClearAllFilters
    ptF1.PivotFilters.Add _
        Type:=xlDateBetween, Value1:=StartDate, Value2:=EndDate

    Sheet17.Range("A10:E999").ClearContents
    'omit copying the top row of the PivotTable:
    pt.TableRange2.Offset(4, 0).Copy
    Sheet17.Cells(10, 1).PasteSpecial xlPasteValues

    'Fill in dates
    For ii = 11 To 100
        If (Me.Cells(ii, 1) = "" And Me.Cells(ii, 2) <> "") Then
            Me.Cells(ii, 1) = Me.Cells(ii - 1, 1)
        End If
    Next

    'Fill in dates
    For ii = 11 To 100
        If (Me.Cells(ii, 8) = "" And Me.Cells(ii, 9) <> "") Then
            Me.Cells(ii, 8) = Me.Cells(ii - 1, 8)
        End If
    Next
End Sub

Body:
I guess it's about date formatting. Please try to ensure, that the dates are formatted correctly, e. g. by this:

ptF1.PivotFilters.Add2 _
    Type:=xlDateBetween, _
    Value1:=CStr(CDate(StartDate)), Value2:=CStr(CDate(EndDate)), _
    WholeDayFilter:=True


问:
Unminify CSS styles
I am trying to un-minify/un-merge my CSS styles. I have a style.css file with lots of merged styles in it, something like:

```<code>.style1,.style2,.style3{float: right}.style1{border-radius: 15px}.style2{border-radius: 0}.style3{border-radius: 10px}
</code>```

What I am trying to convert it into is:

```<code>.style1{float: right;border-radius: 15px}
.style2{float: right;border-radius: 0}
.style3{float: right;border-radius: 10px}
</code>```

How can I un-merge minified css styles to get such an output? I have tried several CSS Beautifiers and Unminifiers but they do not exactly what I need.

UPD: Here is the solution: codebeautifier.com
. In order to get same output as in my example above, open this page, find  Regroup selectors, set it to Only seperate selectors (split at ,), paste your CSS and hit Process CSS

答:
Try https://unminify.com/. Nothing to install, nothing to pay. Copy, paste, boom:

.style1,
.style2,
.style3 {
    float: right
}

.style1 {
    border-radius: 15px
}

.style2 {
    border-radius: 0
}

.style3 {
    border-radius: 10px
}```

Title: Unminify CSS styles

Body:
I am trying to un-minify/un-merge my CSS styles. I have a style.css file with lots of merged styles in it, something like:

.style1,.style2,.style3{float: right}.style1{border-radius: 15px}.style2{border-radius: 0}.style3{border-radius: 10px}

What I am trying to convert it into is:

.style1{float: right;border-radius: 15px}
.style2{float: right;border-radius: 0}
.style3{float: right;border-radius: 10px}

How can I un-merge minified css styles to get such an output? I have tried several CSS Beautifiers and Unminifiers but they do not exactly what I need.

UPD: Here is the solution: codebeautifier.com
. In order to get same output as in my example above, open this page, find  Regroup selectors, set it to Only seperate selectors (split at ,), paste your CSS and hit Process CSS


问:
aws s3 boto3 copy()
I am trying to execute the following program and facing this issue

botocore.exceptions.ClientError: An error occurred (404) when calling
  the HeadObject operation: Not Found

```<code>import boto3
s3 = boto3.resource('s3')
copy_source = {
    'Bucket': 'forw',
    'Key': 'test'
}
s3.meta.client.copy(copy_source,Bucket='copybucket0526',Key='tet')
</code>```

答: In general a 404 code on HeadObject means that the resource does not exist.</p>

Title: aws s3 boto3 copy()

Body:
I am trying to execute the following program and facing this issue

botocore.exceptions.ClientError: An error occurred (404) when calling
  the HeadObject operation: Not Found

import boto3
s3 = boto3.resource('s3')
copy_source = {
    'Bucket': 'forw',
    'Key': 'test'
}
s3.meta.client.copy(copy_source,Bucket='copybucket0526',Key='tet')


问:
Contact Form with Text Area filling remaining content
I am trying to create a contact form similar to the design bellow, but can't seem to get the correct result. I thought I could do this with flex-box, but I am having trouble getting the Text Area to Display correctly. If there is a better way to do this with keeping the HTML structure the same, I am open to suggestions.

CodePen

```<code><form class="flex-container">
  <ul>
  <li>
    <input type="text" placeholder="left">
  </li>
  <li>
    <input type="text" placeholder="left">
  </li>
  <li>
    <input type="text" placeholder="left">
  </li>
  <li>
    <input type="text" placeholder="right">
  </li>
  <li>
    <input type="text" placeholder="left">
  </li>
  <li class="text-area">
    <textarea placeholder="right"></textarea>
  </li>
  </ul>
</form>
</code>```

答:
Maybe there is a more quick solution but you can do that with bootstrap :

```<code><form class="container">
<div class="col-5 row">
    <div class="col-6">
        <div class = "row">
            <input type="text" placeholder="left">
        </div>
        <div class="row mt-3">
            <input type="text" placeholder="left">
        </div>
        <div class="row mt-3">
            <input type="text" placeholder="left">
        </div>
        <div class="row mt-3">
            <input type="text" placeholder="left">
        </div>
    </div>
    <div class="col-3 ml-3">
        <div class = "row">
            <input type="text" placeholder="left">
        </div>
         <div class = "row mt-3 heightCSS">
            <textarea placeholder="right"></textarea>
        </div>
    </div>
</div>
</code>```

CSS :

```<code>.heightCSS{
height: 8em;
width: 14em;
</code>```

}

Body:
I am trying to create a contact form similar to the design bellow, but can't seem to get the correct result. I thought I could do this with flex-box, but I am having trouble getting the Text Area to Display correctly. If there is a better way to do this with keeping the HTML structure the same, I am open to suggestions.

CodePen

<form class="flex-container">

    <input type="text" placeholder="left">

    <input type="text" placeholder="left">

    <input type="text" placeholder="left">

    <input type="text" placeholder="right">

    <input type="text" placeholder="left">

    <textarea placeholder="right"></textarea>

</form>

Body:
Maybe there is a more quick solution but you can do that with bootstrap :

<form class="container">
<div class="col-5 row">
    <div class="col-6">
        <div class = "row">
            <input type="text" placeholder="left">
        </div>
        <div class="row mt-3">
            <input type="text" placeholder="left">
        </div>
        <div class="row mt-3">
            <input type="text" placeholder="left">
        </div>
        <div class="row mt-3">
            <input type="text" placeholder="left">
        </div>
    </div>
    <div class="col-3 ml-3">
        <div class = "row">
            <input type="text" placeholder="left">
        </div>
         <div class = "row mt-3 heightCSS">
            <textarea placeholder="right"></textarea>
        </div>
    </div>
</div>

CSS :

.heightCSS{
height: 8em;
width: 14em;

}


问:
return NULL value

Snippets of framebufferd3d11.h

```<code>namespace dx11 {
...
class FramebufferManager : public FramebufferManagerBase
{
public:
   ...
private:
   ...
   static struct Efb
   {
      ...
      std::unique_ptr<D3DTexture2D> resolved_color_tex;
      std::unique_ptr<D3DTexture2D> resolved_depth_tex;
   } m_efb;
};
} //namespace
</code>```

Snippets of framebufferd3d11.cpp

```<code>namespace DX11
{
...
FramebufferManager::Efb FramebufferManager::m_efb;
...
FramebufferManager::FramebufferManager()
{
   ...
   m_efb.resolved_color_tex = NULL;
   m_efb.resolved_depth_tex = NULL;
}
} //namespace
</code>```

If I compile with icc, I get a problem with NULL assign value, as NULL is defined as 0. How do I solve a problem like this?

答:
Never initialize members in the body of the constructor. If they have non-trivial constructor, it is first called and than operator= is used to reinitialize them. Instead use the base and member initializer list. Like:

```<code>FramebufferManager::FramebufferManager() :
   resolved_color_tex(NULL), resolved_depth_tex(NULL)
{
   ...
}
</code>```

In your case it turns out that:

The default constructor (called if you mention either resolved_color_tex() or not mention it at all) already does what you want.

For primitive types, if you explicitly mention them, they will be zero-initialized. So any pointer members, no matter what type, if explicitly mentioned in the initializer list, will be NULL and you don't have to think about it any more.

Title: return NULL value

Body:
Snippets of framebufferd3d11.h

namespace dx11 {
...
class FramebufferManager : public FramebufferManagerBase
{
public:
   ...
private:
   ...
   static struct Efb
   {
      ...
      std::unique_ptr<D3DTexture2D> resolved_color_tex;
      std::unique_ptr<D3DTexture2D> resolved_depth_tex;
   } m_efb;
};
} //namespace

Snippets of framebufferd3d11.cpp

namespace DX11
{
...
FramebufferManager::Efb FramebufferManager::m_efb;
...
FramebufferManager::FramebufferManager()
{
   ...
   m_efb.resolved_color_tex = NULL;
   m_efb.resolved_depth_tex = NULL;
}
} //namespace

If I compile with icc, I get a problem with NULL assign value, as NULL is defined as 0. How do I solve a problem like this?

Body:
Never initialize members in the body of the constructor. If they have non-trivial constructor, it is first called and than operator= is used to reinitialize them. Instead use the base and member initializer list. Like:

FramebufferManager::FramebufferManager() :
   resolved_color_tex(NULL), resolved_depth_tex(NULL)
{
   ...
}

In your case it turns out that:

The default constructor (called if you mention either resolved_color_tex() or not mention it at all) already does what you want.

For primitive types, if you explicitly mention them, they will be zero-initialized. So any pointer members, no matter what type, if explicitly mentioned in the initializer list, will be NULL and you don't have to think about it any more.


问:
Office web addin addin command send command to taskpane
When the user clicks a button in the ribbon, I want to open the taskbar (when it is not opened already) and then I want to execute code depending on which button in the ribbon was clicked.

I m using vue.js for the taskpane.

答:
I haven't tried this, but it's a suggestion that's too complicated to put into a comment:

For each button, add the <ExtensionPoint> and <Control> markup in the add-in's manifest. Details are in Create Add-in Commands. Set the Action type to ShowTaskpane for all the buttons. For each of the actions, set the <SourceLocation>'s resid to a different string. Then in the <Resources><Urls> section, set each of the resid strings to the URL of the taskpane page, but have a different query parameter on the end of each of them.

```<code><bt:Urls>
    <bt:Url id="residButton1" DefaultValue="https://contoso.com/Home.aspx?Button1">
    <bt:Url id="residButton2" DefaultValue="https://contoso.com/Home.aspx?Button2" />
</bt:Url>
</code>```

Then have startup logic in the taskpane page that reads the query parameter to determine which button was pressed. The startup logic can be in a function assigned to Office.initialize or in a callback to Office.onReady.

Body:
I haven't tried this, but it's a suggestion that's too complicated to put into a comment:

For each button, add the <ExtensionPoint> and <Control> markup in the add-in's manifest. Details are in Create Add-in Commands. Set the Action type to ShowTaskpane for all the buttons. For each of the actions, set the <SourceLocation>'s resid to a different string. Then in the <Resources><Urls> section, set each of the resid strings to the URL of the taskpane page, but have a different query parameter on the end of each of them.

<bt:Urls>
    <bt:Url id="residButton1" DefaultValue="https://contoso.com/Home.aspx?Button1">
    <bt:Url id="residButton2" DefaultValue="https://contoso.com/Home.aspx?Button2" />
</bt:Url>

Then have startup logic in the taskpane page that reads the query parameter to determine which button was pressed. The startup logic can be in a function assigned to Office.initialize or in a callback to Office.onReady.


问:
Is there a way to round a decimals that i get in the coefficients of the function poly.calc?
I'm working with the poly.calc() function to interpolate some points, the problem is that I need to print the polynomial with maximum two decimals for each coefficient

I know that in R there is a function like round (...) and it can do this but with numbers, i don't know if it works with the expression that i get from poly.calc().

A example:

```<code>library(PolynomF)

x=c(1:4)
y=c(15,12,14,17)

pol = poly.calc(x,y)
pol
</code>```

This is the result:

27 - 17.83333*x + 6.5*x^2 - 0.6666667*x^3

And i need something like this:

27 - 17.83*x + 6.5*x^2 - 0.66*x^3

答:
We can make use of the round

```<code>library(PolynomF)
pol <- round(pol, 2)
pol
#27 - 17.83*x + 6.5*x^2 - 0.67*x^3
</code>```

data

```<code>pol <- poly_calc(x,y)
</code>```

Body:
I'm working with the poly.calc() function to interpolate some points, the problem is that I need to print the polynomial with maximum two decimals for each coefficient

I know that in R there is a function like round (...) and it can do this but with numbers, i don't know if it works with the expression that i get from poly.calc().

A example:

library(PolynomF)

x=c(1:4)
y=c(15,12,14,17)

pol = poly.calc(x,y)
pol

This is the result:

27 - 17.83333*x + 6.5*x^2 - 0.6666667*x^3

And i need something like this:

27 - 17.83*x + 6.5*x^2 - 0.66*x^3

Body:
We can make use of the round

library(PolynomF)
pol <- round(pol, 2)
pol
#27 - 17.83*x + 6.5*x^2 - 0.67*x^3

data

pol <- poly_calc(x,y)


问:
gitlab ci cannot build windows container
I am trying to build windows container using https://gitlab.com, but I didnot find if this is supported or not.

I made a test with a really simple Dockerfile:

```<code>FROM mcr.microsoft.com/windows/servercore:ltsc2019
CMD echo "Hello World from Windows"
</code>```

Using .gitlab-ci.yml

```<code>image: docker
services:
- docker:dind

variables:
  DOCKER_HOST: tcp://docker:2375
  DOCKER_DRIVER: overlay2

before_script:
  - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY

windows:
  stage: build
  script:
  - docker build -t ${CI_REGISTRY}/${CI_PROJECT_PATH}:${CI_COMMIT_REF_SLUG} .
  - docker push ${CI_REGISTRY}/${CI_PROJECT_PATH}:${CI_COMMIT_REF_SLUG}
</code>```

It fails with :

image operating system "windows" cannot be used on this platform

  ERROR: Job failed: exit code 1

Looking for the documentation of gitlab-runner, it seems supported https://docs.gitlab.com/runner/executors/#selecting-the-executor.

Is there a way to build a windows container from the online service ?

答:
This should be supported with GitLab 1.11 (May 2019)

Windows Container Executor for GitLab Runner

In GitLab 11.11 we are pleased to add a new executor to the GitLab Runner for using Docker containers on Windows.

Previously, using the shell executor to orchestrate Docker commands was the primary approach for Windows, but with this update you are now able to use Docker containers on Windows directly, in much the same way as if they were on Linux hosts.

  This opens up the door for more advanced kinds of pipeline orchestration and management for our users of Microsoft platforms.

Included with this update is improved support for PowerShell throughout GitLab CI/CD, as well as new helper images for various versions of Windows containers.

  Please note that your own Windows runners can be used with GitLab.com, but are not currently available as part of the shared public fleet.

This is from issue 535: see the documentation "Using Windows containers".

It has limitations, but it is a good first step.

Body:
I am trying to build windows container using https://gitlab.com, but I didnot find if this is supported or not.

I made a test with a really simple Dockerfile:

FROM mcr.microsoft.com/windows/servercore:ltsc2019
CMD echo "Hello World from Windows"

Using .gitlab-ci.yml

image: docker
services:
- docker:dind

variables:
  DOCKER_HOST: tcp://docker:2375
  DOCKER_DRIVER: overlay2

before_script:
  - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY

windows:
  stage: build
  script:
  - docker build -t ${CI_REGISTRY}/${CI_PROJECT_PATH}:${CI_COMMIT_REF_SLUG} .
  - docker push ${CI_REGISTRY}/${CI_PROJECT_PATH}:${CI_COMMIT_REF_SLUG}

It fails with :

image operating system "windows" cannot be used on this platform

  ERROR: Job failed: exit code 1

Looking for the documentation of gitlab-runner, it seems supported https://docs.gitlab.com/runner/executors/#selecting-the-executor.

Is there a way to build a windows container from the online service ?


问:
How to compare 2 textures in JavaScript / WebGL2?
I am writing a fragment shader for an image processing algorithm. The shader will run multiple times between two framebuffers in a loop (ping-pong). At some point I need to stop the loop when input and output textures are identical.

What I intend to do is the last step of Canny edge detector algorithm, "hysterezis edge tracking". I want to make a real time GPU/WebGL2 version of Canny algorithm and upload it to a web site.

This last step is as follows:

Given a double thresholded image containing "strong" edge pixels (1.0) and "weak" edge pixels (0.5)

find all chains of weak pixels connected with a strong pixel and mark them "strong"

keep all "strong" pixels and discard all remaining "weak" ones.

This can be implemented in a fragment shader running multiple times in a loop. The current "weak" pixel is marked "strong" if there is at least one strong pixel in its 8-pixel neighbourhood. At every iteration, we should have more strong pixels and less weak pixels. At the end, only isolated chains of weak pixel should remain. This is the point where the fragment shader becomes a pass-through shader and should be detected to stop the loop.

Update Sept 2019: I uploaded the GPU Canny Edge Detector here http://www.oldrinb.info/dip/canny/ . It works in browsers with WebGL2 support, as well in browsers that support WebGL1 and 'WEBGL_draw_buffers' extension. I'll put also the source code to github shortly.

答:
I'm not 100% sure what you're asking. You're asking to compare on the CPU. You can read the contents of a texture by attaching it to a framebuffer and then calling gl.readPixels. you can then compare all the pixels. Note: not all texture formats can be attached to a framebuffer but assuming you're using a format that can. You've already attached textures to framebuffers for your ping-ponging so what more did you want?

Like I wrote in the comment on the GPU you can write a shader to compare 2 textures

```<code>#version 300 es
precision highp float;

uniform sampler2D tex1;
uniform sampler2D tex2;

out vec4 outColor;

void main() {
  ivec2 size = textureSize(tex1, 0);  // size of mip 0
  float len = 0.0;
  for (int y = 0; y < size.y; ++y) {
    for (int x = 0; x < size.x; ++x) {
      vec4 color1 = texelFetch(tex1, ivec2(x, y), 0);
      vec4 color2 = texelFetch(tex2, ivec2(x, y), 0);
      vec4 diff = color1 - color2;
      len = length(diff);
      if (len > 0.0) break;
    }
    if (len > 0.0) break;
  }
  outColor = mix(vec4(0), vec4(1), step(len, 0.0));
}
</code>```

now just draw 1 pixel and read it with readPixels. if it's 0 the textures are the same. If it's not they are different.

The code assumes the textures are the same size but of course if they aren't the same size then we already know they can't be the same.

// make 3 canvaes as sources for textures
const canvases = ['A', 'B', 'B'].map((msg) => {
  const canvas = document.createElement('canvas');
  canvas.width = 128;
  canvas.height = 128;
  const ctx = canvas.getContext('2d');
  ctx.fillStyle = 'blue';
  ctx.fillRect(0, 0, 128, 128);
  ctx.font = '80px monospace';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillStyle = 'yellow';
  ctx.fillText(msg, 64, 64);
  document.body.appendChild(canvas);
  return canvas;
});

const gl = document.createElement('canvas').getContext('webgl2');
if (!gl) { alert('need webgl2'); }

const vs = `#version 300 es
void main() {
  gl_PointSize = 1.0;
  gl_Position = vec4(0, 0, 0, 1);
}
`;

const fs = `#version 300 es
precision highp float;

uniform sampler2D tex1;
uniform sampler2D tex2;

out vec4 outColor;

void main() {
  ivec2 size = textureSize(tex1, 0);  // size of mip 0
  float len = 0.0;
  for (int y = 0; y < size.y; ++y) {
    for (int x = 0; x < size.x; ++x) {
      vec4 color1 = texelFetch(tex1, ivec2(x, y), 0);
      vec4 color2 = texelFetch(tex2, ivec2(x, y), 0);
      vec4 diff = color1 - color2;
      len = length(diff);
      if (len > 0.0) break;
    }
    if (len > 0.0) break;
  }
  outColor = mix(vec4(0), vec4(1), step(len, 0.0));
}
`;

// compile shaders, link program, look up locations
const programInfo = twgl.createProgramInfo(gl, [vs, fs]);

const textures = canvases.map((canvas) => {
  // gl.createTexture, gl.bindTexture, gl.texImage, etc.
  return twgl.createTexture(gl, {src: canvas});
});

compareTextures(0, 1);
compareTextures(1, 2);

function compareTextures(ndx1, ndx2) {
  gl.useProgram(programInfo.program);

  // gl.activeTexture, gl.bindTexture, gl.uniform
  twgl.setUniforms(programInfo, {
    tex1: textures[ndx1],
    tex2: textures[ndx2],
  });

  // draw the bottom right pixel
  gl.viewport(0, 0, 1, 1);

  gl.drawArrays(gl.POINTS, 0, 1);  // draw 1 point

  // read the pixel
  const result = new Uint8Array(4);
  gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, result);

  console.log('textures', ndx1, 'and', ndx2, 'are', result[0] ? 'the same' : 'not the same');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas { padding: 5px; }</code>```

```
</div>
</div>
</p>

<p>You could also use occlusion queries. The plus is they might not block the GPU where as readPixels does. The minus is you can't check them in the same JavaScript event so they might not fit your needs</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// make 3 canvaes as sources for textures
const canvases = ['A', 'B', 'B'].map((msg) => {
  const canvas = document.createElement('canvas');
  canvas.width = 128;
  canvas.height = 128;
  const ctx = canvas.getContext('2d');
  ctx.fillStyle = 'blue';
  ctx.fillRect(0, 0, 128, 128);
  ctx.font = '80px monospace';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillStyle = 'yellow';
  ctx.fillText(msg, 64, 64);
  document.body.appendChild(canvas);
  return canvas;
});

const gl = document.createElement('canvas').getContext('webgl2');
if (!gl) { alert('need webgl2'); }

const vs = `#version 300 es
void main() {
  gl_PointSize = 1.0;
  gl_Position = vec4(0, 0, 0, 1);
}
`;

const fs = `#version 300 es
precision highp float;

uniform sampler2D tex1;
uniform sampler2D tex2;

out vec4 outColor;

void main() {
  ivec2 size = textureSize(tex1, 0);  // size of mip 0
  float len = 0.0;
  for (int y = 0; y < size.y; ++y) {
    for (int x = 0; x < size.x; ++x) {
      vec4 color1 = texelFetch(tex1, ivec2(x, y), 0);
      vec4 color2 = texelFetch(tex2, ivec2(x, y), 0);
      vec4 diff = color1 - color2;
      len = length(diff);
      if (len > 0.0) break;
    }
    if (len > 0.0) break;
  }
  if (len > 0.0) {
    discard;
  }
  outColor = vec4(1);
}
`;

// compile shaders, link program, look up locations
const programInfo = twgl.createProgramInfo(gl, [vs, fs]);

const textures = canvases.map((canvas) => {
  // gl.createTexture, gl.bindTexture, gl.texImage, etc.
  return twgl.createTexture(gl, {src: canvas});
});

function wait(ms = 0) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

async function test() {
  await compareTextures(0, 1);
  await compareTextures(1, 2);
}
test();

async function compareTextures(ndx1, ndx2) {
  gl.clear(gl.DEPTH_BUFFER_BIT);
  gl.enable(gl.DEPTH_TEST);
  gl.useProgram(programInfo.program);

  // gl.activeTexture, gl.bindTexture, gl.uniform
  twgl.setUniforms(programInfo, {
    tex1: textures[ndx1],
    tex2: textures[ndx2],
  });

  // draw the bottom right pixel
  gl.viewport(0, 0, 1, 1);

  const query = gl.createQuery();
  gl.beginQuery(gl.ANY_SAMPLES_PASSED, query);
  gl.drawArrays(gl.POINTS, 0, 1);  // draw 1 point
  gl.endQuery(gl.ANY_SAMPLES_PASSED);
  gl.flush();

  let ready = false;
  while(!ready) {
    await wait();
    ready = gl.getQueryParameter(query, gl.QUERY_RESULT_AVAILABLE);
  }

  const same = gl.getQueryParameter(query, gl.QUERY_RESULT);

  console.log('textures', ndx1, 'and', ndx2, 'are', same ? 'the same' : 'not the same');
}</code>```

canvas { padding: 5px; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://twgljs.org/dist/4.x/twgl.min.js"></script></code>```

Body:
I'm not 100% sure what you're asking. You're asking to compare on the CPU. You can read the contents of a texture by attaching it to a framebuffer and then calling gl.readPixels. you can then compare all the pixels. Note: not all texture formats can be attached to a framebuffer but assuming you're using a format that can. You've already attached textures to framebuffers for your ping-ponging so what more did you want?

Like I wrote in the comment on the GPU you can write a shader to compare 2 textures

#version 300 es
precision highp float;

uniform sampler2D tex1;
uniform sampler2D tex2;

out vec4 outColor;

void main() {
  ivec2 size = textureSize(tex1, 0);  // size of mip 0
  float len = 0.0;
  for (int y = 0; y < size.y; ++y) {
    for (int x = 0; x < size.x; ++x) {
      vec4 color1 = texelFetch(tex1, ivec2(x, y), 0);
      vec4 color2 = texelFetch(tex2, ivec2(x, y), 0);
      vec4 diff = color1 - color2;
      len = length(diff);
      if (len > 0.0) break;
    }
    if (len > 0.0) break;
  }
  outColor = mix(vec4(0), vec4(1), step(len, 0.0));
}

now just draw 1 pixel and read it with readPixels. if it's 0 the textures are the same. If it's not they are different.

The code assumes the textures are the same size but of course if they aren't the same size then we already know they can't be the same.

// make 3 canvaes as sources for textures
const canvases = ['A', 'B', 'B'].map((msg) => {
  const canvas = document.createElement('canvas');
  canvas.width = 128;
  canvas.height = 128;
  const ctx = canvas.getContext('2d');
  ctx.fillStyle = 'blue';
  ctx.fillRect(0, 0, 128, 128);
  ctx.font = '80px monospace';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillStyle = 'yellow';
  ctx.fillText(msg, 64, 64);
  document.body.appendChild(canvas);
  return canvas;
});

const gl = document.createElement('canvas').getContext('webgl2');
if (!gl) { alert('need webgl2'); }

const vs = `#version 300 es
void main() {
  gl_PointSize = 1.0;
  gl_Position = vec4(0, 0, 0, 1);
}
`;

const fs = `#version 300 es
precision highp float;

uniform sampler2D tex1;
uniform sampler2D tex2;

out vec4 outColor;

void main() {
  ivec2 size = textureSize(tex1, 0);  // size of mip 0
  float len = 0.0;
  for (int y = 0; y < size.y; ++y) {
    for (int x = 0; x < size.x; ++x) {
      vec4 color1 = texelFetch(tex1, ivec2(x, y), 0);
      vec4 color2 = texelFetch(tex2, ivec2(x, y), 0);
      vec4 diff = color1 - color2;
      len = length(diff);
      if (len > 0.0) break;
    }
    if (len > 0.0) break;
  }
  outColor = mix(vec4(0), vec4(1), step(len, 0.0));
}
`;

// compile shaders, link program, look up locations
const programInfo = twgl.createProgramInfo(gl, [vs, fs]);

const textures = canvases.map((canvas) => {
  // gl.createTexture, gl.bindTexture, gl.texImage, etc.
  return twgl.createTexture(gl, {src: canvas});
});

compareTextures(0, 1);
compareTextures(1, 2);

function compareTextures(ndx1, ndx2) {
  gl.useProgram(programInfo.program);

  // gl.activeTexture, gl.bindTexture, gl.uniform
  twgl.setUniforms(programInfo, {
    tex1: textures[ndx1],
    tex2: textures[ndx2],
  });

  // draw the bottom right pixel
  gl.viewport(0, 0, 1, 1);

  gl.drawArrays(gl.POINTS, 0, 1);  // draw 1 point

  // read the pixel
  const result = new Uint8Array(4);
  gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, result);

  console.log('textures', ndx1, 'and', ndx2, 'are', result[0] ? 'the same' : 'not the same');
}

canvas { padding: 5px; }

<script src="https://twgljs.org/dist/4.x/twgl.min.js"></script>

You could also use occlusion queries. The plus is they might not block the GPU where as readPixels does. The minus is you can't check them in the same JavaScript event so they might not fit your needs

// make 3 canvaes as sources for textures
const canvases = ['A', 'B', 'B'].map((msg) => {
  const canvas = document.createElement('canvas');
  canvas.width = 128;
  canvas.height = 128;
  const ctx = canvas.getContext('2d');
  ctx.fillStyle = 'blue';
  ctx.fillRect(0, 0, 128, 128);
  ctx.font = '80px monospace';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillStyle = 'yellow';
  ctx.fillText(msg, 64, 64);
  document.body.appendChild(canvas);
  return canvas;
});

const gl = document.createElement('canvas').getContext('webgl2');
if (!gl) { alert('need webgl2'); }

const vs = `#version 300 es
void main() {
  gl_PointSize = 1.0;
  gl_Position = vec4(0, 0, 0, 1);
}
`;

const fs = `#version 300 es
precision highp float;

uniform sampler2D tex1;
uniform sampler2D tex2;

out vec4 outColor;

void main() {
  ivec2 size = textureSize(tex1, 0);  // size of mip 0
  float len = 0.0;
  for (int y = 0; y < size.y; ++y) {
    for (int x = 0; x < size.x; ++x) {
      vec4 color1 = texelFetch(tex1, ivec2(x, y), 0);
      vec4 color2 = texelFetch(tex2, ivec2(x, y), 0);
      vec4 diff = color1 - color2;
      len = length(diff);
      if (len > 0.0) break;
    }
    if (len > 0.0) break;
  }
  if (len > 0.0) {
    discard;
  }
  outColor = vec4(1);
}
`;

// compile shaders, link program, look up locations
const programInfo = twgl.createProgramInfo(gl, [vs, fs]);

const textures = canvases.map((canvas) => {
  // gl.createTexture, gl.bindTexture, gl.texImage, etc.
  return twgl.createTexture(gl, {src: canvas});
});

function wait(ms = 0) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

async function test() {
  await compareTextures(0, 1);
  await compareTextures(1, 2);
}
test();

async function compareTextures(ndx1, ndx2) {
  gl.clear(gl.DEPTH_BUFFER_BIT);
  gl.enable(gl.DEPTH_TEST);
  gl.useProgram(programInfo.program);

  // gl.activeTexture, gl.bindTexture, gl.uniform
  twgl.setUniforms(programInfo, {
    tex1: textures[ndx1],
    tex2: textures[ndx2],
  });

  // draw the bottom right pixel
  gl.viewport(0, 0, 1, 1);

  const query = gl.createQuery();
  gl.beginQuery(gl.ANY_SAMPLES_PASSED, query);
  gl.drawArrays(gl.POINTS, 0, 1);  // draw 1 point
  gl.endQuery(gl.ANY_SAMPLES_PASSED);
  gl.flush();

  let ready = false;
  while(!ready) {
    await wait();
    ready = gl.getQueryParameter(query, gl.QUERY_RESULT_AVAILABLE);
  }

  const same = gl.getQueryParameter(query, gl.QUERY_RESULT);

  console.log('textures', ndx1, 'and', ndx2, 'are', same ? 'the same' : 'not the same');
}

canvas { padding: 5px; }

<script src="https://twgljs.org/dist/4.x/twgl.min.js"></script>


问:
R Plotly: subplot with table
I can't figure out how to make a table subplot work properly using R and Plotly.

The following demonstrates what I mean. I have two plots, one scatter and one table. Using the subplot function, the table plot does not behave as expected.

I either lose interactivity on the scatter plot, or have overlapping scatter/table plots. Please let me know if I'm missing something or if this is a bug.

I'm using plotly version 4.9.0

Thanks in advance!

```<code>library(plotly)

df <- data.frame(x = 1:10,
                 y = 1:10)

p1 <-
  plot_ly(data = df,
          type = "scatter",
          mode = "line",
          x = ~x,
          y = ~y) %>%
  layout(xaxis = list(fixedrange=T),
         yaxis = list(fixedrange=T)) %>%
  config(displayModeBar = F)

p2 <-
  plot_ly(
    type = 'table',
    header = list(values = c("x", "y")),
    cells = list(values = rbind(df$x, df$y))
  )

subplot(p1, p2, nrows = 2) # overlapping plots

subplot(p2, p1, nrows = 2) # loses interactivity on p2

subplot(p1, p1, nrows = 2) # works as expected
</code>```

答:
I just read in the documentation for Plotly:

In Plotly there is no native way to insert a Plotly Table into a
  Subplot.

https://plot.ly/python/table-subplots/

But it seems we could create our own layout. For the table, I added 'domain' to locate it on the left side:

```<code>p2 <-
  plot_ly(
    type = 'table',
    domain = list(x=c(0,0.5), y=c(0,1)),
    header = list(values = c("x", "y")),
    cells = list(values = rbind(df$x, df$y))
  )
</code>```

And then added 'layout' for the table on the left and scatterplot on the right:

```<code>subplot(p1, p2, nrows = 2) %>%
  layout(xaxis = list(domain=c(0.5,1.0)),
         xaxis2 = list(domain=c(0,0.5)))
</code>```

Title: R Plotly: subplot with table

Body:
I can't figure out how to make a table subplot work properly using R and Plotly.

The following demonstrates what I mean. I have two plots, one scatter and one table. Using the subplot function, the table plot does not behave as expected.

I either lose interactivity on the scatter plot, or have overlapping scatter/table plots. Please let me know if I'm missing something or if this is a bug.

I'm using plotly version 4.9.0

Thanks in advance!

library(plotly)

df <- data.frame(x = 1:10,
                 y = 1:10)

p1 <-
  plot_ly(data = df,
          type = "scatter",
          mode = "line",
          x = ~x,
          y = ~y) %>%
  layout(xaxis = list(fixedrange=T),
         yaxis = list(fixedrange=T)) %>%
  config(displayModeBar = F)

p2 <-
  plot_ly(
    type = 'table',
    header = list(values = c("x", "y")),
    cells = list(values = rbind(df$x, df$y))
  )

subplot(p1, p2, nrows = 2) # overlapping plots

subplot(p2, p1, nrows = 2) # loses interactivity on p2

subplot(p1, p1, nrows = 2) # works as expected

Body:
I just read in the documentation for Plotly:

In Plotly there is no native way to insert a Plotly Table into a
  Subplot.

https://plot.ly/python/table-subplots/

But it seems we could create our own layout. For the table, I added 'domain' to locate it on the left side:

p2 <-
  plot_ly(
    type = 'table',
    domain = list(x=c(0,0.5), y=c(0,1)),
    header = list(values = c("x", "y")),
    cells = list(values = rbind(df$x, df$y))
  )

And then added 'layout' for the table on the left and scatterplot on the right:

subplot(p1, p2, nrows = 2) %>%
  layout(xaxis = list(domain=c(0.5,1.0)),
         xaxis2 = list(domain=c(0,0.5)))


问:
Print out a selected number of a string problem
The exercise says "Make a function with two parameters a string (s) and an integer(n). The function then will return the first n characters. That's what I did, but I'm getting a compiler error "[Warning] passing arg 1 of `symbolse' makes pointer from integer without a cast". I've tried to do some changes, to override this error but then I don't get  the result I want or the program crashes.

```<code> #include<stdio.h>
 #include<stdlib.h>

 void symbolse(char s[50],int n){
    int i;
    for(i=0;i<n;i++)
    printf("%c ",s[i]);

 }

main(){
   int m;
   char a[50];
   printf("Give integer: ");
   scanf("%d",&m);
   printf("Give string: ");
   a[50]=getchar();
   symbolse(a[50],m);

   system("pause");

 }
</code>```

Ex. The user gives m=3 and a[50]=House . The program should print Hou .

答:
You probably want

```<code>symbolse(a,m);
</code>```

instead of

```<code>symbolse(a[50],m);
</code>```

For you want to pass the array (pointer to array, in fact), not its 51st (unexistent) element.

(And the problem pointed by aix also exists, but it's not the one that breaks your compile).

Body:
The exercise says "Make a function with two parameters a string (s) and an integer(n). The function then will return the first n characters. That's what I did, but I'm getting a compiler error "[Warning] passing arg 1 of `symbolse' makes pointer from integer without a cast". I've tried to do some changes, to override this error but then I don't get  the result I want or the program crashes.

 #include<stdio.h>
 #include<stdlib.h>

 void symbolse(char s[50],int n){
    int i;
    for(i=0;i<n;i++)
    printf("%c ",s[i]);

 }

main(){
   int m;
   char a[50];
   printf("Give integer: ");
   scanf("%d",&m);
   printf("Give string: ");
   a[50]=getchar();
   symbolse(a[50],m);

   system("pause");

 }

Ex. The user gives m=3 and a[50]=House . The program should print Hou .

Body:
You probably want

symbolse(a,m);

instead of

symbolse(a[50],m);

For you want to pass the array (pointer to array, in fact), not its 51st (unexistent) element.

(And the problem pointed by aix also exists, but it's not the one that breaks your compile).


问:
Compare 7 input numbers with 7 Random Numbers
I'm new in C sharp but I need help about comparing my input value and random numbers, any function, method or class I have to add..</p>

```<code>List<int> lista1 = new List<int>();
for (int i = 1; i <= 7; i++)
{
    try {
        Console.Write("First Number {0}: ", i);
        int x = Convert.ToInt16(Console.ReadLine());
        lista1.Add(x);
    } catch (Exception ex){
        Console.WriteLine("The input number is incorret! It has to be whole number");
        Console.WriteLine("Error: {0}", ex.Message);
        i--;
    }
    Console.WriteLine("Random Numbers are: ");
    InitArray();
    Console.WriteLine(item);
}
</code>```

答:
This is how I would Go about approaching it Cleanly using CSharp.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
    class Program
    {
        public List<List<int>> Players { get; set; } //Your Players
        public List<int> RandomNumbers { get; set; } //Your Random numbers enerated my Computer
        public List<List<int>> MatchedNumbers { get; set; } //to store Matched Numbers for each player
        public int NumbersRequiredCount { get; set; } = 7; //Depends on how many numbers the players must guess, initialize to 7 numbers

        Program()
        {
            //Instantiate your objects
            Players = new List<List<int>>(); //List of Players with their list of guessed numbers
            RandomNumbers = new List<int>();
            MatchedNumbers = new List<List<int>>(); //To hold Matched Values
        }

        private List<int> GenerateAutoNumbers(int Count, int Min, int Max)
        {
            var Result = new List<int>(); //Result Container - will be returned
            var Random = new Random(); //Create Random Number Object
            for(int i = 0; i < Count; i++)
            {
                //Generate your random number and save
                Result.Add(Random.Next(Min, Max));
            }
            //Return "Count" Numbers of Random Numbers generated
            return Result;
        }

        public List<int> EvaluateMatches(List<int> Inputs, List<int> Bases)
        {
            var result = new List<int>();
            //Inplement a counter to check each value that was inputted
            for(int i = 0; i <  Inputs.Count; i++)
            {
                for (int r = 0; r < Bases.Count; r++)
                {
                    //Check if the current input equals the current Random Number at the given index
                    if(Inputs[i] == Bases[r])
                    {
                        //If matched. Add the matched number to the matched list
                        result.Add(Inputs[i]);
                    }
                }
            }

            //At this point, all matched numbers are organized in result object
            return result; //return result object
        }

        static void Main(string[] args)
        {
            Program App = new Program();

            //Players must input numbers - Assuming they must guess between 1 - 100
            //It can be as many players

            //Player 1
            App.Players.Add(new List<int> { 5, 47, 33, 47, 36, 89, 33 });
            //Player 2
            App.Players.Add(new List<int> { 1, 17, 38, 43, 34, 91, 24 });
            //Player 3
            App.Players.Add(new List<int> { 6, 74, 39, 58, 52, 21, 9 });

            //At this point the inputs are all in for the 3 players
            //Now generate your RandomNumbers
            App.RandomNumbers = App.GenerateAutoNumbers(App.NumbersRequiredCount, 1, 100);

            //Now you need to evaluate the guessed numbers
            //For each Player
            for(int p = 0; p < App.Players.Count; p++)
            {
                //Create the list for each user to hold the matched numbers
                App.MatchedNumbers.Add(App.EvaluateMatches(App.Players[p], App.RandomNumbers));
            }

            //Now all Players numbers are evaluated, all you need is to print the results
            Console.WriteLine("Results has been retrieved");
            Console.Write("Generated Numbers are: ");
            foreach(int i in App.RandomNumbers)
            {
                Console.Write(i + " ");
            }
            Console.WriteLine();
            Console.WriteLine();

            Console.WriteLine("Following Matches were Found: ");
            for(int p = 0; p < App.Players.Count; p++)
            {
                Console.Write($"Player {p + 1} has {App.MatchedNumbers[p].Count} Matches: ");
                foreach(int i in App.MatchedNumbers[p])
                {
                    Console.Write(i + "  ");
                }
                Console.WriteLine();
            }
            Console.Write("\n");
            Console.WriteLine("Press any Key to Exit!");
            Console.ReadKey();

        }
    }
}
</code>```

It will print the numbers matched on the screen.

Body:
I'm new in C sharp but I need help about comparing my input value and random numbers, any function, method or class I have to add..

List<int> lista1 = new List<int>();
for (int i = 1; i <= 7; i++)
{
    try {
        Console.Write("First Number {0}: ", i);
        int x = Convert.ToInt16(Console.ReadLine());
        lista1.Add(x);
    } catch (Exception ex){
        Console.WriteLine("The input number is incorret! It has to be whole number");
        Console.WriteLine("Error: {0}", ex.Message);
        i--;
    }
    Console.WriteLine("Random Numbers are: ");
    InitArray();
    Console.WriteLine(item);
}

Body:
This is how I would Go about approaching it Cleanly using CSharp.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
    class Program
    {
        public List<List<int>> Players { get; set; } //Your Players
        public List<int> RandomNumbers { get; set; } //Your Random numbers enerated my Computer
        public List<List<int>> MatchedNumbers { get; set; } //to store Matched Numbers for each player
        public int NumbersRequiredCount { get; set; } = 7; //Depends on how many numbers the players must guess, initialize to 7 numbers

        Program()
        {
            //Instantiate your objects
            Players = new List<List<int>>(); //List of Players with their list of guessed numbers
            RandomNumbers = new List<int>();
            MatchedNumbers = new List<List<int>>(); //To hold Matched Values
        }

        private List<int> GenerateAutoNumbers(int Count, int Min, int Max)
        {
            var Result = new List<int>(); //Result Container - will be returned
            var Random = new Random(); //Create Random Number Object
            for(int i = 0; i < Count; i++)
            {
                //Generate your random number and save
                Result.Add(Random.Next(Min, Max));
            }
            //Return "Count" Numbers of Random Numbers generated
            return Result;
        }

        public List<int> EvaluateMatches(List<int> Inputs, List<int> Bases)
        {
            var result = new List<int>();
            //Inplement a counter to check each value that was inputted
            for(int i = 0; i <  Inputs.Count; i++)
            {
                for (int r = 0; r < Bases.Count; r++)
                {
                    //Check if the current input equals the current Random Number at the given index
                    if(Inputs[i] == Bases[r])
                    {
                        //If matched. Add the matched number to the matched list
                        result.Add(Inputs[i]);
                    }
                }
            }

            //At this point, all matched numbers are organized in result object
            return result; //return result object
        }

        static void Main(string[] args)
        {
            Program App = new Program();

            //Players must input numbers - Assuming they must guess between 1 - 100
            //It can be as many players

            //Player 1
            App.Players.Add(new List<int> { 5, 47, 33, 47, 36, 89, 33 });
            //Player 2
            App.Players.Add(new List<int> { 1, 17, 38, 43, 34, 91, 24 });
            //Player 3
            App.Players.Add(new List<int> { 6, 74, 39, 58, 52, 21, 9 });

            //At this point the inputs are all in for the 3 players
            //Now generate your RandomNumbers
            App.RandomNumbers = App.GenerateAutoNumbers(App.NumbersRequiredCount, 1, 100);

            //Now you need to evaluate the guessed numbers
            //For each Player
            for(int p = 0; p < App.Players.Count; p++)
            {
                //Create the list for each user to hold the matched numbers
                App.MatchedNumbers.Add(App.EvaluateMatches(App.Players[p], App.RandomNumbers));
            }

            //Now all Players numbers are evaluated, all you need is to print the results
            Console.WriteLine("Results has been retrieved");
            Console.Write("Generated Numbers are: ");
            foreach(int i in App.RandomNumbers)
            {
                Console.Write(i + " ");
            }
            Console.WriteLine();
            Console.WriteLine();

            Console.WriteLine("Following Matches were Found: ");
            for(int p = 0; p < App.Players.Count; p++)
            {
                Console.Write($"Player {p + 1} has {App.MatchedNumbers[p].Count} Matches: ");
                foreach(int i in App.MatchedNumbers[p])
                {
                    Console.Write(i + "  ");
                }
                Console.WriteLine();
            }
            Console.Write("\n");
            Console.WriteLine("Press any Key to Exit!");
            Console.ReadKey();

        }
    }
}

It will print the numbers matched on the screen.


问:
Nested list comprehension with generators
I have some strange behavior on python 3.7 with a nested list comprehension that involves a generator.

This works:

```<code>i = range(20)
n = [1, 2, 3]
result = [min(x + y for x in i) for y in n]
</code>```

It does not work if i is a generator:

```<code>i = (p for p in range(20))
n = [1, 2, 3]
result = [min(x + y for x in i) for y in n]
</code>```

This raises a ValueError: min() arg is an empty sequence

Now even if the generator i is wrapped with list it still creates the same error:

```<code>i = (p for p in range(20))
n = [1, 2, 3]
result = [min(x + y for x in list(i)) for y in n]
</code>```

Is this a python bug or is it expected behavior? If it is expected behavior, can you explain why this does not work?

答:
In i = range(20) the range(20) is a promise to generate a generator.
While i = (p for p in range(20)) is already a generator.

Now write your list expression as:

```<code>for y in [1, 2, 3]:
    print(min(x + y for x in i))
## 1
## ...
## ValueError: min() arg is an empty sequence
</code>```

You get a 1 printed, but (the generator is exhausted in the first call)
and then you get in the next round a
ValueError: min() arg is an empty sequence
because the generator i was already consumed in the first for-loop call for y as 1.
While if i is defined as range(20),
everytime the for x in i is called, the generator is re-created again and again.

You can imitate what range(20) is doing by:

```<code>def gen():
    return (p for p in range(20))

for y in [1, 2, 3]:
    print(min(x + y for x in gen()))
    # range() like gen() is a promise to generate the generator
## 1
## 2
## 3
</code>```

Now the generator is created everytime anew.

But in fact, range is even cooler, if you do:

```<code>i = range(20)

for y in [1, 2, 3]:
    print(min(x + y for x in i))
## 1
## 2
## 3
</code>```

The i inside the innerst generator is not a function call.
But despite of that it creates - when evaluted - a new generator -
at least when used as an iterable within a for loop.

This is actually implemented in Python using a class and by defining the __iter__() method. Which defines the behaviour in interators - here especiall a lazy behavior.

To imitate this behavior, we can generate a lazy generator (lazy_gen).

```<code>class lazy_gen:
    def __init__(self):
        pass

    def __iter__(self):    # everytime when used as an iterator
        return self.gen()  # recreate the generator # real lazy behavior

    def gen(self):
        return (p for p in range(20))
</code>```

Which we can use like:

```<code>i = lazy_gen()

for y in [1, 2, 3]:
    print(min(x + y for x in i))
## 1
## 2
## 3
</code>```

So this reflects even better the range() behavior.

Other languages (functional languages) like Lisp family languages (common-lisp, Racket, Scheme, Clojure), R, or Haskell
have a better control over evaluation - thus over lazy evaluation and promises. But in Python, for such implementations and fine grained control, one has to take resort in OOP.

My range function and class

Finally, I figured out how the range function must have been realized roughly.
(For fun, though I could have looked it up in the source code of Python I know - but sometimes reasoning is fun.)

```<code>class Myrange:
    def __init__(self, start, end, step):
        self.start = start
        self.end = end
        self.step = step

    def __iter__(self):
        return self.generate_range()

    def generate_range(self):
        x = self.start - self.step
        while x + self.step < self.end:
            x = x + self.step
            yield x

    def __repr__(self):
        return "myrange({}, {})".format(self.start, self.end)

def myrange(start=None, end=None, step=1):
    if start is None and end is None:
        raise "Please provide at least one number for the range-limits."
    elif start is not None and end is None:
        _start = 0
        _end = start
    elif start is not None and end is not None:
        _start = start
        _end = end
    else:
        _start = 0
        _end = end
    _step = step
    return Myrange(_start, _end, _step)
</code>```

One can use it exactly like the range function.

```<code>i = myrange(20)

n = [1, 2, 3]
result = [min(x + y for x in i) for y in n]

result
## [1, 2, 3]

i
## myrange(0, 20)  # representation of a Myrange object.

myrange(20)
## myrange(0, 20)

list(myrange(3, 10))
## [3, 4, 5, 6, 7, 8, 9]

list(myrange(0, 10))
## [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

list(myrange(10))
## [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

list(myrange(0, 10, 2))
## [0, 2, 4, 6, 8]

list(myrange(3, 10, 2))
## [3, 5, 7, 9]
</code>```

Body:
I have some strange behavior on python 3.7 with a nested list comprehension that involves a generator.

This works:

i = range(20)
n = [1, 2, 3]
result = [min(x + y for x in i) for y in n]

It does not work if i is a generator:

i = (p for p in range(20))
n = [1, 2, 3]
result = [min(x + y for x in i) for y in n]

This raises a ValueError: min() arg is an empty sequence

Now even if the generator i is wrapped with list it still creates the same error:

i = (p for p in range(20))
n = [1, 2, 3]
result = [min(x + y for x in list(i)) for y in n]

Is this a python bug or is it expected behavior? If it is expected behavior, can you explain why this does not work?

Body:
In i = range(20) the range(20) is a promise to generate a generator.
While i = (p for p in range(20)) is already a generator.

Now write your list expression as:

for y in [1, 2, 3]:
    print(min(x + y for x in i))
## 1
## ...
## ValueError: min() arg is an empty sequence

You get a 1 printed, but (the generator is exhausted in the first call)
and then you get in the next round a
ValueError: min() arg is an empty sequence
because the generator i was already consumed in the first for-loop call for y as 1.
While if i is defined as range(20),
everytime the for x in i is called, the generator is re-created again and again.

You can imitate what range(20) is doing by:

def gen():
    return (p for p in range(20))

for y in [1, 2, 3]:
    print(min(x + y for x in gen()))
    # range() like gen() is a promise to generate the generator
## 1
## 2
## 3

Now the generator is created everytime anew.

But in fact, range is even cooler, if you do:

i = range(20)

for y in [1, 2, 3]:
    print(min(x + y for x in i))
## 1
## 2
## 3

The i inside the innerst generator is not a function call.
But despite of that it creates - when evaluted - a new generator -
at least when used as an iterable within a for loop.

This is actually implemented in Python using a class and by defining the __iter__() method. Which defines the behaviour in interators - here especiall a lazy behavior.

To imitate this behavior, we can generate a lazy generator (lazy_gen).

class lazy_gen:
    def __init__(self):
        pass

    def __iter__(self):    # everytime when used as an iterator
        return self.gen()  # recreate the generator # real lazy behavior

    def gen(self):
        return (p for p in range(20))

Which we can use like:

i = lazy_gen()

for y in [1, 2, 3]:
    print(min(x + y for x in i))
## 1
## 2
## 3

So this reflects even better the range() behavior.

Other languages (functional languages) like Lisp family languages (common-lisp, Racket, Scheme, Clojure), R, or Haskell
have a better control over evaluation - thus over lazy evaluation and promises. But in Python, for such implementations and fine grained control, one has to take resort in OOP.

My range function and class

Finally, I figured out how the range function must have been realized roughly.
(For fun, though I could have looked it up in the source code of Python I know - but sometimes reasoning is fun.)

class Myrange:
    def __init__(self, start, end, step):
        self.start = start
        self.end = end
        self.step = step

    def __iter__(self):
        return self.generate_range()

    def generate_range(self):
        x = self.start - self.step
        while x + self.step < self.end:
            x = x + self.step
            yield x

    def __repr__(self):
        return "myrange({}, {})".format(self.start, self.end)

def myrange(start=None, end=None, step=1):
    if start is None and end is None:
        raise "Please provide at least one number for the range-limits."
    elif start is not None and end is None:
        _start = 0
        _end = start
    elif start is not None and end is not None:
        _start = start
        _end = end
    else:
        _start = 0
        _end = end
    _step = step
    return Myrange(_start, _end, _step)

One can use it exactly like the range function.

i = myrange(20)

n = [1, 2, 3]
result = [min(x + y for x in i) for y in n]

result
## [1, 2, 3]

i
## myrange(0, 20)  # representation of a Myrange object.

myrange(20)
## myrange(0, 20)

list(myrange(3, 10))
## [3, 4, 5, 6, 7, 8, 9]

list(myrange(0, 10))
## [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

list(myrange(10))
## [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

list(myrange(0, 10, 2))
## [0, 2, 4, 6, 8]

list(myrange(3, 10, 2))
## [3, 5, 7, 9]


问:
How can Java prevent duplicated number creation with Random class?
I'm learning Java by reading the book "JAVA, How To Program", and I have reached chapter 7 which talks about array and arrays manipulations. In section 7.5 (case study: card shuffling and dealing simulation), it presents a program that creates a deck of cards, shuffles it and displays the shuffled cards without any duplicates.

In the program it uses the method shuffle to shuffle the cards after creating them. The method uses random object to create a random number between 0 and 51 to select a card from the deck and assign it to an array. The code:

```<code> public void shuffle() {
     // after shuffling, dealing should start at deck[ 0 ] again
     currentCard = 0; // reinitialize currentCard

     // for each Card, pick another random Card (0-51) and swap them
     for (int first = 0; first < deck.length; first++) {
         // select a random number between 0 and 51
         int second = randomNumbers.nextInt( NUMBER_OF_CARDS );

         // swap current Card with randomly selected Card
         Card temp = deck[ first ];
         deck[ first ] = deck[ second ];
         deck[ second ] = temp;
    }
}
</code>```

What if int second = randomNumbers.nextInt( Number_OF_CARDS );
generates a random number that is already selected? Wouldn't be there any duplicates in the deck? If this not the case, why duplicated numbers are not given by this line? What am I missing?

I have learnt that random numbers are generated "almost" equally between the range given, but there is still a chance for generating a number that is already generated before.

答: This code doesn't pick cards from a deck and insert in a new list. Instead it swaps two random cards multiple times. The cards inside the deck are still "unique" to each other. That one of the index is selected more than one time is not a problem, it just gets swapped with another card. So in one case it might swap the cards at index 5 and 14 and in another for loop iteration, it might swap the cards at index 11 and 14. But in the end the deck contains the same cards, they are just not in the original order anymore.

Body:
I'm learning Java by reading the book "JAVA, How To Program", and I have reached chapter 7 which talks about array and arrays manipulations. In section 7.5 (case study: card shuffling and dealing simulation), it presents a program that creates a deck of cards, shuffles it and displays the shuffled cards without any duplicates.

In the program it uses the method shuffle to shuffle the cards after creating them. The method uses random object to create a random number between 0 and 51 to select a card from the deck and assign it to an array. The code:

 public void shuffle() {
     // after shuffling, dealing should start at deck[ 0 ] again
     currentCard = 0; // reinitialize currentCard

     // for each Card, pick another random Card (0-51) and swap them
     for (int first = 0; first < deck.length; first++) {
         // select a random number between 0 and 51
         int second = randomNumbers.nextInt( NUMBER_OF_CARDS );

         // swap current Card with randomly selected Card
         Card temp = deck[ first ];
         deck[ first ] = deck[ second ];
         deck[ second ] = temp;
    }
}

What if int second = randomNumbers.nextInt( Number_OF_CARDS );
generates a random number that is already selected? Wouldn't be there any duplicates in the deck? If this not the case, why duplicated numbers are not given by this line? What am I missing?

I have learnt that random numbers are generated "almost" equally between the range given, but there is still a chance for generating a number that is already generated before.


问:
How to connect to mq queue with python and bindings file?
I'm trying to connect with a remote MQ queue/serie and I only have a .bindings file to do it. I'm trying the python library "pymqi" but I can't connect using binding mode. Does someone knows what should I do or where should I place the file in order to use it with the library? Is there some other python solution to connect to the MQ queue?

this is a glimpse of my .bindings file:

```<code>JMSC/ClassName=com.ibm.mq.jms.MQQueueConnectionFactory
JMSC/FactoryName=com.ibm.mq.jms.MQQueueConnectionFactoryFactory
JMSC/RefAddr/0/Type=VER
JMSC/RefAddr/0/Encoding=String
JMSC/RefAddr/0/Content=7
JMSC/RefAddr/1/Type=TRAN
JMSC/RefAddr/1/Encoding=String
JMSC/RefAddr/1/Content=1
JMSC/RefAddr/2/Type=QMGR
JMSC/RefAddr/2/Encoding=String
JMSC/RefAddr/2/Content=MQFEND00
JMSC/RefAddr/3/Type=HOST
JMSC/RefAddr/3/Encoding=String
JMSC/RefAddr/3/Content=somehost
JMSC/RefAddr/4/Type=PORT
JMSC/RefAddr/4/Encoding=String
JMSC/RefAddr/4/Content=1414
JMSC/RefAddr/5/Type=CHAN
JMSC/RefAddr/5/Encoding=String
JMSC/RefAddr/5/Content=PORTALS.MQFEND00
</code>```

It has like 100 params, that are the first 6,

Thanks

update 22/05/2019:

I will add more information about what I try.
I tried to connect with bindings mode as I saw on the pymqi documentation:

```<code>qmgr = pymqi.connect('MQFEND00')
</code>```

And I get this error:

```<code>MQI Error. Comp: 2, Reason 2058: FAILED: MQRC_Q_MGR_NAME_ERROR
</code>```

I'm not sure if it's the queue_manager, someone knows how can I get the queue_manager from bindings file?

I've also tried to connect with host, channel and port:

```<code>qmgr = pymqi.connect(queue_manager, channel, conn_info)
</code>```

And I get an error of not authorized, I think it's because this second way is to connect with the client and I would need user and password which I haven't.

答:
If you want to use binding mode, you should setup pymqi with server or binding parameters. You can not use binding and client mode simultaneously:

```<code>#From pymqi folder
cd ./code
./setup.py build server
</code>```

I am not sure, that you can use .bindings file with pymqi without parsing it himself.

Body:
I'm trying to connect with a remote MQ queue/serie and I only have a .bindings file to do it. I'm trying the python library "pymqi" but I can't connect using binding mode. Does someone knows what should I do or where should I place the file in order to use it with the library? Is there some other python solution to connect to the MQ queue?

this is a glimpse of my .bindings file:

JMSC/ClassName=com.ibm.mq.jms.MQQueueConnectionFactory
JMSC/FactoryName=com.ibm.mq.jms.MQQueueConnectionFactoryFactory
JMSC/RefAddr/0/Type=VER
JMSC/RefAddr/0/Encoding=String
JMSC/RefAddr/0/Content=7
JMSC/RefAddr/1/Type=TRAN
JMSC/RefAddr/1/Encoding=String
JMSC/RefAddr/1/Content=1
JMSC/RefAddr/2/Type=QMGR
JMSC/RefAddr/2/Encoding=String
JMSC/RefAddr/2/Content=MQFEND00
JMSC/RefAddr/3/Type=HOST
JMSC/RefAddr/3/Encoding=String
JMSC/RefAddr/3/Content=somehost
JMSC/RefAddr/4/Type=PORT
JMSC/RefAddr/4/Encoding=String
JMSC/RefAddr/4/Content=1414
JMSC/RefAddr/5/Type=CHAN
JMSC/RefAddr/5/Encoding=String
JMSC/RefAddr/5/Content=PORTALS.MQFEND00

It has like 100 params, that are the first 6,

Thanks

update 22/05/2019:

I will add more information about what I try.
I tried to connect with bindings mode as I saw on the pymqi documentation:

qmgr = pymqi.connect('MQFEND00')

And I get this error:

MQI Error. Comp: 2, Reason 2058: FAILED: MQRC_Q_MGR_NAME_ERROR

I'm not sure if it's the queue_manager, someone knows how can I get the queue_manager from bindings file?

I've also tried to connect with host, channel and port:

qmgr = pymqi.connect(queue_manager, channel, conn_info)

And I get an error of not authorized, I think it's because this second way is to connect with the client and I would need user and password which I haven't.

Body:
If you want to use binding mode, you should setup pymqi with server or binding parameters. You can not use binding and client mode simultaneously:

#From pymqi folder
cd ./code
./setup.py build server

I am not sure, that you can use .bindings file with pymqi without parsing it himself.


问:
SyntaxError: Unexpected identifier import bodyParser from 'body-parser'; … In REACT JS app
Create react app on Express originally built using the CRA-E for Heroku instructions here https://originmaster.com/running-create-react-app-and-express-crae-on-heroku-c39a39fe7851

Locally I can see this error, but my app serves requests correctly anyway. When deploy this on Heroku,  I also see this same error, and then for any request I get an H10 "App crashed" in the Heroku logs.

```<code>2019-05-26T18:12:00.682298+00:00 app[web.1]: (function (exports, require, module, __filename, __dirname) { import bodyParser from 'body-parser';
2019-05-26T18:12:00.682300+00:00 app[web.1]: ^^^^^^^^^^
2019-05-26T18:12:00.682302+00:00 app[web.1]:
2019-05-26T18:12:00.682304+00:00 app[web.1]: SyntaxError: Unexpected identifier
2019-05-26T18:12:00.682305+00:00 app[web.1]: at new Script (vm.js:84:7)
2019-05-26T18:12:00.682308+00:00 app[web.1]: at createScript (vm.js:264:10)
2019-05-26T18:12:00.682310+00:00 app[web.1]: at Object.runInThisContext (vm.js:312:10)
2019-05-26T18:12:00.682312+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:696:28)
2019-05-26T18:12:00.682313+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:747:10)
2019-05-26T18:12:00.682318+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:628:32)
2019-05-26T18:12:00.682319+00:00 app[web.1]: at tryModuleLoad (internal/modules/cjs/loader.js:568:12)
2019-05-26T18:12:00.682321+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:560:3)
2019-05-26T18:12:00.682323+00:00 app[web.1]: at Function.Module.runMain (internal/modules/cjs/loader.js:801:12)
2019-05-26T18:12:00.682324+00:00 app[web.1]: at executeUserCode (internal/bootstrap/node.js:526:15)
2019-05-26T18:12:00.699031+00:00 app[web.1]: error Command failed with exit code 1.
2019-05-26T18:12:00.699246+00:00 app[web.1]: info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
2019-05-26T18:12:00.728654+00:00 app[web.1]: error Command failed with exit code 1.
2019-05-26T18:12:00.728814+00:00 app[web.1]: info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
2019-05-26T18:12:00.796019+00:00 heroku[web.1]: Process exited with status 1
2019-05-26T18:12:00.814020+00:00 heroku[web.1]: State changed from starting to crashed
</code>```

the app was created following these CRA-E instructions for Heroku: https://originmaster.com/running-create-react-app-and-express-crae-on-heroku-c39a39fe7851

The root package.json file is

```<code>{
  "name": "xxxxxxxxxxxxxx-front",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "bootstrap": "^4.2.1",
    "concurrently": "^4.1.0"
  },
  "scripts": {
    "build": "concurrently \"cd client && yarn build\" \"cd server && yarn build\"",
    "clean": "concurrently \"rimraf node_modules\" \"cd client && rimraf node_modules build\" \"cd server && rimraf node_modules build\"",
    "heroku-postbuild": "yarn build",
    "install": "(cd client && yarn) && (cd server && yarn)",
    "start": "concurrently \"cd client && PORT=3000 yarn start\" \"cd server && PORT=3001 yarn start\"",
    "start:prod": "cd server && yarn start:prod"
  },
  "engines": {
    "node": "11.8.0"
  }
}
</code>```

the client/ package.json is

```<code>{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://localhost:3001",
  "dependencies": {
    "boostrap": "^2.0.0",
    "bootstrap": "^4.3.1",
    "case-sensitive-paths-webpack-plugin": "^2.2.0",
    "d3-hierarchy": "^1.1.8",
    "d3-selection": "^1.4.0",
    "d3-tree": "^1.0.20",
    "node-sass": "^4.11.0",
    "prop-types": "^15.7.2",
    "react": "^16.8.4",
    "react-bootstrap-typeahead": "^3.4.1",
    "react-dom": "^16.8.4",
    "react-scripts": "2.1.8",
    "reactstrap": "^6.5.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ],
  "main": "index.js",
  "license": "SEE LICENSE IN LICENSE.md",
  "author": "Jason Fleetwood-Boldt"
}
</code>```

the server/ pacakge.json file is

```<code>{
  "name": "server",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "babel-cli": "^6.26.0",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
    "body-parser": "^1.18.3",
    "express": "^4.16.4"
  },
  "devDependencies": {
    "babel-register": "^6.26.0",
    "nodemon": "^1.18.9"
  },
  "scripts": {
    "start": "nodemon -r babel-register server.js",
    "build": "babel . --ignore node_modules,build --out-dir build",
    "start:prod": "node build/server.js"
  }
}
</code>```

the server/server.js file is

```<code>import bodyParser from 'body-parser'
import express from 'express'
import path from 'path'
const app = express()

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))

const router = express.Router()

const staticFiles = express.static(path.join(__dirname, '../../client/build'))
app.use(staticFiles)

app.use(router)

// any routes not picked up by the server api will be handled by the react router
app.use('/*', staticFiles)

app.set('port', (process.env.PORT || 3001))

app.listen(app.get('port'), () => {
  console.log(`Listening on ${app.get('port')}`)
})
</code>```

答:
If you want to use import statements in a nodejs app, your code needs to be transpiled by babel before it's run. You seem to have installed the babel packages, but you haven't set up a .babelrc file. Try creating a .babelrc file in the server directory with the following contents:

```<code>{
   "presets": ["es2015", "stage-0"],
   "plugins": ["transform-runtime"]
}
</code>```

Body:
Create react app on Express originally built using the CRA-E for Heroku instructions here https://originmaster.com/running-create-react-app-and-express-crae-on-heroku-c39a39fe7851

Locally I can see this error, but my app serves requests correctly anyway. When deploy this on Heroku,  I also see this same error, and then for any request I get an H10 "App crashed" in the Heroku logs.

2019-05-26T18:12:00.682298+00:00 app[web.1]: (function (exports, require, module, __filename, __dirname) { import bodyParser from 'body-parser';
2019-05-26T18:12:00.682300+00:00 app[web.1]: ^^^^^^^^^^
2019-05-26T18:12:00.682302+00:00 app[web.1]:
2019-05-26T18:12:00.682304+00:00 app[web.1]: SyntaxError: Unexpected identifier
2019-05-26T18:12:00.682305+00:00 app[web.1]: at new Script (vm.js:84:7)
2019-05-26T18:12:00.682308+00:00 app[web.1]: at createScript (vm.js:264:10)
2019-05-26T18:12:00.682310+00:00 app[web.1]: at Object.runInThisContext (vm.js:312:10)
2019-05-26T18:12:00.682312+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:696:28)
2019-05-26T18:12:00.682313+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:747:10)
2019-05-26T18:12:00.682318+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:628:32)
2019-05-26T18:12:00.682319+00:00 app[web.1]: at tryModuleLoad (internal/modules/cjs/loader.js:568:12)
2019-05-26T18:12:00.682321+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:560:3)
2019-05-26T18:12:00.682323+00:00 app[web.1]: at Function.Module.runMain (internal/modules/cjs/loader.js:801:12)
2019-05-26T18:12:00.682324+00:00 app[web.1]: at executeUserCode (internal/bootstrap/node.js:526:15)
2019-05-26T18:12:00.699031+00:00 app[web.1]: error Command failed with exit code 1.
2019-05-26T18:12:00.699246+00:00 app[web.1]: info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
2019-05-26T18:12:00.728654+00:00 app[web.1]: error Command failed with exit code 1.
2019-05-26T18:12:00.728814+00:00 app[web.1]: info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
2019-05-26T18:12:00.796019+00:00 heroku[web.1]: Process exited with status 1
2019-05-26T18:12:00.814020+00:00 heroku[web.1]: State changed from starting to crashed

the app was created following these CRA-E instructions for Heroku: https://originmaster.com/running-create-react-app-and-express-crae-on-heroku-c39a39fe7851

The root package.json file is

{
  "name": "xxxxxxxxxxxxxx-front",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "bootstrap": "^4.2.1",
    "concurrently": "^4.1.0"
  },
  "scripts": {
    "build": "concurrently \"cd client && yarn build\" \"cd server && yarn build\"",
    "clean": "concurrently \"rimraf node_modules\" \"cd client && rimraf node_modules build\" \"cd server && rimraf node_modules build\"",
    "heroku-postbuild": "yarn build",
    "install": "(cd client && yarn) && (cd server && yarn)",
    "start": "concurrently \"cd client && PORT=3000 yarn start\" \"cd server && PORT=3001 yarn start\"",
    "start:prod": "cd server && yarn start:prod"
  },
  "engines": {
    "node": "11.8.0"
  }
}

the client/ package.json is

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://localhost:3001",
  "dependencies": {
    "boostrap": "^2.0.0",
    "bootstrap": "^4.3.1",
    "case-sensitive-paths-webpack-plugin": "^2.2.0",
    "d3-hierarchy": "^1.1.8",
    "d3-selection": "^1.4.0",
    "d3-tree": "^1.0.20",
    "node-sass": "^4.11.0",
    "prop-types": "^15.7.2",
    "react": "^16.8.4",
    "react-bootstrap-typeahead": "^3.4.1",
    "react-dom": "^16.8.4",
    "react-scripts": "2.1.8",
    "reactstrap": "^6.5.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ],
  "main": "index.js",
  "license": "SEE LICENSE IN LICENSE.md",
  "author": "Jason Fleetwood-Boldt"
}

the server/ pacakge.json file is

{
  "name": "server",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "babel-cli": "^6.26.0",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
    "body-parser": "^1.18.3",
    "express": "^4.16.4"
  },
  "devDependencies": {
    "babel-register": "^6.26.0",
    "nodemon": "^1.18.9"
  },
  "scripts": {
    "start": "nodemon -r babel-register server.js",
    "build": "babel . --ignore node_modules,build --out-dir build",
    "start:prod": "node build/server.js"
  }
}

the server/server.js file is

import bodyParser from 'body-parser'
import express from 'express'
import path from 'path'
const app = express()

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))

const router = express.Router()

const staticFiles = express.static(path.join(__dirname, '../../client/build'))
app.use(staticFiles)

app.use(router)

// any routes not picked up by the server api will be handled by the react router
app.use('/*', staticFiles)

app.set('port', (process.env.PORT || 3001))

app.listen(app.get('port'), () => {
  console.log(`Listening on ${app.get('port')}`)
})

Body:
If you want to use import statements in a nodejs app, your code needs to be transpiled by babel before it's run. You seem to have installed the babel packages, but you haven't set up a .babelrc file. Try creating a .babelrc file in the server directory with the following contents:

{
   "presets": ["es2015", "stage-0"],
   "plugins": ["transform-runtime"]
}


问:
How to extract an ID number from a string?
How do I retrieve the middle value using regex or preg_match?

```<code>$str = 'fxs_124024574287414=base_domain=.example.com; datr=KWHazxXEIkldzBaVq_of--syv5; csrftoken=szcwad; ds_user_id=219132; mid=XN4bpAAEAAHOyBRR4V17xfbaosyN; sessionid=14811313756%12fasda%3A27; rur=VLL;'
</code>```

How do I only get values from ds_user_id using regex or preg_match?

答:
If we wish to use explode:

```<code>$str = 'fxs_124024574287414=base_domain=.example.com; datr=KWHazxXEIkldzBaVq_of--syv5; csrftoken=szcwad; ds_user_id=219132; mid=XN4bpAAEAAHOyBRR4V17xfbaosyN; sessionid=14811313756%12fasda%3A27; rur=VLL;';

$arr = explode(';', $str);

foreach ($arr as $key => $value) {
    if (preg_match('/ds_user_id/s', $value)) {
        $ds_user_id = explode('=', $value);
        echo $ds_user_id[1];
    }
}
</code>```

Output

```<code>219132
</code>```

Here, we can also use two non-capturing groups with a capturing group:

```<code>(?:ds_user_id=)(.+?)(?:;)
</code>```

where we have a left boundary:

```<code>(?:ds_user_id=)
</code>```

and a right boundary:

```<code>(?:;)
</code>```

and we collect our desired digits or anything else that we wish to have using:

```<code>(.+?)
</code>```

If we wish to validate our ID number, we can use:

```<code>(?:ds_user_id=)([0-9]+?)(?:;)
</code>```

DEMO

and our desired value can be simply called using var_dump($matches[0][1]);.

Test

```<code>$re = '/(?:ds_user_id=)(.+?)(?:;)/m';
$str = 'fxs_124024574287414=base_domain=.example.com; datr=KWHazxXEIkldzBaVq_of--syv5; csrftoken=szcwad; ds_user_id=219132; mid=XN4bpAAEAAHOyBRR4V17xfbaosyN; sessionid=14811313756%12fasda%3A27; rur=VLL;';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
var_dump($matches);
</code>```

Output

```<code>array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(18) "ds_user_id=219132;"
    [1]=>
    string(6) "219132"
  }
}
</code>```

DEMO

Body:
How do I retrieve the middle value using regex or preg_match?

$str = 'fxs_124024574287414=base_domain=.example.com; datr=KWHazxXEIkldzBaVq_of--syv5; csrftoken=szcwad; ds_user_id=219132; mid=XN4bpAAEAAHOyBRR4V17xfbaosyN; sessionid=14811313756%12fasda%3A27; rur=VLL;'

How do I only get values from ds_user_id using regex or preg_match?

Body:
If we wish to use explode:

$str = 'fxs_124024574287414=base_domain=.example.com; datr=KWHazxXEIkldzBaVq_of--syv5; csrftoken=szcwad; ds_user_id=219132; mid=XN4bpAAEAAHOyBRR4V17xfbaosyN; sessionid=14811313756%12fasda%3A27; rur=VLL;';

$arr = explode(';', $str);

foreach ($arr as $key => $value) {
    if (preg_match('/ds_user_id/s', $value)) {
        $ds_user_id = explode('=', $value);
        echo $ds_user_id[1];
    }
}

Output

219132

Here, we can also use two non-capturing groups with a capturing group:

(?:ds_user_id=)(.+?)(?:;)

where we have a left boundary:

(?:ds_user_id=)

and a right boundary:

(?:;)

and we collect our desired digits or anything else that we wish to have using:

(.+?)

If we wish to validate our ID number, we can use:

(?:ds_user_id=)([0-9]+?)(?:;)

DEMO

and our desired value can be simply called using var_dump($matches[0][1]);.

Test

$re = '/(?:ds_user_id=)(.+?)(?:;)/m';
$str = 'fxs_124024574287414=base_domain=.example.com; datr=KWHazxXEIkldzBaVq_of--syv5; csrftoken=szcwad; ds_user_id=219132; mid=XN4bpAAEAAHOyBRR4V17xfbaosyN; sessionid=14811313756%12fasda%3A27; rur=VLL;';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
var_dump($matches);

Output

array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(18) "ds_user_id=219132;"
    [1]=>
    string(6) "219132"
  }
}

DEMO