问:
How to update "select-editable" value through other html elements
I have a web application which has a zoom-in, zoom-out and zoom-by feature, which I have implemented as below :

HTML

```<code><ul class="canvas-zoom">
    <li id="id_zoom_in"><span class="icon-Icon-ZoomIn"></span><span class="lblText">Zoom In</span></li>
    <li id="id_zoom_out"><span class="icon-Icon-ZoomOut"></span><span class="lblText">Zoom Out</span>
    </li>
    <li>
        <div class="select-editable">
            <select id="id_zoom_select" class="zoom-combo-box" >
                <option value="25">25%</option>
                <option value="50">50%</option>
                <option value="66">66%</option>
                <option value="75">75%</option>
                <option value="100">100%</option>
                <option value="Fit" selected>Fit</option>
            </select>
            <input type="text" id="id_zoom_text" value="" maxlength="4" />
        </div>

        <span class="lblText">Zoom By</span>
    </li>
</ul>
</code>```

JS

```<code>  zoom: function (event) {
        var textElem = $('.canvas-zoom #id_zoom_text'),
            selectElem = $('.canvas-zoom #id_zoom_select');

        if (this.id == "id_zoom_in") {

            var zoom_in = parseInt(textElem.val()) + 10;
            console.log("value of zoom is : " + zoom_in );
            textElem.val(zoom_in + "%");
            selectElem.val(zoom_in);
            console.log("value of zoom by should be : " + textElem.val());
            textElem.trigger('change');
        }
        else if (this.id == "id_zoom_out") {
            var zoom_out = parseInt(textElem.val()) - 10;
            console.log("value of zoom is : " + zoom_out );
            textElem.val(zoom_out + "%");
            selectElem.val(zoom_out);
            textElem.trigger('change');
        }
        else if (this.id == "id_zoom_select") {
            var zoomValue = $(this).val();
            textElem.val(zoomValue + "%");
            textElem.trigger('change');
        }
        else if (this.id == "id_zoom_text") {
            var percent = textElem.val();
            //validate the input text
            if (/^[0-9%]+$/.test(percent) && percent.indexOf("%") !== 0) {
                var symbolCount = percent.match(/%/g) || [].length;
                //append % if only numeric is entered
                if (symbolCount == 0)
                    textElem.val(percent + "%");
                percent = parseInt(percent);
                if (percent < ZOOM_MIN)
                    percent = ZOOM_MIN;
                //else if (percent > ZOOM_MAX)
                //    percent = ZOOM_MAX
            }
            else
                percent = ZOOM_MAX;

            textElem.val(percent + "%");
            selectElem.val(percent);
            ContentEditor.setCanvasArea(percent);

        }
    }
</code>```

I am able to select the zoom percentage from zoom-by like so :

However, when I hit zoom-in or zoom-out, the zoom-by text doesn't update, unless the zoom-in/out percentage coincides with one of the preset options in the html code [25,50,66,75,100, "Fit"]

I was able to add some console.log to verify that if the zoom-in/out percentage is not one of the presets the text in zoom-by doesn't change. Ideally I would like that if the zoom-in increases the zoom percentage to 72% then the zoom-by text should show that value instead of a blank, as shown in the screenshot.

Is there a way I can implement the functionality I want to? Thanks in advance!

答:
I was only able to come up with this - I hope it's exactly what you're looking for.
To avoid errors I've ran a few if statements to ensure that the zoom values matter throughout the process. Check JSFiddle here

$(function(){
  //  Get all Zoom Controls
  var zoomInElement = $("#id_zoom_in");
  var zoomOutElement = $("#id_zoom_out");
  var zoomByElement = $("#id_zoom_select");
  var zoomValueTextElement = $("#id_zoom_text");

  function getZoomValue(){
    return zoomValueTextElement.attr("value");
  }

  function setZoomValue(value){
    zoomValueTextElement.attr("value", value);
  }

  zoomByElement.on('change',
    (e)=>{
      setZoomValue(e.target.value);
    }
  );

  zoomInElement.on('click', ()=>{
    // First Get the current Value
    var tempVal = getZoomValue();
    // Esnure that before performing any calculations, the current zoomvalue is not "Fit"
    if(tempVal != "Fit")
    {
     tempVal = parseInt(tempVal);
      //Before you increase by 10,  ensure that the zoom is not at 100%
      if(tempVal <= 100)
      {
        // Then increase
        tempVal += 10;

        //Check if the zoom is not over 100% after incrementing by 10
        if(tempVal > 100)
        {
          // then set the zoom to Max
          tempVal = "Fit";
        }
      }
    }
    setZoomValue(tempVal.toString());
  });

  zoomOutElement.on('click', ()=>{
    // First Get the current Value
    var tempVal = getZoomValue();

    // Esnure that before performing any calculations, the current zoomvalue is not "Fit"
    if(tempVal != "Fit")
    {
     // Convert value to integer
     tempVal = parseInt(tempVal);

      //Before you derease,  ensure that the zoom is not less than 0%
      if(tempVal > 0)
      {
        // Then decrease by 10
        tempVal -= 10;

        //Check if the zoom is not below 0% after decreasing by 10
        if(tempVal < 0)
        {
          // then set the zoom to Max
          tempVal = 0;
        }
      }
    }else{
      tempVal = 100;
    }
    setZoomValue(tempVal);
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.zoom-button{
  display: block;
  padding: 15px;
  width: 120px;
  border: thin solid #e1e1e1;
  margin: 10px 0;
  cursor: pointer;
}

.zoom-button:hover{
  background-color: #f5f5f5;
}</code>```

Zoom In

Zoom Out

   <select id="id_zoom_select" class="zoom-combo-box" >
    <option value="25">25%</option>
    <option value="50">50%</option>
    <option value="66">66%</option>
    <option value="75">75%</option>
    <option value="100">100%</option>
    <option value="Fit" selected>Fit</option>
   </select>

  Zoom By

Current Zoom Value:
   <input type="text" id="id_zoom_text" value="Fit" maxlength="4" />

```

Body:
I have a web application which has a zoom-in, zoom-out and zoom-by feature, which I have implemented as below :

HTML

Zoom In

Zoom Out

            <select id="id_zoom_select" class="zoom-combo-box" >
                <option value="25">25%</option>
                <option value="50">50%</option>
                <option value="66">66%</option>
                <option value="75">75%</option>
                <option value="100">100%</option>
                <option value="Fit" selected>Fit</option>
            </select>
            <input type="text" id="id_zoom_text" value="" maxlength="4" />

        Zoom By

JS

  zoom: function (event) {
        var textElem = $('.canvas-zoom #id_zoom_text'),
            selectElem = $('.canvas-zoom #id_zoom_select');

        if (this.id == "id_zoom_in") {

            var zoom_in = parseInt(textElem.val()) + 10;
            console.log("value of zoom is : " + zoom_in );
            textElem.val(zoom_in + "%");
            selectElem.val(zoom_in);
            console.log("value of zoom by should be : " + textElem.val());
            textElem.trigger('change');
        }
        else if (this.id == "id_zoom_out") {
            var zoom_out = parseInt(textElem.val()) - 10;
            console.log("value of zoom is : " + zoom_out );
            textElem.val(zoom_out + "%");
            selectElem.val(zoom_out);
            textElem.trigger('change');
        }
        else if (this.id == "id_zoom_select") {
            var zoomValue = $(this).val();
            textElem.val(zoomValue + "%");
            textElem.trigger('change');
        }
        else if (this.id == "id_zoom_text") {
            var percent = textElem.val();
            //validate the input text
            if (/^[0-9%]+$/.test(percent) && percent.indexOf("%") !== 0) {
                var symbolCount = percent.match(/%/g) || [].length;
                //append % if only numeric is entered
                if (symbolCount == 0)
                    textElem.val(percent + "%");
                percent = parseInt(percent);
                if (percent < ZOOM_MIN)
                    percent = ZOOM_MIN;
                //else if (percent > ZOOM_MAX)
                //    percent = ZOOM_MAX
            }
            else
                percent = ZOOM_MAX;

            textElem.val(percent + "%");
            selectElem.val(percent);
            ContentEditor.setCanvasArea(percent);

        }
    }

I am able to select the zoom percentage from zoom-by like so :

However, when I hit zoom-in or zoom-out, the zoom-by text doesn't update, unless the zoom-in/out percentage coincides with one of the preset options in the html code [25,50,66,75,100, "Fit"]

I was able to add some console.log to verify that if the zoom-in/out percentage is not one of the presets the text in zoom-by doesn't change. Ideally I would like that if the zoom-in increases the zoom percentage to 72% then the zoom-by text should show that value instead of a blank, as shown in the screenshot.

Is there a way I can implement the functionality I want to? Thanks in advance!

Body:
I was only able to come up with this - I hope it's exactly what you're looking for.
To avoid errors I've ran a few if statements to ensure that the zoom values matter throughout the process. Check JSFiddle here

$(function(){
  //  Get all Zoom Controls
  var zoomInElement = $("#id_zoom_in");
  var zoomOutElement = $("#id_zoom_out");
  var zoomByElement = $("#id_zoom_select");
  var zoomValueTextElement = $("#id_zoom_text");

  function getZoomValue(){
    return zoomValueTextElement.attr("value");
  }

  function setZoomValue(value){
    zoomValueTextElement.attr("value", value);
  }

  zoomByElement.on('change',
    (e)=>{
      setZoomValue(e.target.value);
    }
  );

  zoomInElement.on('click', ()=>{
    // First Get the current Value
    var tempVal = getZoomValue();
    // Esnure that before performing any calculations, the current zoomvalue is not "Fit"
    if(tempVal != "Fit")
    {
     tempVal = parseInt(tempVal);
      //Before you increase by 10,  ensure that the zoom is not at 100%
      if(tempVal <= 100)
      {
        // Then increase
        tempVal += 10;

        //Check if the zoom is not over 100% after incrementing by 10
        if(tempVal > 100)
        {
          // then set the zoom to Max
          tempVal = "Fit";
        }
      }
    }
    setZoomValue(tempVal.toString());
  });

  zoomOutElement.on('click', ()=>{
    // First Get the current Value
    var tempVal = getZoomValue();

    // Esnure that before performing any calculations, the current zoomvalue is not "Fit"
    if(tempVal != "Fit")
    {
     // Convert value to integer
     tempVal = parseInt(tempVal);

      //Before you derease,  ensure that the zoom is not less than 0%
      if(tempVal > 0)
      {
        // Then decrease by 10
        tempVal -= 10;

        //Check if the zoom is not below 0% after decreasing by 10
        if(tempVal < 0)
        {
          // then set the zoom to Max
          tempVal = 0;
        }
      }
    }else{
      tempVal = 100;
    }
    setZoomValue(tempVal);
  });

});

.zoom-button{
  display: block;
  padding: 15px;
  width: 120px;
  border: thin solid #e1e1e1;
  margin: 10px 0;
  cursor: pointer;
}

.zoom-button:hover{
  background-color: #f5f5f5;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="canvas-zoom">
 <li id="id_zoom_in" class="zoom-button"><span class="icon-Icon-ZoomIn"></span><span class="lblText">Zoom In</span></li>
 <li id="id_zoom_out" class="zoom-button"><span class="icon-Icon-ZoomOut"></span><span class="lblText">Zoom Out</span>
 </li>
 <li>
  <div class="select-editable">
   <select id="id_zoom_select" class="zoom-combo-box" >
    <option value="25">25%</option>
    <option value="50">50%</option>
    <option value="66">66%</option>
    <option value="75">75%</option>
    <option value="100">100%</option>
    <option value="Fit" selected>Fit</option>
   </select>
  </div>
  <span class="lblText">Zoom By</span>
 </li>
  <li>Current Zoom Value:
   <input type="text" id="id_zoom_text" value="Fit" maxlength="4" /></li>
</ul>


来源: stackexchange

问:
Amazon S3 Write Only access
I'm backing up files from several customers directly into an Amazon S3 bucket - each customer to a different folder. I'm using a simple .Net client running under a Windows task once a night. To allow writing to the bucket, my client requires both the AWS access key and the secret key (I created a new pair).

My problem is:

How do I make sure none of my customers could potentially use the pair to peek in the bucket and in a folder not his own? Can I create a "write only" access pair?

Am I approaching this the right way? Should this be solved through AWS access settings, or should I client-side encrypt files on the customer's machine (each customer with a different key) prior to uploading and avoid a the above mentioned cross-access?

答:
As a variation on the approach recommended in Charles' answer, you can also manage access control at the user level via SFTP.  These users can all share the same global IAM policy:

SFTP does support user-specific home directories (akin to "chroot").

SFTP allows you to manage user access via service managed authentication or via your own authentication provider.  I am unsure if service managed authentication has user limits.

If you wish to allow users to access uploaded files using a client, SFTP provides it very cleanly.

ContentLicense: CC BY-SA 3.0

Title: Amazon S3 Write Only access

ContentLicense: CC BY-SA 4.0


问:
Can you join three tables on the same key if that key could be missing from one or more of the tables?
I'm taking three tables and joining them all together using the same primary key, but with no guarantee that all values exist across all three tables, and I want every value to end up in the final join.

For example, there's a TableA, TableB, and TableC, each with only one column (we'll just call the columns colA, colB, and colC). Value 10 is present in TableA and TableC, but not TableB.

```<code>SELECT * FROM TableA FULL OUTER JOIN TableB ON TableA.colA = TableB.colB
                     FULL OUTER JOIN TableC ON TableB.colB = TableC.colC;

+--------+  +--------+  +--------+
|  colA  |  |  colB  |  |  colC  |
+--------+  +--------+  +--------+
|      5 |  |      5 |  |      5 |
|     10 |  |     15 |  |     10 |
|     15 |  +--------+  |     15 |
+--------+              +--------+
</code>```

In the above example, I end up with something like this after the joins:

```<code>+--------+--------+--------+
|  colA  |  colB  |  colC  |
+--------+--------+--------+
| 5      | 5      | 5      |
| null   | null   | 10     |
| 15     | 15     | 15     |
| 10     | null   | null   |
+--------+--------+--------+
</code>```

My expected result is this:

```<code>+--------+--------+--------+
|  colA  |  colB  |  colC  |
+--------+--------+--------+
|      5 | 5      |      5 |
|     10 | null   |     10 |
|     15 | 15     |     15 |
+--------+--------+--------+
</code>```

The logic for my join is to first join TableA and TableB, then join the result with TableC. In this specific scenario, the join does not work. The join can try to match on the column passed through from TableA or the column from TableB, but I'm not sure how to make it check both.

Because I first joined TableA and TableB, there was no matching value in TableB. When I try to join TableC on TableB, it also finds no match, even though the key exists in TableA.

The closest I've gotten to my desired result is by using this query:

```<code>SELECT * FROM TableA FULL OUTER JOIN TableB ON TableA.colA = TableB.colB
                     RIGHT OUTER JOIN TableC ON TableC.colC IN (TableA.colA, TableB.colB);

+------+  +------+  +------+     +------+------+------+
| colA |  | colB |  | colC |     | colA | colB | colC |
+------+  +------+  +------+     +------+------+------+
|    5 |  |    5 |  |    5 |     | 5    | 5    |    5 |
|   10 |  |   15 |  |   10 | --> | 10   | null |   10 |
|   15 |  |   25 |  |   15 |     | 15   | 15   |   15 |
+------+  +------+  |   20 |     | null | null |   20 |
                    +------+     +------+------+------+
</code>```

Expected result:

```<code>+------+------+------+
| colA | colB | colC |
+------+------+------+
| 5    | 5    | 5    |
| 10   | null | 10   |
| 15   | 15   | 15   |
| null | null | 20   |
| null | 25   | null |
+------+------+------+
</code>```

This, unfortunately, does not include values that only exist in TableA or TableB in the final joined table, which is why I was using the FULL OUTER JOIN in the first place. With the FULL OUTER JOIN, I can't use the IN clause. Is there a solution that gives me what I want?

DB Fiddle: https://www.db-fiddle.com/f/faMLh4EAAKfBotXbaDofaQ/1

答:
This join combination will give you your desired results:

```<code>select *
from (SELECT *
      FROM TableC
      full outer join TableB on TableC.colC = TableB.colB ) t1
left join TableA on t1.colc = TableA.colA or  t1.colB = TableA.colA
</code>```

Here is a demo

It was a different join you needed. Here is another example:

```<code>select * from
(SELECT *
FROM TableC
full outer join TableB on TableC.colC = TableB.colB ) t1
full join TableA on t1.colc = TableA.colA
</code>```

Here is a demo

Body:
I'm taking three tables and joining them all together using the same primary key, but with no guarantee that all values exist across all three tables, and I want every value to end up in the final join.

For example, there's a TableA, TableB, and TableC, each with only one column (we'll just call the columns colA, colB, and colC). Value 10 is present in TableA and TableC, but not TableB.

SELECT * FROM TableA FULL OUTER JOIN TableB ON TableA.colA = TableB.colB
                     FULL OUTER JOIN TableC ON TableB.colB = TableC.colC;

+--------+  +--------+  +--------+
|  colA  |  |  colB  |  |  colC  |
+--------+  +--------+  +--------+
|      5 |  |      5 |  |      5 |
|     10 |  |     15 |  |     10 |
|     15 |  +--------+  |     15 |
+--------+              +--------+

In the above example, I end up with something like this after the joins:

+--------+--------+--------+
|  colA  |  colB  |  colC  |
+--------+--------+--------+
| 5      | 5      | 5      |
| null   | null   | 10     |
| 15     | 15     | 15     |
| 10     | null   | null   |
+--------+--------+--------+

My expected result is this:

+--------+--------+--------+
|  colA  |  colB  |  colC  |
+--------+--------+--------+
|      5 | 5      |      5 |
|     10 | null   |     10 |
|     15 | 15     |     15 |
+--------+--------+--------+

The logic for my join is to first join TableA and TableB, then join the result with TableC. In this specific scenario, the join does not work. The join can try to match on the column passed through from TableA or the column from TableB, but I'm not sure how to make it check both.

Because I first joined TableA and TableB, there was no matching value in TableB. When I try to join TableC on TableB, it also finds no match, even though the key exists in TableA.

The closest I've gotten to my desired result is by using this query:

SELECT * FROM TableA FULL OUTER JOIN TableB ON TableA.colA = TableB.colB
                     RIGHT OUTER JOIN TableC ON TableC.colC IN (TableA.colA, TableB.colB);

+------+  +------+  +------+     +------+------+------+
| colA |  | colB |  | colC |     | colA | colB | colC |
+------+  +------+  +------+     +------+------+------+
|    5 |  |    5 |  |    5 |     | 5    | 5    |    5 |
|   10 |  |   15 |  |   10 | --> | 10   | null |   10 |
|   15 |  |   25 |  |   15 |     | 15   | 15   |   15 |
+------+  +------+  |   20 |     | null | null |   20 |
                    +------+     +------+------+------+

Expected result:

+------+------+------+
| colA | colB | colC |
+------+------+------+
| 5    | 5    | 5    |
| 10   | null | 10   |
| 15   | 15   | 15   |
| null | null | 20   |
| null | 25   | null |
+------+------+------+

This, unfortunately, does not include values that only exist in TableA or TableB in the final joined table, which is why I was using the FULL OUTER JOIN in the first place. With the FULL OUTER JOIN, I can't use the IN clause. Is there a solution that gives me what I want?

DB Fiddle: https://www.db-fiddle.com/f/faMLh4EAAKfBotXbaDofaQ/1

Body:
This join combination will give you your desired results:

select *
from (SELECT *
      FROM TableC
      full outer join TableB on TableC.colC = TableB.colB ) t1
left join TableA on t1.colc = TableA.colA or  t1.colB = TableA.colA

Here is a demo

It was a different join you needed. Here is another example:

select * from
(SELECT *
FROM TableC
full outer join TableB on TableC.colC = TableB.colB ) t1
full join TableA on t1.colc = TableA.colA

Here is a demo


问:
Split Dataframe into list of one-row Dataframes
I would like to split a dataframe

```<code>df <- data.frame(a = 1:4, b = letters[1:4])

  a b
1 1 a
2 2 b
3 3 c
4 4 d
</code>```

into a list of one-row dataframes

```<code>list(
    data.frame(a = 1, b = letters[1])
    , data.frame(a = 2, b = letters[2])
    , data.frame(a = 3, b = letters[3])
    , data.frame(a = 4, b = letters[4])
)

[[1]]
  a b
1 1 a

[[2]]
  a b
1 2 b

[[3]]
  a b
1 3 c

[[4]]
  a b
1 4 d
</code>```

Is there an elegant solution to this?

答:
It would be with asplit

```<code>lapply(asplit(df, 1), as.data.frame.list)
#[[1]]
#  a b
#1 1 a

#[[2]]
#  a b
#1 2 b

#[[3]]
#  a b
#1 3 c

#[[4]]
#  a b
#1 4 d
</code>```

Or with pmap

```<code>library(purrr)
pmap(df, tibble)
#[[1]]
# A tibble: 1 x 2
#      a b
#  <int> <fct>
#1     1 a

#[[2]]
# A tibble: 1 x 2
#      a b
#  <int> <fct>
#1     2 b

#[[3]]
# A tibble: 1 x 2
#      a b
#  <int> <fct>
#1     3 c

#[[4]]
# A tibble: 1 x 2
#      a b
#  <int> <fct>
#1     4 d
</code>```

Body:
I would like to split a dataframe

df <- data.frame(a = 1:4, b = letters[1:4])

  a b
1 1 a
2 2 b
3 3 c
4 4 d

into a list of one-row dataframes

list(
    data.frame(a = 1, b = letters[1])
    , data.frame(a = 2, b = letters[2])
    , data.frame(a = 3, b = letters[3])
    , data.frame(a = 4, b = letters[4])
)

[[1]]
  a b
1 1 a

[[2]]
  a b
1 2 b

[[3]]
  a b
1 3 c

[[4]]
  a b
1 4 d

Is there an elegant solution to this?

Body:
It would be with asplit

lapply(asplit(df, 1), as.data.frame.list)
#[[1]]
#  a b
#1 1 a

#[[2]]
#  a b
#1 2 b

#[[3]]
#  a b
#1 3 c

#[[4]]
#  a b
#1 4 d

Or with pmap

library(purrr)
pmap(df, tibble)
#[[1]]
# A tibble: 1 x 2
#      a b
#  <int> <fct>
#1     1 a

#[[2]]
# A tibble: 1 x 2
#      a b
#  <int> <fct>
#1     2 b

#[[3]]
# A tibble: 1 x 2
#      a b
#  <int> <fct>
#1     3 c

#[[4]]
# A tibble: 1 x 2
#      a b
#  <int> <fct>
#1     4 d


问:
JQuery Unobtrusive Validation firing on dropdownlist when it should not
I have the following in an .NET MVC3 using viewmodels.  I am using Razor and FluentValidation (but I have also tried DataAnnotations with the same results).

From View:

```<code>@Html.DropDownListFor(model=>model.L2, Model.RegisteredL2s, "[Select One]")
</code>```

From Controller:

```<code>    [HttpGet]
    [Authorize(Roles = "Supervisor")]
    public ActionResult Edit(string siteId, bool? isNew)
    {
            SiteEditViewModel model = new SiteEditViewModel();

                   List<SelectListItem> items = RegisteredL2Repository.GetRegisteredL2List()
                                                      .Select(x => new SelectListItem() { Text = x.L2, Value = x.L2.Trim() })
                                                      .OrderBy(x => x.Text)
                                                      .ToList();

                   model.RegisteredL2s = items.AsEnumerable();

                   if(!isNew.HasValue)
                   {
                        model.IsNew = false;
                   }

                   if(isNew.HasValue && (bool)isNew)
                   {
                        model.IsNew = true;
                        return View(model);
                   }

                   if(model.IsNew)
                   {
                        return View(model);
                   }

                   model.ConvertModelToViewModel(SiteRepository.GetSite(siteId));

                   return View("Edit", model);
              }
     }
</code>```

From ViewModel:

```<code>[DisplayName("Site:")]
          [TextboxLength(2)]
          public virtual string SiteId { get; set; }

          [DisplayName("L2:")]
          public virtual string L2 { get; set; }

          [DisplayName("Description:")]
          [TextboxLength(50)]
          public virtual string Description { get; set; }

          public IEnumerable<SelectListItem> RegisteredL2s { get; set; }

          public bool IsNew { get; set; }

          public string OverallError { get; set; }
</code>```

From my Validator class (Fluent):

```<code>public SiteEditValidator()
          {
               RuleFor(model => model.SiteId)
                    .NotEmpty()
                    .WithMessage("Site is required.")
                    .Length(2)
                    .WithMessage("Site must be 2 characters. Ex: 1C")
                    .Matches(@"^[0-9A-Za-z]{2}$")
                    .WithMessage("Site contains invalid characters. Only letters and numbers.");

               RuleFor(model => model.L2)
                    .NotEmpty()
                    .WithMessage("L2 is required.")
                    .Length(2)
                    .WithMessage("L2 must be 2 characters. Ex: 30")
                    .Matches(@"^[\d]{2}$")
                    .WithMessage("L2 contains invalid characters. Only numbers are allowed.");

               RuleFor(model => model.Description)
                    .NotEmpty()
                    .WithMessage("Description is required.")
                    .Length(3, 50)
                    .WithMessage("Description must be at least 3 characters and not more than 50.")
                    .Matches(@"^[\w\,\.\'\-\s]{3,50}$")
                    .WithMessage("Description contains some invalid characters.");
          }
</code>```

And the generated HTML:

```<code><div class="Edit-Field">
               <div class="Edit-Field-Label" style="width: 5em">
                    <label for="SiteId">Site:</label>
               </div>
               <div class="Editor-For">
                    <input autocomplete="off" data-val="true" data-val-length="Site must be 2 characters. Ex: 1C" data-val-length-max="2" data-val-length-min="2" data-val-regex="Site contains invalid characters. Only letters and numbers." data-val-regex-pattern="^[0-9A-Za-z]{2}$" data-val-required="Site is required." id="SiteId" maxlength="2" name="SiteId" readonly="readonly" style="width: 2.5em; background-color: LightGrey" type="text" value="30" />
                    <div class="Validation-For">
                         <span class="field-validation-valid" data-valmsg-for="SiteId" data-valmsg-replace="true"></span>
                    </div>
               </div>
          </div>
          <div class="Edit-Field">
               <div class="Edit-Field-Label" style="width: 5em">
                    <label for="L2">L2:</label>
               </div>
               <div class="Editor-For">
                    <select data-val="true" data-val-length="L2 must be 2 characters. Ex: 30" data-val-length-max="2" data-val-length-min="2" data-val-regex="L2 contains invalid characters. Only numbers are allowed." data-val-regex-pattern="^[\d]{2}$" data-val-required="L2 is required." id="L2" name="L2"><option value="">[Select One]</option>
<option value="30">30</option>
<option value="31">31</option>
<option value="32">32</option>
</select>
                    <div class="Validation-For">
                         <span class="field-validation-valid" data-valmsg-for="L2" data-valmsg-replace="true"></span>
                    </div>
               </div>
          </div>
          <div class="Edit-Field">
               <div class="Edit-Field-Label" style="width: 5em">
                    <label for="Description">Description:</label>
               </div>
               <div class="Editor-For">
                    <input autocomplete="off" data-val="true" data-val-length="Description must be at least 3 characters and not more than 50." data-val-length-max="50" data-val-length-min="3" data-val-regex="Description contains some invalid characters." data-val-regex-pattern="^[\w\,\.\'\-\s]{3,50}$" data-val-required="Description is required." id="Description" maxlength="50" name="Description" style="width: 30em" type="text" value="Central Office-Cash Receipts Unit" />
                    <div class="Validation-For">
                         <span class="field-validation-valid" data-valmsg-for="Description" data-valmsg-replace="true"></span>
                    </div>
               </div>
          </div>
</code>```

Now the problem:

I have the L2 field being drawn from a prepopulated IEnumerable (RegisteredL2s) and having that as a dropdownlist (ID=L2, roughly middle of the html). L2 is required and must be of a certain length (2). My problem is that even when a user has picked something other than the [Select One] the length error appears. If I remove that error the Regular Expression error appears. Server-side validation on submit works correctly. Why is it doing this and how do I stop it? Or can I just turn off the client-side for this one field?

Update:
I believe I found an issue with jquery.validate.js... I would like someone to confirm this.

Here is the original lines of code that I changed that seems to have fixed my problem:
this is line 683. Line 686 is the problem point.

```<code>getLength: function(value, element) {
  switch( element.nodeName.toLowerCase() ) {
    case 'select':

        return $("option:selected", element).length;            case 'input':
        if( this.checkable( element) )
        return this.findByName(element.name).filter(':checked').length;
        }
    return value.length;
    },
</code>```

I believe that when you have a required dropdown value with the length validator also present, it generates the error. When I run my code the length of this line returns 1 not 2. If I change the bolded line to return $("option:selected", element).val().length; it functions properly. Any comments on if this is a proper bug and if my fix will not interfere with any other part of jquery.validation would be helpful.

This is from jquery.validation 1.8.1 (updated from 1.7 since I thought my versions may have been out of sync) Jquery = 1.6.1.

Update 2:
Not sure if this should be an exact answer but:

It turns out that according to the JQuery.Validation documentation for rangelength (which is what jquery.validation.unobtrusive constructs for a Length of exactly 2) here It states that for selects (dropdownlist) it is for ensuring that a certain number items has been selected not for verifying the length of the value.

I am after checking the value length or turning validation off on the client side for this particular item while retaining validation server-side.

答:
It's not a complete answer(I am not sure how to accomplish the same thing under DataAnnotations) which is why I have not marked it as the accepted answer.

Under FluentValidation I changed the following line above

```<code>RuleFor(model => model.L2)
     .NotEmpty()
     .WithMessage("L2 is required.")
     .Length(2)
     .WithMessage("L2 must be 2 characters. Ex: 30")
     .Matches(@"^[\d]{2}$")
     .WithMessage("L2 contains invalid characters. Only numbers are allowed.");
</code>```

To:

```<code>RuleFor(model => model.L2)
                .NotEmpty()
                .WithMessage("L2 is required.")
                .Length(2)
                .When(x => 1==1)
                .WithMessage("L2 must be 2 characters. Ex: 30")
                .Matches(@"^[\d]{2}$")
                .WithMessage("L2 contains invalid characters or is too long. Only numbers are allowed.");
</code>```

This effectively turned off clientside validation but left the serverside intact. Apparently Fluent doesn't generate client-side validation for items with When conditions. Hopefully this helps someone out there.

Body:
I have the following in an .NET MVC3 using viewmodels.  I am using Razor and FluentValidation (but I have also tried DataAnnotations with the same results).

From View:

@Html.DropDownListFor(model=>model.L2, Model.RegisteredL2s, "[Select One]")

From Controller:

    [HttpGet]
    [Authorize(Roles = "Supervisor")]
    public ActionResult Edit(string siteId, bool? isNew)
    {
            SiteEditViewModel model = new SiteEditViewModel();

                   List<SelectListItem> items = RegisteredL2Repository.GetRegisteredL2List()
                                                      .Select(x => new SelectListItem() { Text = x.L2, Value = x.L2.Trim() })
                                                      .OrderBy(x => x.Text)
                                                      .ToList();

                   model.RegisteredL2s = items.AsEnumerable();

                   if(!isNew.HasValue)
                   {
                        model.IsNew = false;
                   }

                   if(isNew.HasValue && (bool)isNew)
                   {
                        model.IsNew = true;
                        return View(model);
                   }

                   if(model.IsNew)
                   {
                        return View(model);
                   }

                   model.ConvertModelToViewModel(SiteRepository.GetSite(siteId));

                   return View("Edit", model);
              }
     }

From ViewModel:

[DisplayName("Site:")]
          [TextboxLength(2)]
          public virtual string SiteId { get; set; }

          [DisplayName("L2:")]
          public virtual string L2 { get; set; }

          [DisplayName("Description:")]
          [TextboxLength(50)]
          public virtual string Description { get; set; }

          public IEnumerable<SelectListItem> RegisteredL2s { get; set; }

          public bool IsNew { get; set; }

          public string OverallError { get; set; }

From my Validator class (Fluent):

public SiteEditValidator()
          {
               RuleFor(model => model.SiteId)
                    .NotEmpty()
                    .WithMessage("Site is required.")
                    .Length(2)
                    .WithMessage("Site must be 2 characters. Ex: 1C")
                    .Matches(@"^[0-9A-Za-z]{2}$")
                    .WithMessage("Site contains invalid characters. Only letters and numbers.");

               RuleFor(model => model.L2)
                    .NotEmpty()
                    .WithMessage("L2 is required.")
                    .Length(2)
                    .WithMessage("L2 must be 2 characters. Ex: 30")
                    .Matches(@"^[\d]{2}$")
                    .WithMessage("L2 contains invalid characters. Only numbers are allowed.");

               RuleFor(model => model.Description)
                    .NotEmpty()
                    .WithMessage("Description is required.")
                    .Length(3, 50)
                    .WithMessage("Description must be at least 3 characters and not more than 50.")
                    .Matches(@"^[\w\,\.\'\-\s]{3,50}$")
                    .WithMessage("Description contains some invalid characters.");
          }

And the generated HTML:

                    Site:

                    <input autocomplete="off" data-val="true" data-val-length="Site must be 2 characters. Ex: 1C" data-val-length-max="2" data-val-length-min="2" data-val-regex="Site contains invalid characters. Only letters and numbers." data-val-regex-pattern="^[0-9A-Za-z]{2}$" data-val-required="Site is required." id="SiteId" maxlength="2" name="SiteId" readonly="readonly" style="width: 2.5em; background-color: LightGrey" type="text" value="30" />

                    L2:

                    <select data-val="true" data-val-length="L2 must be 2 characters. Ex: 30" data-val-length-max="2" data-val-length-min="2" data-val-regex="L2 contains invalid characters. Only numbers are allowed." data-val-regex-pattern="^[\d]{2}$" data-val-required="L2 is required." id="L2" name="L2"><option value="">[Select One]</option>
<option value="30">30</option>
<option value="31">31</option>
<option value="32">32</option>
</select>

                    Description:

                    <input autocomplete="off" data-val="true" data-val-length="Description must be at least 3 characters and not more than 50." data-val-length-max="50" data-val-length-min="3" data-val-regex="Description contains some invalid characters." data-val-regex-pattern="^[\w\,\.\'\-\s]{3,50}$" data-val-required="Description is required." id="Description" maxlength="50" name="Description" style="width: 30em" type="text" value="Central Office-Cash Receipts Unit" />

Now the problem:

I have the L2 field being drawn from a prepopulated IEnumerable (RegisteredL2s) and having that as a dropdownlist (ID=L2, roughly middle of the html). L2 is required and must be of a certain length (2). My problem is that even when a user has picked something other than the [Select One] the length error appears. If I remove that error the Regular Expression error appears. Server-side validation on submit works correctly. Why is it doing this and how do I stop it? Or can I just turn off the client-side for this one field?

Update:
I believe I found an issue with jquery.validate.js... I would like someone to confirm this.

Here is the original lines of code that I changed that seems to have fixed my problem:
this is line 683. Line 686 is the problem point.

getLength: function(value, element) {
  switch( element.nodeName.toLowerCase() ) {
    case 'select':

        return $("option:selected", element).length;            case 'input':
        if( this.checkable( element) )
        return this.findByName(element.name).filter(':checked').length;
        }
    return value.length;
    },

I believe that when you have a required dropdown value with the length validator also present, it generates the error. When I run my code the length of this line returns 1 not 2. If I change the bolded line to return $("option:selected", element).val().length; it functions properly. Any comments on if this is a proper bug and if my fix will not interfere with any other part of jquery.validation would be helpful.

This is from jquery.validation 1.8.1 (updated from 1.7 since I thought my versions may have been out of sync) Jquery = 1.6.1.

Update 2:
Not sure if this should be an exact answer but:

It turns out that according to the JQuery.Validation documentation for rangelength (which is what jquery.validation.unobtrusive constructs for a Length of exactly 2) here It states that for selects (dropdownlist) it is for ensuring that a certain number items has been selected not for verifying the length of the value.

I am after checking the value length or turning validation off on the client side for this particular item while retaining validation server-side.

Body:
It's not a complete answer(I am not sure how to accomplish the same thing under DataAnnotations) which is why I have not marked it as the accepted answer.

Under FluentValidation I changed the following line above

RuleFor(model => model.L2)
     .NotEmpty()
     .WithMessage("L2 is required.")
     .Length(2)
     .WithMessage("L2 must be 2 characters. Ex: 30")
     .Matches(@"^[\d]{2}$")
     .WithMessage("L2 contains invalid characters. Only numbers are allowed.");

To:

RuleFor(model => model.L2)
                .NotEmpty()
                .WithMessage("L2 is required.")
                .Length(2)
                .When(x => 1==1)
                .WithMessage("L2 must be 2 characters. Ex: 30")
                .Matches(@"^[\d]{2}$")
                .WithMessage("L2 contains invalid characters or is too long. Only numbers are allowed.");

This effectively turned off clientside validation but left the serverside intact. Apparently Fluent doesn't generate client-side validation for items with When conditions. Hopefully this helps someone out there.


问:
batch file parenthesis error when running within a CI runner
I have the following script for gitlab. When I run my test using: gitlab-runner exec shell test-unittest it works fine.

```<code>test-unittest:
 stage: test
 script:
 - 'echo: testing...'
 - 'dir /s /b RunnerUnitTest.dll | findstr /r bin\\ > tests_list.txt'
 - 'for /f %%f in (tests_list.txt) do vstest.console.exe "%%f"'
</code>```

but when I run it as part of the automated version, i.e. gitlab-runner run

I get the following error

Time Elapsed 00:00:00.80
$ echo: testing...

```<code>testing...
$ dir /s /b RunnerUnitTest.dll | findstr /r bin\\ > tests_list.txt

$ for /f %%f in (tests_list.txt) do vstest.console.exe "%%f"

The syntax of the command is incorrect.
ERROR: Job failed: exit status 255
</code>```

Any idea what is wrong? it is just the for loop. I've tried using %%f and putting cmd /r in front. My shell is set to 'cmd'.

答:
My fault, I didn't realise my config.toml file was using powershell. So after fixing it, I forgot to retry %%f

What is odd though, is the first command (the dir) didn't fail, but in powershell running that line does fail.

Body:
I have the following script for gitlab. When I run my test using: gitlab-runner exec shell test-unittest it works fine.

test-unittest:
 stage: test
 script:
 - 'echo: testing...'
 - 'dir /s /b RunnerUnitTest.dll | findstr /r bin\\ > tests_list.txt'
 - 'for /f %%f in (tests_list.txt) do vstest.console.exe "%%f"'

but when I run it as part of the automated version, i.e. gitlab-runner run

I get the following error

Time Elapsed 00:00:00.80
$ echo: testing...

testing...
$ dir /s /b RunnerUnitTest.dll | findstr /r bin\\ > tests_list.txt

$ for /f %%f in (tests_list.txt) do vstest.console.exe "%%f"

The syntax of the command is incorrect.
ERROR: Job failed: exit status 255

Any idea what is wrong? it is just the for loop. I've tried using %%f and putting cmd /r in front. My shell is set to 'cmd'.


问:
How to set value of -DefaultProfile (of type IAzureContextContainer) in New-AzSqlSyncMember
I am trying to create a powershell script to create azure data sync between 2 azure SQL databases.
My member database is on another subscription.

I need to set -DefaultProfile which is of type  on 'New-AzSqlSyncMember' command.
I am not aware of the syntax for setting this parameter.

My current script without -DefaultProfile looks like below:

```<code>New-AzSqlSyncMember -ResourceGroupName $resourceGroupName `
                    -ServerName $serverName `
                    -DatabaseName $databaseName `
                    -SyncGroupName $syncGroupName `
                    -Name $syncMemberName `
                    -MemberDatabaseType $memberDatabaseType `
                    -SyncDirection $syncDirection
</code>```

I want to set the value of the subscription field using powershell like in the image below using powershell:

答:
Possible cross post from https://social.msdn.microsoft.com/Forums/en-US/4ad3dd3e-314a-4442-957f-da77c17ef85b/how-to-set-value-of-defaultprofile-of-type-iazurecontextcontainer-in-newazsqlsyncmember?forum=azurescripting&prof=required

You want to call Connect-AzAccount with the credentials for the account you want to use in the -DefaultProfile parameter and store that in a variable. You can use that variable to set the parameter:

```<code>$DefaultProfile = Connect-AzAccount <params> -SubscriptionId $SubscriptionId

New-AzSqlSyncMember <params> -DefaultContext $DefaultProfile
</code>```

If this throws a type error that it can't convert from a PSAzureContext to a IAzureContextContainer there is an explicit converter available.

```<code>$DefaultProfile = Connect-AzAccount <params> -SubscriptionId $SubscriptionId

$Converter =  New-Object -TypeName Microsoft.Azure.Commands.Profile.Models.AzureContextConverter
$Container =  $converter.ConvertFrom($DefaultProfile, [Microsoft.Azure.Commands.Common.Authentication.Abstractions.Core.IAzureContextContainer], $null, $true)

New-AzSqlSyncMember <params> -DefaultContext $Container
</code>```

Body:
I am trying to create a powershell script to create azure data sync between 2 azure SQL databases.
My member database is on another subscription.

I need to set -DefaultProfile which is of type  on 'New-AzSqlSyncMember' command.
I am not aware of the syntax for setting this parameter.

My current script without -DefaultProfile looks like below:

New-AzSqlSyncMember -ResourceGroupName $resourceGroupName `
                    -ServerName $serverName `
                    -DatabaseName $databaseName `
                    -SyncGroupName $syncGroupName `
                    -Name $syncMemberName `
                    -MemberDatabaseType $memberDatabaseType `
                    -SyncDirection $syncDirection

I want to set the value of the subscription field using powershell like in the image below using powershell:

Body:
Possible cross post from https://social.msdn.microsoft.com/Forums/en-US/4ad3dd3e-314a-4442-957f-da77c17ef85b/how-to-set-value-of-defaultprofile-of-type-iazurecontextcontainer-in-newazsqlsyncmember?forum=azurescripting&prof=required

You want to call Connect-AzAccount with the credentials for the account you want to use in the -DefaultProfile parameter and store that in a variable. You can use that variable to set the parameter:

$DefaultProfile = Connect-AzAccount <params> -SubscriptionId $SubscriptionId

New-AzSqlSyncMember <params> -DefaultContext $DefaultProfile

If this throws a type error that it can't convert from a PSAzureContext to a IAzureContextContainer there is an explicit converter available.

$DefaultProfile = Connect-AzAccount <params> -SubscriptionId $SubscriptionId

$Converter =  New-Object -TypeName Microsoft.Azure.Commands.Profile.Models.AzureContextConverter
$Container =  $converter.ConvertFrom($DefaultProfile, [Microsoft.Azure.Commands.Common.Authentication.Abstractions.Core.IAzureContextContainer], $null, $true)

New-AzSqlSyncMember <params> -DefaultContext $Container


问:
How to get Microsoft.Extensions.Logging<T> in console application using Serilog and AutoFac?
We have common BL classes in a ASP.NET Core application that get in the ctor:

Microsoft.Extensions.Logging.ILogger<Foo>

In ASP.NET Core, the internal infrastructure of ASP.NET handles getting the ILogger via the LoggerFactory.

We now want to reuse these BL classes in a console application (for async jobs), how do we setup AutoFac and Serilog to inject Microsoft.Extensions.Logging.ILogger<T> in environment that LoggerFactory doesn't exists?

答:
I would recommend a slightly different approach if you want to register ir manually direct on Autofac:

```<code>private static void ConfigureLogging(ILoggingBuilder log)
{
    log.ClearProviders();
    log.SetMinimumLevel(LogLevel.Error);
    log.AddConsole();
}

private static void ConfigureContainer(ContainerBuilder builder)
{
    builder.Register(handler => LoggerFactory.Create(ConfigureLogging))
        .As<ILoggerFactory>()
        .SingleInstance()
        .AutoActivate();

    builder.RegisterGeneric(typeof(Logger<>))
        .As(typeof(ILogger<>))
        .SingleInstance();
    // other registrations
}
</code>```

And this on you main startup code:

```<code>var containerBuilder = new ContainerBuilder();
ConfigureContainer(containerBuilder);

var container = containerBuilder.Build();
var serviceProvider = new AutofacServiceProvider(container);
// you can use either the built container or set the serviceProvider onto the library you are using.
</code>```

Body:
I would recommend a slightly different approach if you want to register ir manually direct on Autofac:

private static void ConfigureLogging(ILoggingBuilder log)
{
    log.ClearProviders();
    log.SetMinimumLevel(LogLevel.Error);
    log.AddConsole();
}

private static void ConfigureContainer(ContainerBuilder builder)
{
    builder.Register(handler => LoggerFactory.Create(ConfigureLogging))
        .As<ILoggerFactory>()
        .SingleInstance()
        .AutoActivate();

    builder.RegisterGeneric(typeof(Logger<>))
        .As(typeof(ILogger<>))
        .SingleInstance();
    // other registrations
}

And this on you main startup code:

var containerBuilder = new ContainerBuilder();
ConfigureContainer(containerBuilder);

var container = containerBuilder.Build();
var serviceProvider = new AutofacServiceProvider(container);
// you can use either the built container or set the serviceProvider onto the library you are using.


问:
Android build error after installing cloud_firestore dependency
I want to connect my app to Cloud Firestore with cloud_firestore dependency but the problem occurred with android after I install this dependency. I received this error Image of the error

After that I can’t build the android app to test it on the emulator but on iOS it works just fine.

I also migrated to androidx already as I found in the document I read before.
So anyone have any idea to fix this?

答:
Top 2 errors you will face and solutions:

ERROR 1:

```<code>Note: C:\src\flutter\.pub-cache\hosted\pub.dartlang.org\cloud_firestore-0.12.10\android\src\main\java\io\flutter\plugins\firebase\cloudfirestore\CloudFirestorePlugin.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: C:\src\flutter\.pub-cache\hosted\pub.dartlang.org\cloud_firestore-0.12.10\android\src\main\java\io\flutter\plugins\firebase\cloudfirestore\CloudFirestorePlugin.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Note: Recompile with -Xlint:deprecation for details.
Note: C:\src\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_core-0.4.0+1\android\src\main\java\io\flutter\plugins\firebase\core\FirebaseCorePlugin.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
</code>```

SOLUTION

I had the same issue and combined two suggested fixes to get it to finally work:

1: minSdkVersion 21, change to 23

2: run "flutter pub upgrade"
= issues fixed!

To double-check what the fix was:
I also reverted back to 21 and invalidated + flutter clean and the issue appeared again. Then I changed to 23 and the warnings disappeared!

ERROR 2:

```<code>com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives:
Learn how to resolve the issue at
https://developer.android.com/studio/build/dependencies#duplicate_classes.
Program type already present: io.flutter.BuildConfig
at com. android. builder. dexing. D8DexArchiveMerger. getExceptionToRethrow (D8DexArchiveMerger.java:131)
at com. android. builder. dexing. D8DexArchiveMerger. mergeDexArchives (D8DexArchiveMerger.java:118)
at com.android.build.gradle.internal.transforms.DexMergerTransformCallable.call(DexMergerTransformCallable.java:102)
at com.android.build.gradle.internal.tasks.DexMergingTaskRunnable.run(DexMergingTask.kt:444)
at com.android.build.gradle.internal.tasks.Workers$ActionFacade.run(Workers.kt:335)
at org.gradle.workers.internal.DefaultWorkerServer.execute(DefaultWorkerServer.java:39)
at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1.execute(NoIsolationWorkerFactory.java:61)
at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:44)
at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:41)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
at org.gradle.workers.internal.AbstractWorker.executeWrappedInBuildOperation(AbstractWorker.java:41)
at org.gradle.workers.internal.NoIsolationWorkerFactory$1.execute(NoIsolationWorkerFactory.java:55)
at org.gradle.workers.internal.DefaultWorkerExecutor$1.call(DefaultWorkerExecutor.java:105)
at org.gradle.workers.internal.DefaultWorkerExecutor$1.call(DefaultWorkerExecutor.java:99)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runExecution(DefaultConditionalExecutionQueue.java:215)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runBatch(DefaultConditionalExecutionQueue.java:164)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.run(DefaultConditionalExecutionQueue.java:131)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
at java.lang.Thread.run(Thread.java:748)
</code>```

Caused by: com.android.tools.r8.CompilationFailedException: Compilation failed to complete
    at com.android.tools.r8.utils.t.a(:55)
    at com.android.tools.r8.D8.run(:11)
    at com.android.builder.dexing.D8DexArchiveMerger.mergeDexArchives(D8DexArchiveMerger.java:116)
    ... 30 more

SOLUTION:

I received the same error, but after flutter clean and flutter packages get everything works great.

Body:
Top 2 errors you will face and solutions:

ERROR 1:

Note: C:\src\flutter\.pub-cache\hosted\pub.dartlang.org\cloud_firestore-0.12.10\android\src\main\java\io\flutter\plugins\firebase\cloudfirestore\CloudFirestorePlugin.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: C:\src\flutter\.pub-cache\hosted\pub.dartlang.org\cloud_firestore-0.12.10\android\src\main\java\io\flutter\plugins\firebase\cloudfirestore\CloudFirestorePlugin.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Note: Recompile with -Xlint:deprecation for details.
Note: C:\src\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_core-0.4.0+1\android\src\main\java\io\flutter\plugins\firebase\core\FirebaseCorePlugin.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

SOLUTION

I had the same issue and combined two suggested fixes to get it to finally work:

1: minSdkVersion 21, change to 23

2: run "flutter pub upgrade"
= issues fixed!

To double-check what the fix was:
I also reverted back to 21 and invalidated + flutter clean and the issue appeared again. Then I changed to 23 and the warnings disappeared!

ERROR 2:

com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives:
Learn how to resolve the issue at
https://developer.android.com/studio/build/dependencies#duplicate_classes.
Program type already present: io.flutter.BuildConfig
at com. android. builder. dexing. D8DexArchiveMerger. getExceptionToRethrow (D8DexArchiveMerger.java:131)
at com. android. builder. dexing. D8DexArchiveMerger. mergeDexArchives (D8DexArchiveMerger.java:118)
at com.android.build.gradle.internal.transforms.DexMergerTransformCallable.call(DexMergerTransformCallable.java:102)
at com.android.build.gradle.internal.tasks.DexMergingTaskRunnable.run(DexMergingTask.kt:444)
at com.android.build.gradle.internal.tasks.Workers$ActionFacade.run(Workers.kt:335)
at org.gradle.workers.internal.DefaultWorkerServer.execute(DefaultWorkerServer.java:39)
at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1.execute(NoIsolationWorkerFactory.java:61)
at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:44)
at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:41)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
at org.gradle.workers.internal.AbstractWorker.executeWrappedInBuildOperation(AbstractWorker.java:41)
at org.gradle.workers.internal.NoIsolationWorkerFactory$1.execute(NoIsolationWorkerFactory.java:55)
at org.gradle.workers.internal.DefaultWorkerExecutor$1.call(DefaultWorkerExecutor.java:105)
at org.gradle.workers.internal.DefaultWorkerExecutor$1.call(DefaultWorkerExecutor.java:99)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runExecution(DefaultConditionalExecutionQueue.java:215)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runBatch(DefaultConditionalExecutionQueue.java:164)
at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.run(DefaultConditionalExecutionQueue.java:131)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
at java.lang.Thread.run(Thread.java:748)

Caused by: com.android.tools.r8.CompilationFailedException: Compilation failed to complete
    at com.android.tools.r8.utils.t.a(:55)
    at com.android.tools.r8.D8.run(:11)
    at com.android.builder.dexing.D8DexArchiveMerger.mergeDexArchives(D8DexArchiveMerger.java:116)
    ... 30 more

SOLUTION:

I received the same error, but after flutter clean and flutter packages get everything works great.


问:
Add CORS policy for Swagger Endpoints Only
I would like to add cors to swagger.json but not to the controller endpoints.  I am able to make a cross-site call when I add a cors policy globally using.

```<code>            services.AddCors(options => options.AddPolicy("SwaggerCorsPolicy",
                builder =>
                {
                    builder.AllowAnyMethod().AllowAnyHeader()
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader();
                }));

</code>```

along with

app.UseCors("SwaggerCorsPolicy");

With this in place I can call /swagger/v1/swagger.json from another port, so I know it's working.

I'd like to add cors only to the endpoint /swagger/v1/swagger.json.

I have tried using MapGet in the app.UseEndpoints but I have not been successful.  Here is what I tried

```<code>            app.UseSwagger();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapGet("/swagger/v1/swagger.json", async context => context.Response.WriteAsync("echo"))
                    .RequireCors("SwaggerCorsPolicy");
            });
</code>```

I'm running is to issues when I produce the swagger.json from the applicaiton and run ReDoc in a container passing in the localhost uri of the swagger.json.  It works when the cors is enabled globally, but not when I try to enable it just for swagger.json.

I'm using .net core 3 and openapi 3.

答:
You can specify a CORS rule based on the controller methods, read more about it here: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#enable-cors-with-attributes

Once you define a policy you can attach it to individual methods. Although, I'm not sure why you would need CORS specific policies for Swagger. Swagger is just the user interface for the API methods you've configured.

I don't foresee anyone trying to pull your Swagger from another origin. To be clear, you can't just set CORS policies for the API methods when you're in Swagger. Swagger is just an interfacing tool for the API's.

Body:
I would like to add cors to swagger.json but not to the controller endpoints.  I am able to make a cross-site call when I add a cors policy globally using.

            services.AddCors(options => options.AddPolicy("SwaggerCorsPolicy",
                builder =>
                {
                    builder.AllowAnyMethod().AllowAnyHeader()
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader();
                }));

along with

app.UseCors("SwaggerCorsPolicy");

With this in place I can call /swagger/v1/swagger.json from another port, so I know it's working.

I'd like to add cors only to the endpoint /swagger/v1/swagger.json.

I have tried using MapGet in the app.UseEndpoints but I have not been successful.  Here is what I tried

            app.UseSwagger();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapGet("/swagger/v1/swagger.json", async context => context.Response.WriteAsync("echo"))
                    .RequireCors("SwaggerCorsPolicy");
            });

I'm running is to issues when I produce the swagger.json from the applicaiton and run ReDoc in a container passing in the localhost uri of the swagger.json.  It works when the cors is enabled globally, but not when I try to enable it just for swagger.json.

I'm using .net core 3 and openapi 3.


问:
Not able to figure out the logical error in C program
A program that prints its input one word per line.

```<code>int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c== ' ' || c== '\n' ||c == '\t')
                putchar('\n');
        else {
            putchar(c);
        }
    }
    return 0;
}
</code>```

The above program prints the result correctly, one word per line. After changing the condition accordingly, I was expecting the program below to also print one word per line. However I am not getting the correct result. Am I making some silly mistake or is something wrong?

```<code>int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c != ' ' || c != '\n' || c != '\t')
            putchar(c);
        else {
            putchar('\n');
        }
    }

    return 0;

}
</code>```

答:
the correct change of condition is:

```<code>if (!(c == ' ' || c == '\n' || c == '\t'))
</code>```

or

```<code>if (c != ' ' && c != '\n' && c != '\t')
</code>```

See De Morgan's law

Body:
A program that prints its input one word per line.

int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c== ' ' || c== '\n' ||c == '\t')
                putchar('\n');
        else {
            putchar(c);
        }
    }
    return 0;
}

The above program prints the result correctly, one word per line. After changing the condition accordingly, I was expecting the program below to also print one word per line. However I am not getting the correct result. Am I making some silly mistake or is something wrong?

int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c != ' ' || c != '\n' || c != '\t')
            putchar(c);
        else {
            putchar('\n');
        }
    }

    return 0;

}

Body:
the correct change of condition is:

if (!(c == ' ' || c == '\n' || c == '\t'))

or

if (c != ' ' && c != '\n' && c != '\t')

See De Morgan's law


问:
Deal with Date Time in PowerShell
I've written a pretty nifty PowerShell script that works with VMware PowerCLI to clone a couple of VMs off to a second storage device and then automatically delete them when they reach a certain age.  It seems to work great until it gets to the end/beginning of the month, then the approach I used for date time seems to fail and all clones are deleted unexpectedly.  Rather than include the entire script, here are the pieces that matter.

First, when the clones are created I am using the following code..

```<code>$vmdatestamp = (Get-Date).tostring('yyyyMMdd-HHmmss')
new-vm -Name $VM-$vmdatestamp -VM $VM -Datastore $CPFlag -vmhost host.domain.local -Location 'Regular Clone'
</code>```

This variable ends up creating a VM clone that is named something like "VMName-20200214-040022" in the case that the date is Feb 14th, 2020 and the variable captured 4 AM and 00 Min and 22 seconds.

Then later on in the script there is a cleanup section that lists these cloned VMs and checks the date.  The objective is to run a delete command if the clone is older than 3 days.  So there is a foreach loop that runs off of all VMs found within a particular folder, "Regular Clone".  $vmls is the var within the loop for each VM found.  Here is the code I am using to check the dates and delete older than 3 days.

```<code>#Grab matched string and doctor it to only look at 8 digit date.
$var1 = $vmls.name
$var2 = $var1 -split '-' | Select-String '\d{8}'
$var3 = $var2 -replace '(?S)'

#Grab todays date in the same 8 digit format then subtract to compare variance.  How old is the clone?
$CompareDate = (Get-Date).tostring('yyyyMMdd')
$var4 = $CompareDate - $var3

      #If clone is older than 3 days, delete it.  Turn this knob based on your requirements.
      if($var4 -gt '3') {
</code>```

So this last "if" statement that checks $var4 is greater than 3 is where the source of my problem is.  I don't think the script is smart enough to figure out if for example today is the 1st, how minus '-' works.  Anyone have a suggestion on how to better deal with this?

Regards,
Adam Tyler

答:
Powershell has a great deal of flexibility in dealing with dates and times using the [datetime] type.  There is probably another answer to this somewhere out there, and I'll search for it later, but here are some basics.

When you read in your filenames, which I am assuming are in 'VMName-yyyyMMdd-HHmmss' format, you can turn that into a PowerShell [datetime] object like so (Thanks to this post for the info on [datetime]::parseexact):

```<code>[string]$VMFileName = #load $VMFileName variable with the name of your VM file somehow
$VMFNSplit = $VMFileName -split '-'
$FileDateStamp = [datetime]::ParseExact("$($VMFNSplit[-2])-$($VMFNSplit[-1])",'yyyyMMdd-HHmmss',$null)
</code>```

EDIT:
Tested the above, and got this:

```<code>PS> $VMFileName = 'VMName-20200222-043322'
PS> $VMFNSplit = $VMFileName -split '-'

PS> $VMFNSplit[-2]
20200222

PS> $VMFNSplit[-1]
043322

PS> "$($VMFNSplit[-2])-$($VMFNSplit[-1])"
20200222-043322

PS> $FileDateStamp = [datetime]::ParseExact("$($VMFNSplit[-2])-$($VMFNSplit[-1])",'yyyyMMdd-HHmmss',$null)

PS> $FileDateStamp
Saturday, February 22, 2020 4:33:22 AM
</code>```

Once you have your file date/time stamp in a [datetime], you can use the built in methods to add/subtract your intervals, like this:

```<code>#If clone is older than 3 days, delete it.  Turn this knob based on your requirements.
$TooOld = (Get-Date).AddDays(-3)
If ($FileDateStamp -lt $TooOld) {#Delete it}
</code>```

Hope this helps!

Title: Deal with Date Time in PowerShell

Body:
I've written a pretty nifty PowerShell script that works with VMware PowerCLI to clone a couple of VMs off to a second storage device and then automatically delete them when they reach a certain age.  It seems to work great until it gets to the end/beginning of the month, then the approach I used for date time seems to fail and all clones are deleted unexpectedly.  Rather than include the entire script, here are the pieces that matter.

First, when the clones are created I am using the following code..

$vmdatestamp = (Get-Date).tostring('yyyyMMdd-HHmmss')
new-vm -Name $VM-$vmdatestamp -VM $VM -Datastore $CPFlag -vmhost host.domain.local -Location 'Regular Clone'

This variable ends up creating a VM clone that is named something like "VMName-20200214-040022" in the case that the date is Feb 14th, 2020 and the variable captured 4 AM and 00 Min and 22 seconds.

Then later on in the script there is a cleanup section that lists these cloned VMs and checks the date.  The objective is to run a delete command if the clone is older than 3 days.  So there is a foreach loop that runs off of all VMs found within a particular folder, "Regular Clone".  $vmls is the var within the loop for each VM found.  Here is the code I am using to check the dates and delete older than 3 days.

#Grab matched string and doctor it to only look at 8 digit date.
$var1 = $vmls.name
$var2 = $var1 -split '-' | Select-String '\d{8}'
$var3 = $var2 -replace '(?S)'

#Grab todays date in the same 8 digit format then subtract to compare variance.  How old is the clone?
$CompareDate = (Get-Date).tostring('yyyyMMdd')
$var4 = $CompareDate - $var3

      #If clone is older than 3 days, delete it.  Turn this knob based on your requirements.
      if($var4 -gt '3') {

So this last "if" statement that checks $var4 is greater than 3 is where the source of my problem is.  I don't think the script is smart enough to figure out if for example today is the 1st, how minus '-' works.  Anyone have a suggestion on how to better deal with this?

Regards,
Adam Tyler

Body:
Powershell has a great deal of flexibility in dealing with dates and times using the [datetime] type.  There is probably another answer to this somewhere out there, and I'll search for it later, but here are some basics.

When you read in your filenames, which I am assuming are in 'VMName-yyyyMMdd-HHmmss' format, you can turn that into a PowerShell [datetime] object like so (Thanks to this post for the info on [datetime]::parseexact):

[string]$VMFileName = #load $VMFileName variable with the name of your VM file somehow
$VMFNSplit = $VMFileName -split '-'
$FileDateStamp = [datetime]::ParseExact("$($VMFNSplit[-2])-$($VMFNSplit[-1])",'yyyyMMdd-HHmmss',$null)

EDIT:
Tested the above, and got this:

PS> $VMFileName = 'VMName-20200222-043322'
PS> $VMFNSplit = $VMFileName -split '-'

PS> $VMFNSplit[-2]
20200222

PS> $VMFNSplit[-1]
043322

PS> "$($VMFNSplit[-2])-$($VMFNSplit[-1])"
20200222-043322

PS> $FileDateStamp = [datetime]::ParseExact("$($VMFNSplit[-2])-$($VMFNSplit[-1])",'yyyyMMdd-HHmmss',$null)

PS> $FileDateStamp
Saturday, February 22, 2020 4:33:22 AM

Once you have your file date/time stamp in a [datetime], you can use the built in methods to add/subtract your intervals, like this:

#If clone is older than 3 days, delete it.  Turn this knob based on your requirements.
$TooOld = (Get-Date).AddDays(-3)
If ($FileDateStamp -lt $TooOld) {#Delete it}

Hope this helps!


问:
Search index with python without a loop
I have a list in python, for example A = [-22,-10,0,3,8] and I want to find A[x]=x, that means that the index and number in the list have the same value. In this case x=3 because A[3]=3.

Can I find x without a loop?

EDIT: It's a academic problem and I have a clue "You don't need to visit each position in the array" and the numbers will be ordered and unique

答:
Just for lulz, the recursive function:</p>

```<code>def find(l, i):
  if i>=len(l):
    return None
  elif l[i]==i:
    return i
  else:
    return find(l, i+1)

# for searching in the whole list the second argument needs to be 0
print(find([-22,-10,0,3,8], 0))
</code>```

Title: Search index with python without a loop

Body:
Just for lulz, the recursive function:

def find(l, i):
  if i>=len(l):
    return None
  elif l[i]==i:
    return i
  else:
    return find(l, i+1)

# for searching in the whole list the second argument needs to be 0
print(find([-22,-10,0,3,8], 0))


问:
How can I add spacebar on Header Nav Bar
So I made a navigation bar and a section lists and I successfully done it but the only problem is that the lists are not spaced. How do I fix this?

How the Page looks like

header {
  width:    100%;
  height:    80px;
  position:   fixed;
  top:    0;
  left:    0;
  background:   white;
  box-shadow:   0 32px 55px rgba(0, 0, 0, 0.5);
  z-index:    999;
}

header nav {
  float:    none;
  margin:    30px;
}

header nav ul li {
  display:    inline-block;
}

header nav ul li a {
  font-size:   16px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <header>

  <nav id="nav-main">
   <ul>
    <li>Home</li>
    <li>Elektro One</li>
    <li>Über uns</li>
    <li>Kontakt</li>
    <li>Impressum</li>
   </ul>
  </nav>

 </header></code>```

答:
Add "padding-left" and "padding-right" to the anchor tag CSS under "#nav-main" id. Please update below anchor CSS :</p>

```<code>header nav ul li a  {
    font-size:16px;
    padding-left: 30px;
    padding-right:30px; }
</code>```

Body:
So I made a navigation bar and a section lists and I successfully done it but the only problem is that the lists are not spaced. How do I fix this?

How the Page looks like

header {
  width:    100%;
  height:    80px;
  position:   fixed;
  top:    0;
  left:    0;
  background:   white;
  box-shadow:   0 32px 55px rgba(0, 0, 0, 0.5);
  z-index:    999;
}

header nav {
  float:    none;
  margin:    30px;
}

header nav ul li {
  display:    inline-block;
}

header nav ul li a {
  font-size:   16px;
}

Home

Elektro One

Über uns

Kontakt

Impressum

Body:
Add "padding-left" and "padding-right" to the anchor tag CSS under "#nav-main" id. Please update below anchor CSS :

header nav ul li a  {
    font-size:16px;
    padding-left: 30px;
    padding-right:30px; }


问:
Summing across SAS arrays based on intervals i.e. start date and end date
I am trying to sum variables in an array based on start and end date. For each ID there is one row (if the start and end date are within the same year), two rows (if the start and end date are within consecutive years) or multiple rows for different periods of start and end dates. There are 12 variables with counts for each month i.e. v1-v12 where v1 is january and v12 is december. The two rows for some ID contain monthly values for the 2 consecutive years i.e. within the stat year and the end year. I am trying to get the sum count for the array variables but only from the start date to the end date for each ID. For example, for ID 1  the start date is 07/23/2007 and end date is 06/07/2008, i would like to sum from V7 (july start month) to v12 in 2007 and V1 to V6 (june end month) in 2008 i.e. second row.  Here's what I have:

```<code>ID  STARTDATE   ENDDATE      YR    V1  V2  V3  V4  V5  V6  V7  V8  V9  V10 V11 V12
1   07/23/2007  06/07/2008  2007    3   5   2   6   3   2   1   3   4   1   2   3
1   07/23/2007  06/07/2008  2008    0   4   2   2   3   0   1   3   1   0   2   3
2   02/01/2002  07/27/2002  2002    1   0   2   3   1   0   1   2   3   0   0   2
3   05/26/2008  03/07/2009  2008    2   0   2   3   1   2   1   1   3   0   0   1
3   05/26/2008  03/07/2009  2009    4   1   4   3   1   0   2   3   3   1   0   3
3   10/17/2011  08/17/2012  2011    3   3   0   1   0   1   1   5   3   1   0   1
3   10/17/2011  08/17/2012  2012    1   3   2   3   1   0   1   2   3   2   0   2
4   02/27/2004  01/22/2005  2004    2   0   2   3   1   2   1   1   3   0   0   1
4   02/27/2004  01/22/2005  2005    0   4   2   2   3   0   1   3   1   0   2   3
</code>```

and this is what I want :

```<code>ID  STARTDATE   ENDDATE      YR    V1  V2  V3  V4  V5  V6  V7  V8  V9  V10  V11  V12  sum
1   07/23/2007  06/07/2008  2007    3   5   2   6   3   2  [1   3   4    1    2    3]  25
1   07/23/2007  06/07/2008  2008   [0   4   2   2   3   0]  1   3   1    0    2    3   25
2   02/01/2002  07/27/2002  2002    1  [0   2   3   1   0   1]  2   3    0    0    2    8
3   05/26/2008  03/07/2009  2008    2   0   2   3  [1   2   1   1   3    0    0    1]  18
3   05/26/2008  03/07/2009  2009   [4   1   4]  3   1   0   2   3   3    1    0    3   18
3   10/17/2011  08/17/2012  2011    3   3   0   1   0   1   1   5   3   [1    0    1]  15
3   10/17/2011  08/17/2012  2011   [1   3   2   3   1   0   1   2]  3    2    0    2   15
4   02/27/2004  01/22/2005  2004    2  [0   2   3   1   2   1   1   3    0    0    1]  14
4   02/27/2004  01/22/2005  2005   [0]  4   2   2   3   0   1   3   1    0    2    3   14
</code>```

Here's the code I tried

```<code>data want;
  set have;
  array vars(*) V1-V12;
  DT_CHECK=intnx('month',ENDDATE,-12);
  start=intck('month','STARTDATE,DT_CHECK)+1;
  if start<1 then do;
    error 'Start date out of range';
    delete;
    end;
  else if start>dim(vars)-12 then do;
    error 'End date out of range';
    delete;
    end;
  do _N_=start to start+12;
    sum_n+vars(_N_);
    end;
  format DT_CHECK mmddyy10.;
run;
</code>```

But am having problems. Any help is appreciated. Thank you.

答:
Since each observation represents one year a straight forward approach would be to just loop month from Jan to Dec and check if that month falls within your date range.

```<code>data want;
 do until(last.startdate);
   set have;
   by id startdate;
   array v v1-v12;
   do month=1 to 12 ;
     if intnx('month',startdate,0,'b')<=mdy(month,1,yr)<=intnx('month',enddate,0,'e')
       then sum=sum(sum,v[month])
     ;
   end;
 end;
 keep id startdate enddate sum;
run;
</code>```

Results:

```<code>Obs    ID     STARTDATE       ENDDATE    sum

 1     1     2007-07-23    2008-06-07     25
 2     2     2002-02-01    2002-07-27      7
 3     3     2008-05-26    2009-03-07     18
 4     3     2011-10-17    2012-08-17     15
 5     4     2004-02-27    2005-01-22     14
</code>```

Body:
I am trying to sum variables in an array based on start and end date. For each ID there is one row (if the start and end date are within the same year), two rows (if the start and end date are within consecutive years) or multiple rows for different periods of start and end dates. There are 12 variables with counts for each month i.e. v1-v12 where v1 is january and v12 is december. The two rows for some ID contain monthly values for the 2 consecutive years i.e. within the stat year and the end year. I am trying to get the sum count for the array variables but only from the start date to the end date for each ID. For example, for ID 1  the start date is 07/23/2007 and end date is 06/07/2008, i would like to sum from V7 (july start month) to v12 in 2007 and V1 to V6 (june end month) in 2008 i.e. second row.  Here's what I have:

ID  STARTDATE   ENDDATE      YR    V1  V2  V3  V4  V5  V6  V7  V8  V9  V10 V11 V12
1   07/23/2007  06/07/2008  2007    3   5   2   6   3   2   1   3   4   1   2   3
1   07/23/2007  06/07/2008  2008    0   4   2   2   3   0   1   3   1   0   2   3
2   02/01/2002  07/27/2002  2002    1   0   2   3   1   0   1   2   3   0   0   2
3   05/26/2008  03/07/2009  2008    2   0   2   3   1   2   1   1   3   0   0   1
3   05/26/2008  03/07/2009  2009    4   1   4   3   1   0   2   3   3   1   0   3
3   10/17/2011  08/17/2012  2011    3   3   0   1   0   1   1   5   3   1   0   1
3   10/17/2011  08/17/2012  2012    1   3   2   3   1   0   1   2   3   2   0   2
4   02/27/2004  01/22/2005  2004    2   0   2   3   1   2   1   1   3   0   0   1
4   02/27/2004  01/22/2005  2005    0   4   2   2   3   0   1   3   1   0   2   3

and this is what I want :

ID  STARTDATE   ENDDATE      YR    V1  V2  V3  V4  V5  V6  V7  V8  V9  V10  V11  V12  sum
1   07/23/2007  06/07/2008  2007    3   5   2   6   3   2  [1   3   4    1    2    3]  25
1   07/23/2007  06/07/2008  2008   [0   4   2   2   3   0]  1   3   1    0    2    3   25
2   02/01/2002  07/27/2002  2002    1  [0   2   3   1   0   1]  2   3    0    0    2    8
3   05/26/2008  03/07/2009  2008    2   0   2   3  [1   2   1   1   3    0    0    1]  18
3   05/26/2008  03/07/2009  2009   [4   1   4]  3   1   0   2   3   3    1    0    3   18
3   10/17/2011  08/17/2012  2011    3   3   0   1   0   1   1   5   3   [1    0    1]  15
3   10/17/2011  08/17/2012  2011   [1   3   2   3   1   0   1   2]  3    2    0    2   15
4   02/27/2004  01/22/2005  2004    2  [0   2   3   1   2   1   1   3    0    0    1]  14
4   02/27/2004  01/22/2005  2005   [0]  4   2   2   3   0   1   3   1    0    2    3   14

Here's the code I tried

data want;
  set have;
  array vars(*) V1-V12;
  DT_CHECK=intnx('month',ENDDATE,-12);
  start=intck('month','STARTDATE,DT_CHECK)+1;
  if start<1 then do;
    error 'Start date out of range';
    delete;
    end;
  else if start>dim(vars)-12 then do;
    error 'End date out of range';
    delete;
    end;
  do _N_=start to start+12;
    sum_n+vars(_N_);
    end;
  format DT_CHECK mmddyy10.;
run;

But am having problems. Any help is appreciated. Thank you.

Body:
Since each observation represents one year a straight forward approach would be to just loop month from Jan to Dec and check if that month falls within your date range.

data want;
 do until(last.startdate);
   set have;
   by id startdate;
   array v v1-v12;
   do month=1 to 12 ;
     if intnx('month',startdate,0,'b')<=mdy(month,1,yr)<=intnx('month',enddate,0,'e')
       then sum=sum(sum,v[month])
     ;
   end;
 end;
 keep id startdate enddate sum;
run;

Results:

Obs    ID     STARTDATE       ENDDATE    sum

 1     1     2007-07-23    2008-06-07     25
 2     2     2002-02-01    2002-07-27      7
 3     3     2008-05-26    2009-03-07     18
 4     3     2011-10-17    2012-08-17     15
 5     4     2004-02-27    2005-01-22     14


问:
PySpark - select distinct rows based on max value from another column
I'm writing my first spark job and I'm stuck in a situation that I don't know how to solve with Spark. I have a list like this one:

```<code>mylist = [
  {"id":1,"name":"sally", "role": "manager", "updated_at": "2020-01-13T18:42:21Z"},
  {"id":1,"name":"sally", "role": "director", "updated_at": "2020-01-14T10:17:45Z"},
  {"id":2,"name":"eric", "role": "leader", "updated_at": "2020-01-28T07:33:58Z"},
  {"id":3,"name":"john", "role": "leader", "updated_at": "2020-01-01T20:00:00Z"},
  {"id":2,"name":"eric", "role": "developer", "updated_at": "2020-01-10T08:28:31Z"},
]

df = spark.createDataFrame(Row(**x) for x in mylist).show(truncate=False)

df.show(n=10)
</code>```

I'm wondering if it's possible to filter this dataframe and get distinct rows (unique ids) based on max updated_at. The max value of updated_at represents the last status of each employee.

The expected output from example above is:

```<code>  {"id":1,"name":"sally", "role": "director", "updated_at": "2020-01-14T10:17:45Z"},
  {"id":2,"name":"eric", "role": "leader", "updated_at": "2020-01-28T07:33:58Z"},
  {"id":3,"name":"john", "role": "leader", "updated_at": "2020-01-01T20:00:00Z"},
</code>```

If is it possible? For what function should I look?

答:
Try to use row_number()-window function and get only the latest record for the uniqueids.
Then create a json output for the dataframe.

Example:

```<code>from pyspark.sql.functions import *
from pyspark.sql import *
from pyspark.sql.window import Window

mylist = [
  {"id":1,"name":"sally", "role": "manager", "updated_at": "2020-01-13T18:42:21Z"},
  {"id":1,"name":"sally", "role": "director", "updated_at": "2020-01-14T10:17:45Z"},
  {"id":2,"name":"eric", "role": "leader", "updated_at": "2020-01-28T07:33:58Z"},
  {"id":3,"name":"john", "role": "leader", "updated_at": "2020-01-01T20:00:00Z"},
  {"id":2,"name":"eric", "role": "developer", "updated_at": "2020-01-10T08:28:31Z"},
]

df = spark.createDataFrame(Row(**x) for x in mylist)

w =  Window.partitionBy("id").orderBy(desc("updated_at"))

df1=df.withColumn("rn", row_number().over(w)).filter(col("rn") == 1).drop("rn")

df1.toJSON().collect()

#result
#[u'{"id":1,"name":"sally","role":"director","updated_at":"2020-01-14T10:17:45Z"}',
#u'{"id":2,"name":"eric","role":"leader","updated_at":"2020-01-28T07:33:58Z"}',
#u'{"id":3,"name":"john","role":"leader","updated_at":"2020-01-01T20:00:00Z"}']

#write to HDFS..etc filesystems
#only use repartition with less data or else use coalesce(1)

df1.repartition(1).write.mode("overwrite").format("json").save("<path>")
</code>```

Body:
I'm writing my first spark job and I'm stuck in a situation that I don't know how to solve with Spark. I have a list like this one:

mylist = [
  {"id":1,"name":"sally", "role": "manager", "updated_at": "2020-01-13T18:42:21Z"},
  {"id":1,"name":"sally", "role": "director", "updated_at": "2020-01-14T10:17:45Z"},
  {"id":2,"name":"eric", "role": "leader", "updated_at": "2020-01-28T07:33:58Z"},
  {"id":3,"name":"john", "role": "leader", "updated_at": "2020-01-01T20:00:00Z"},
  {"id":2,"name":"eric", "role": "developer", "updated_at": "2020-01-10T08:28:31Z"},
]

df = spark.createDataFrame(Row(**x) for x in mylist).show(truncate=False)

df.show(n=10)

I'm wondering if it's possible to filter this dataframe and get distinct rows (unique ids) based on max updated_at. The max value of updated_at represents the last status of each employee.

The expected output from example above is:

  {"id":1,"name":"sally", "role": "director", "updated_at": "2020-01-14T10:17:45Z"},
  {"id":2,"name":"eric", "role": "leader", "updated_at": "2020-01-28T07:33:58Z"},
  {"id":3,"name":"john", "role": "leader", "updated_at": "2020-01-01T20:00:00Z"},

If is it possible? For what function should I look?

Body:
Try to use row_number()-window function and get only the latest record for the uniqueids.
Then create a json output for the dataframe.

Example:

from pyspark.sql.functions import *
from pyspark.sql import *
from pyspark.sql.window import Window

mylist = [
  {"id":1,"name":"sally", "role": "manager", "updated_at": "2020-01-13T18:42:21Z"},
  {"id":1,"name":"sally", "role": "director", "updated_at": "2020-01-14T10:17:45Z"},
  {"id":2,"name":"eric", "role": "leader", "updated_at": "2020-01-28T07:33:58Z"},
  {"id":3,"name":"john", "role": "leader", "updated_at": "2020-01-01T20:00:00Z"},
  {"id":2,"name":"eric", "role": "developer", "updated_at": "2020-01-10T08:28:31Z"},
]

df = spark.createDataFrame(Row(**x) for x in mylist)

w =  Window.partitionBy("id").orderBy(desc("updated_at"))

df1=df.withColumn("rn", row_number().over(w)).filter(col("rn") == 1).drop("rn")

df1.toJSON().collect()

#result
#[u'{"id":1,"name":"sally","role":"director","updated_at":"2020-01-14T10:17:45Z"}',
#u'{"id":2,"name":"eric","role":"leader","updated_at":"2020-01-28T07:33:58Z"}',
#u'{"id":3,"name":"john","role":"leader","updated_at":"2020-01-01T20:00:00Z"}']

#write to HDFS..etc filesystems
#only use repartition with less data or else use coalesce(1)

df1.repartition(1).write.mode("overwrite").format("json").save("<path>")


问:
Android SDK missing emulator-arm on Linux
It seems like the latest versions of the Android emulator on Linux are missing the "emulator-arm" executable. I have version 29.3.4 and whenever I try to run an ARM AVD, I get the following error:

PANIC: Missing emulator engine program for 'arm' CPU.

Everywhere I find this error, people talk about Avast putting "emulator-arm" on quarantine, but I'm running Ubuntu 18.04, so that's clearly not the case here. I've downloaded the emulator straight from the repository using the following link

https://dl.google.com/android/repository/emulator-linux-6110076.zip

and the binaries for other architectures are really not there. What happened to them?

答:
Here's for those facing the same situation. Apparently I'm outdated and these binaries have been removed a while ago.

https://androidstudio.googleblog.com/2018/12/emulator-2810-canary.html

They now have an image that can translate arm to x86.

https://androidstudio.googleblog.com/2019/09/android-p-x86-system-images-google-play.html

I would like to emulate Android 5.1, but it seems that won't be possible with the latest SDK. You either downgrade or take that Android P image. =/


问:
I am looking find dups
I am trying to filter out the dups writing a query in Oracle TOAD SQL. Below is the data I have:

```<code>Primary          T_ID           C_ID
2039515494      276162453       20028
2176514662      276721971       5508
2176514662      276721972       5508
</code>```

I am looking to have only

```<code> Primary          T_ID          C_ID
2176514662      276721971       5508
2176514662      276721972       5508
</code>```

答:
This assumes that you are looking for rows with duplicate 'primary' values;

```<code>select * from t where primary in
(select primary from t group by(primary) having count(primary) > 1);
</code>```

This assumes you want to consider both primary and c_id

```<code>with t1 as (select primary, c_id from t group by(primary, c_id) having count(*) > 1)
select t.primary, t.t_id, t.c_id from t, t1 where t.c_id = t1.c_id and t.primary = t1.primary;
</code>```

Title: I am looking find dups

Body:
I am trying to filter out the dups writing a query in Oracle TOAD SQL. Below is the data I have:

Primary          T_ID           C_ID
2039515494      276162453       20028
2176514662      276721971       5508
2176514662      276721972       5508

I am looking to have only

 Primary          T_ID          C_ID
2176514662      276721971       5508
2176514662      276721972       5508

Body:
This assumes that you are looking for rows with duplicate 'primary' values;

select * from t where primary in
(select primary from t group by(primary) having count(primary) > 1);

This assumes you want to consider both primary and c_id

with t1 as (select primary, c_id from t group by(primary, c_id) having count(*) > 1)
select t.primary, t.t_id, t.c_id from t, t1 where t.c_id = t1.c_id and t.primary = t1.primary;


问:
How can I check which file is a function in?
I'm working with PHP and sometimes, I want to find where the function being used is located. How can I do this easily without tracing through everything?</p>

答:
I usually just do a quick

```<code>'grep -d recurse "function\ function_name" *
</code>```

from the root of the project.

Body:
I usually just do a quick

'grep -d recurse "function\ function_name" *

from the root of the project.


问:
Creating a dataframe using 3 other data frames that have no common merge values
I'm trying to accomplish a very particular type of data cleaning process using R.

I am given 2 dataframe structures and one matrix structure. The matrix corresponds to DF1 as column headers and DF2 as row headers, but I want to take all of this data and convert to a rectangular dataframe with one observation per row (based on result matrix, matrix_data).

Using the code below, I am able to create one observation per row, but for large data sets (~1M+ unique entries), this can take several minutes to run (~5 min). Right now, I am using a for loop to cycle through DF1, and I'm using do.call(... replicate()) to append rows to DF2. Treatment of the matrix_data is simple - I unwrap the data into a vector and cbind it to the DF1_ext and DF2_ext dataframes. Is there a better way to execute this for() loop in R?

```<code>DF1 <- data.frame(x_1 = c('a','b','c','d','e'), y_1 = c('f','g','h','i','j'), z_1 = c('k','l','m','n','o'))
DF2 <- data.frame(v_2 = 1:3, w_2 = 4:6, x_2 = 7:9, y_2 = 10:12, z_2 = 13:15)
matrix_data <- matrix(data = 1:15, nrow = 3, ncol = 5)

DF1_ext <- NULL
DF1_length <- nrow(DF1) * nrow(DF2)

#Use ceiling function to determine which row to put in NULL dataframe
#i.e. ceiling() rounds up to nearest integer value, setting j = to incremental step in origin dataframe
#See resultant DF

for (k in 1:DF1_length) {
  j = ceiling(k / DF1_length * length(DF1[,2]))
  DF1_ext <- rbind(DF1_ext[], DF1[j,])
}

#replicate DF2 matrix with rbind() based on the number of rows in DF1
DF2_ext <- do.call(rbind, replicate(nrow(DF1), DF2, simplify = FALSE))

#cbind() all values together.
#matrix_data can be transposed or not. This matters in the actual analysis, but should not matter here.
DF_result <- cbind(DF1_ext, DF2_ext, as.vector(t(matrix_data)))

View(DF_result)
</code>```

I am seeking a more "R" way of executing this code, hoping that there may be some more efficient functions along the way. This code, as is, can be copied into R and run with only base functions. To be clear, I am seeking a better way of executing in R because this method executes very slowly, and it seems like a lot of running around to do compared to most R methodology.

答:
This can be done pretty simply with the dplyr and tidyr packages.

```<code>library(dplyr)
library(tidyr)
test <- DF1 %>% mutate(list_col = list(DF2)) %>% unnest() %>%
  mutate(matrix_data = as.vector(t(matrix_data)))
</code>```

Basically it repeats DF2 as much as needed to fill all the rows in DF1 and then unnest repeats each row of DF1 for each row in DF2.

Body:
I'm trying to accomplish a very particular type of data cleaning process using R.

I am given 2 dataframe structures and one matrix structure. The matrix corresponds to DF1 as column headers and DF2 as row headers, but I want to take all of this data and convert to a rectangular dataframe with one observation per row (based on result matrix, matrix_data).

Using the code below, I am able to create one observation per row, but for large data sets (~1M+ unique entries), this can take several minutes to run (~5 min). Right now, I am using a for loop to cycle through DF1, and I'm using do.call(... replicate()) to append rows to DF2. Treatment of the matrix_data is simple - I unwrap the data into a vector and cbind it to the DF1_ext and DF2_ext dataframes. Is there a better way to execute this for() loop in R?

DF1 <- data.frame(x_1 = c('a','b','c','d','e'), y_1 = c('f','g','h','i','j'), z_1 = c('k','l','m','n','o'))
DF2 <- data.frame(v_2 = 1:3, w_2 = 4:6, x_2 = 7:9, y_2 = 10:12, z_2 = 13:15)
matrix_data <- matrix(data = 1:15, nrow = 3, ncol = 5)

DF1_ext <- NULL
DF1_length <- nrow(DF1) * nrow(DF2)

#Use ceiling function to determine which row to put in NULL dataframe
#i.e. ceiling() rounds up to nearest integer value, setting j = to incremental step in origin dataframe
#See resultant DF

for (k in 1:DF1_length) {
  j = ceiling(k / DF1_length * length(DF1[,2]))
  DF1_ext <- rbind(DF1_ext[], DF1[j,])
}

#replicate DF2 matrix with rbind() based on the number of rows in DF1
DF2_ext <- do.call(rbind, replicate(nrow(DF1), DF2, simplify = FALSE))

#cbind() all values together.
#matrix_data can be transposed or not. This matters in the actual analysis, but should not matter here.
DF_result <- cbind(DF1_ext, DF2_ext, as.vector(t(matrix_data)))

View(DF_result)

I am seeking a more "R" way of executing this code, hoping that there may be some more efficient functions along the way. This code, as is, can be copied into R and run with only base functions. To be clear, I am seeking a better way of executing in R because this method executes very slowly, and it seems like a lot of running around to do compared to most R methodology.

Body:
This can be done pretty simply with the dplyr and tidyr packages.

library(dplyr)
library(tidyr)
test <- DF1 %>% mutate(list_col = list(DF2)) %>% unnest() %>%
  mutate(matrix_data = as.vector(t(matrix_data)))

Basically it repeats DF2 as much as needed to fill all the rows in DF1 and then unnest repeats each row of DF1 for each row in DF2.