问:
Various Errors, depending on format - RunTime "438", "91", "13"
I am attempting to copy multiple columns from one workbook into another based on the values in a third column. I've attempted multiple formats for this, declaring the Object as range, or variant, setting the selected range as .value or .select.  All in all, this has resulted in Runtime Errors 438, 424, 91, and 13.

This most recent iteration is producing 'Runtime error 438: Object doesn't support this property or method`.

```<code>Sub Fetch()
    Dim Group As String
    Dim gPath As String
    Dim BUname As String
    Dim PMAname As String
    Dim Backup As Workbook
    Dim PMA As Workbook
    Dim Fetch As Workbook, Home As Worksheet

    Set Fetch = ThisWorkbook
    Set Home = ThisWorkbook.Sheets("Home")
    Group = Range("B2").Value
    mola = Range("B1").Value
    maybe = Format(mola, "mm")
    real = Format(mola, "yy")
    nope = Format(mola, "yyyy")
    ShtNm = Format(mola, "mm.yy")
    gPath = "U:\BILLREC\M & R EG Billing\Analysts\My Name\" & Group & "\M2M\Original Backup" & "\" & nope & "\"
    BUname = gPath & maybe & "." & real & " " & "Original Backup" & ".xlsx"
    PMAname = gPath & maybe & "." & real & " " & "PMA" & ".xlsx"

    'Opens Backup File and determines current premium
    Set Backup = Workbooks.Open(BUname)

        Backup.Sheets(ShtNm).Range(Range("E2"), Range("E2").End(xlDown)).Copy
        Home.Range("D2").PasteSpecial xlPasteValues

        Backup.Sheets(ShtNm).Range(Range("N2"), Range("N2").End(xlDown)).Copy
        Home.Range("E2").PasteSpecial xlPasteValues

        If Application.CountIf(Backup.Sheets(ShtNm).Range(Range("BW2"), Range("BW2").End(xlDown)).Values, "<>0") < 0 Then 'Runtime 438 occurs here.
            Backup.Sheets(ShtNm).Range(Range("BX2"), Range("BX2").End(xlDown)).Copy
            Home.Range("F2").PasteSpecial xlPasteValues
            Backup.Sheets(ShtNm).Range(Range("BY2"), Range("BY2").End(xlDown)).Copy
            Home.Range("G2").PasteSpecial xlPasteValues
        Else
            Backup.Sheets(ShtNm).Range(Range("CA2"), Range("CA2").End(xlDown)).Copy
            Home.Range("F2").PasteSpecial xlPasteValues
            Backup.Sheets(ShtNm).Range(Range("CB2"), Range("CB2").End(xlDown)).Copy
            Home.Range("G2").PasteSpecial xlPasteValues
        End If

    Set PMA = Workbooks.Open(PMAname)
End Sub
</code>```

Another variation I've attempted is naming the actual range... again, this results in a 438:

```<code>Backup.Sheets(ShtNm).Range(Range("N2"), Range("N2").End(xlDown)).Copy
Home.Range("E2").PasteSpecial xlPasteValues

TotPrm = Backup.Sheets(ShtNm).Range(Range("BW2"), Range("BW2").End(xlDown)).Values 'Error Occurs here now.

If Application.CountIf(TotPrm, "<>0") < 0 Then
    Backup.Sheets(ShtNm).Range(Range("BX2"), Range("BX2").End(xlDown)).Copy
    Home.Range("F2").PasteSpecial xlPasteValues
    Backup.Sheets(ShtNm).Range(Range("BY2"), Range("BY2").End(xlDown)).Copy
    Home.Range("G2").PasteSpecial xlPasteValues
Else
</code>```

I've attempted to declare TotPrm as both a Range, and a Variant with the same 438 via:

```<code>Dim TotPrm As Range
</code>```

and

```<code>Dim TotPrm As Variant
</code>```

With the same 438 occurring at the same point.

Changing .Values to .Value resulted in a Runtime 424 Object Required:

```<code>Set TotPrm = Backup.Sheets(ShtNm).Range(Range("BW2"), Range("BW2").End(xlDown)).Value 'This line is the bane of my existence
</code>```

My dataset that this is being run against is:

```<code>BW       BX      BY      BZ       CA      CB
TotPrmA  CurA    RetroA  TotPrmB  CurB    RetroB
$0.00    $0.00   $0.00   $42.55   $42.55  $0.00
$0.00    $0.00   $0.00   $39.72   $39.72  $0.00
$0.00    $0.00   $0.00   $39.72   $39.72  $0.00
$0.00    $0.00   $0.00   $41.14   $41.14  $0.00
$0.00    $0.00   $0.00   $41.14   $41.14  $0.00
$0.00    $0.00   $0.00   $41.14   $41.14  $0.00
$0.00    $0.00   $0.00   $82.28   $82.28  $0.00
$0.00    $0.00   $0.00   $39.72   $39.72  $0.00
</code>```

This is an array of Total Premiums, Current Premiums, Retroactive Adjustments that are repeated.  As you can see by the If...Else function that immediately follows my troublesome devil, it's looking for a value other than zero in the first Total Premiums column, and determining which columns to copy over based on the results. With TotPrm declared as Variant and defined as Range.Value it produces the Runtime Error 13: Type Mismatch at the same line.

Last but not least, the Runtime 91:

```<code>Dim TotPrm As Range
TotPrm = Backup.Sheets(ShtNm).Range(Range("BW2"), Range("BW2").End(xlDown)).Value
</code>```

I'm at my wits' end.  Any help would be vastly appreciated!

答:
Dim TotPrm As Range expects a Range object when assigned, and since it's an object, must use the Set keyword:

```<code>Set TotPrm = <expression that evaluates to an instance of a Range object>
</code>```

So when you do this, you're missing the Set keyword for starters, also the Select method actually returns a Boolean (True/False) value, not the range itself.

```<code>TotPrm = Backup.Sheets(ShtNm).Range(Range("BW2"), Range("BW2").End(xlDown)).Select
</code>```

Likewise, this fails because you've defined TotPrem as an object (Range) but you're attempting to assign to it some other data type -- the range.Value is not a Range (and even if it were, you'd need to use Set keyord as above) -- but a string,numeric/etc.

```<code>TotPrm = Backup.Sheets(ShtNm).Range(Range("BW2"), Range("BW2").End(xlDown)).Value`
</code>```

Remove the Select (or .Value, etc.) and use Set:

```<code>Set TotPrm = Backup.Sheets(ShtNm).Range(Range("BW2"), Range("BW2").End(xlDown))
</code>```

Body:
I am attempting to copy multiple columns from one workbook into another based on the values in a third column. I've attempted multiple formats for this, declaring the Object as range, or variant, setting the selected range as .value or .select.  All in all, this has resulted in Runtime Errors 438, 424, 91, and 13.

This most recent iteration is producing 'Runtime error 438: Object doesn't support this property or method`.

Sub Fetch()
    Dim Group As String
    Dim gPath As String
    Dim BUname As String
    Dim PMAname As String
    Dim Backup As Workbook
    Dim PMA As Workbook
    Dim Fetch As Workbook, Home As Worksheet

    Set Fetch = ThisWorkbook
    Set Home = ThisWorkbook.Sheets("Home")
    Group = Range("B2").Value
    mola = Range("B1").Value
    maybe = Format(mola, "mm")
    real = Format(mola, "yy")
    nope = Format(mola, "yyyy")
    ShtNm = Format(mola, "mm.yy")
    gPath = "U:\BILLREC\M & R EG Billing\Analysts\My Name\" & Group & "\M2M\Original Backup" & "\" & nope & "\"
    BUname = gPath & maybe & "." & real & " " & "Original Backup" & ".xlsx"
    PMAname = gPath & maybe & "." & real & " " & "PMA" & ".xlsx"

    'Opens Backup File and determines current premium
    Set Backup = Workbooks.Open(BUname)

        Backup.Sheets(ShtNm).Range(Range("E2"), Range("E2").End(xlDown)).Copy
        Home.Range("D2").PasteSpecial xlPasteValues

        Backup.Sheets(ShtNm).Range(Range("N2"), Range("N2").End(xlDown)).Copy
        Home.Range("E2").PasteSpecial xlPasteValues

        If Application.CountIf(Backup.Sheets(ShtNm).Range(Range("BW2"), Range("BW2").End(xlDown)).Values, "<>0") < 0 Then 'Runtime 438 occurs here.
            Backup.Sheets(ShtNm).Range(Range("BX2"), Range("BX2").End(xlDown)).Copy
            Home.Range("F2").PasteSpecial xlPasteValues
            Backup.Sheets(ShtNm).Range(Range("BY2"), Range("BY2").End(xlDown)).Copy
            Home.Range("G2").PasteSpecial xlPasteValues
        Else
            Backup.Sheets(ShtNm).Range(Range("CA2"), Range("CA2").End(xlDown)).Copy
            Home.Range("F2").PasteSpecial xlPasteValues
            Backup.Sheets(ShtNm).Range(Range("CB2"), Range("CB2").End(xlDown)).Copy
            Home.Range("G2").PasteSpecial xlPasteValues
        End If

    Set PMA = Workbooks.Open(PMAname)
End Sub

Another variation I've attempted is naming the actual range... again, this results in a 438:

Backup.Sheets(ShtNm).Range(Range("N2"), Range("N2").End(xlDown)).Copy
Home.Range("E2").PasteSpecial xlPasteValues

TotPrm = Backup.Sheets(ShtNm).Range(Range("BW2"), Range("BW2").End(xlDown)).Values 'Error Occurs here now.

If Application.CountIf(TotPrm, "<>0") < 0 Then
    Backup.Sheets(ShtNm).Range(Range("BX2"), Range("BX2").End(xlDown)).Copy
    Home.Range("F2").PasteSpecial xlPasteValues
    Backup.Sheets(ShtNm).Range(Range("BY2"), Range("BY2").End(xlDown)).Copy
    Home.Range("G2").PasteSpecial xlPasteValues
Else

I've attempted to declare TotPrm as both a Range, and a Variant with the same 438 via:

Dim TotPrm As Range

and

Dim TotPrm As Variant

With the same 438 occurring at the same point.

Changing .Values to .Value resulted in a Runtime 424 Object Required:

Set TotPrm = Backup.Sheets(ShtNm).Range(Range("BW2"), Range("BW2").End(xlDown)).Value 'This line is the bane of my existence

My dataset that this is being run against is:

BW       BX      BY      BZ       CA      CB
TotPrmA  CurA    RetroA  TotPrmB  CurB    RetroB
$0.00    $0.00   $0.00   $42.55   $42.55  $0.00
$0.00    $0.00   $0.00   $39.72   $39.72  $0.00
$0.00    $0.00   $0.00   $39.72   $39.72  $0.00
$0.00    $0.00   $0.00   $41.14   $41.14  $0.00
$0.00    $0.00   $0.00   $41.14   $41.14  $0.00
$0.00    $0.00   $0.00   $41.14   $41.14  $0.00
$0.00    $0.00   $0.00   $82.28   $82.28  $0.00
$0.00    $0.00   $0.00   $39.72   $39.72  $0.00

This is an array of Total Premiums, Current Premiums, Retroactive Adjustments that are repeated.  As you can see by the If...Else function that immediately follows my troublesome devil, it's looking for a value other than zero in the first Total Premiums column, and determining which columns to copy over based on the results. With TotPrm declared as Variant and defined as Range.Value it produces the Runtime Error 13: Type Mismatch at the same line.

Last but not least, the Runtime 91:

Dim TotPrm As Range
TotPrm = Backup.Sheets(ShtNm).Range(Range("BW2"), Range("BW2").End(xlDown)).Value

I'm at my wits' end.  Any help would be vastly appreciated!

Body:
Dim TotPrm As Range expects a Range object when assigned, and since it's an object, must use the Set keyword:

Set TotPrm = <expression that evaluates to an instance of a Range object>

So when you do this, you're missing the Set keyword for starters, also the Select method actually returns a Boolean (True/False) value, not the range itself.

TotPrm = Backup.Sheets(ShtNm).Range(Range("BW2"), Range("BW2").End(xlDown)).Select

Likewise, this fails because you've defined TotPrem as an object (Range) but you're attempting to assign to it some other data type -- the range.Value is not a Range (and even if it were, you'd need to use Set keyord as above) -- but a string,numeric/etc.

TotPrm = Backup.Sheets(ShtNm).Range(Range("BW2"), Range("BW2").End(xlDown)).Value`

Remove the Select (or .Value, etc.) and use Set:

Set TotPrm = Backup.Sheets(ShtNm).Range(Range("BW2"), Range("BW2").End(xlDown))


来源: stackexchange

问:
Google People API, return last modified date?
Is there a way to retrieve the last modified timestamp for this endpoint GET https://people.googleapis.com/v1/{resourceName=people/*}/connections

I am unable to see anything close to resembling this in the Person object fields described here https://developers.google.com/people/api/rest/v1/people#Person

答:
Recently an updateTime was added to the Source field https://developers.google.com/people/api/rest/v1/people#Person.Source.

You can get it by iterating over the person.metadata.sources

ContentLicense: CC BY-SA 3.0


问:
How can I select the first word of every line of a block of text?
I'm trying to select each first word, to wrap it in a specific span.

Lorem ipsum dolor sit amet,
  consectetur adipiscing elit. Cras
  sagittis nunc non nisi venenatis
  auctor. Aliquam consectetur pretium
  sapien, eget congue purus egestas nec.
  Maecenas sed purus ut turpis varius
  dictum. Praesent a nunc ipsum, id
  mattis odio. Donec rhoncus posuere
  bibendum. Fusce nulla elit, laoreet
  non posuere.

If this is the text, the script should select Lorem, Aliquam, varius and nulla.

答:
You can do this, by using JavaScript to wrap every word in the paragraph in its own span, and then walking through the spans finding out what their actual position on the page is, and then applying your style changes to the spans whose Y position is greater than the preceding span. (Best do it beginning-to-end, though, as earlier ones may well affect the wrapping of latter ones.) But it's going to be a lot of work for the browser, and you'll have to repeat it each time the window is resized, so the effect will have to be worth the cost.

Something like this (used jQuery as you've listed the jquery tag on your question):

jQuery(function($) {
  var lasty;

  var $target = $('#target');
  $target.html(
    "" +
    $target.text().split(/\s/).join(" ") +
    "");
  lasty = -1;
  $target.find('span').each(function() {
    var $this = $(this),
        top = $this.position().top;
    if (top > lasty) {
      $this.css("fontWeight", "bold");
      lasty = top;
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='target' style='width: 20em'>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sagittis nunc non nisi venenatis auctor. Aliquam consectetur pretium sapien, eget congue purus egestas nec. Maecenas sed purus ut turpis varius dictum. Praesent a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere.</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script></code>```

Naturally that's making a huge set of assumptions (that all whitespace should be replaced with a single space, that there's no markup in the text, probably others). But you get the idea.

Here's a version that handles window resize, 50ms after the last resize event occurs (so we're not doing it interim) and with Gaby's suggestion (below) that we unbold at the start of the resize:

jQuery(function($) {
  var resizeTriggerHandle = 0;

  // Do it on load
  boldFirstWord('#target');

  // Do it 100ms after the end of a resize operation,
  // because it's *expensive*
  $(window).resize(function() {
    if (resizeTriggerHandle != 0) {
      clearTimeout(resizeTriggerHandle);
    }
    unboldFirstWord('#target');
    resizeTriggerHandle = setTimeout(function() {
      resizeTriggerHandle = 0;
      boldFirstWord('#target');
    }, 50);
  });

  function boldFirstWord(selector) {
    var lasty;

    // Break into spans if not already done;
    // if already done, remove any previous bold
    var $target = $(selector);
    if (!$target.data('spanned')) {
      $target.html(
        "" +
        $target.text().split(/\s/).join(" ") +
        "");
      $target.data('spanned', true);
    }
    else {
      unboldFirstWord($target);
    }

    // Apply bold to first span of each new line
    lasty = -1;
    $target.find('span').each(function() {
      var $this = $(this),
          top = $this.position().top;
      if (top > lasty) {
        $this.css("fontWeight", "bold");
        lasty = top;
      }
    });
    $target.data('bolded', true);
  }

  function unboldFirstWord(selector) {
    var $target = selector.jquery ? selector : $(selector);
    if ($target.data('spanned') && $target.data('bolded')) {
      $target.find('span').css("fontWeight", "normal");
      $target.data('bolded', false);
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='target'>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sagittis nunc non nisi venenatis auctor. Aliquam consectetur pretium sapien, eget congue purus egestas nec. Maecenas sed purus ut turpis varius dictum. Praesent a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sagittis nunc non nisi venenatis auctor. Aliquam consectetur pretium sapien, eget congue purus egestas nec. Maecenas sed purus ut turpis varius dictum. Praesent a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sagittis nunc non nisi venenatis auctor. Aliquam consectetur pretium sapien, eget congue purus egestas nec. Maecenas sed purus ut turpis varius dictum. Praesent a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sagittis nunc non nisi venenatis auctor. Aliquam consectetur pretium sapien, eget congue purus egestas nec. Maecenas sed purus ut turpis varius dictum. Praesent a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sagittis nunc non nisi venenatis auctor. Aliquam consectetur pretium sapien, eget congue purus egestas nec. Maecenas sed purus ut turpis varius dictum. Praesent a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere.</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script></code>```

ContentLicense: CC BY-SA 4.0

Body:
You can do this, by using JavaScript to wrap every word in the paragraph in its own span, and then walking through the spans finding out what their actual position on the page is, and then applying your style changes to the spans whose Y position is greater than the preceding span. (Best do it beginning-to-end, though, as earlier ones may well affect the wrapping of latter ones.) But it's going to be a lot of work for the browser, and you'll have to repeat it each time the window is resized, so the effect will have to be worth the cost.

Something like this (used jQuery as you've listed the jquery tag on your question):

jQuery(function($) {
  var lasty;

  var $target = $('#target');
  $target.html(
    "<span>" +
    $target.text().split(/\s/).join("</span> <span>") +
    "</span>");
  lasty = -1;
  $target.find('span').each(function() {
    var $this = $(this),
        top = $this.position().top;
    if (top > lasty) {
      $this.css("fontWeight", "bold");
      lasty = top;
    }
  });
});

<div id='target' style='width: 20em'>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sagittis nunc non nisi venenatis auctor. Aliquam consectetur pretium sapien, eget congue purus egestas nec. Maecenas sed purus ut turpis varius dictum. Praesent a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere.</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

Naturally that's making a huge set of assumptions (that all whitespace should be replaced with a single space, that there's no markup in the text, probably others). But you get the idea.

Here's a version that handles window resize, 50ms after the last resize event occurs (so we're not doing it interim) and with Gaby's suggestion (below) that we unbold at the start of the resize:

jQuery(function($) {
  var resizeTriggerHandle = 0;

  // Do it on load
  boldFirstWord('#target');

  // Do it 100ms after the end of a resize operation,
  // because it's *expensive*
  $(window).resize(function() {
    if (resizeTriggerHandle != 0) {
      clearTimeout(resizeTriggerHandle);
    }
    unboldFirstWord('#target');
    resizeTriggerHandle = setTimeout(function() {
      resizeTriggerHandle = 0;
      boldFirstWord('#target');
    }, 50);
  });

  function boldFirstWord(selector) {
    var lasty;

    // Break into spans if not already done;
    // if already done, remove any previous bold
    var $target = $(selector);
    if (!$target.data('spanned')) {
      $target.html(
        "<span>" +
        $target.text().split(/\s/).join("</span> <span>") +
        "</span>");
      $target.data('spanned', true);
    }
    else {
      unboldFirstWord($target);
    }

    // Apply bold to first span of each new line
    lasty = -1;
    $target.find('span').each(function() {
      var $this = $(this),
          top = $this.position().top;
      if (top > lasty) {
        $this.css("fontWeight", "bold");
        lasty = top;
      }
    });
    $target.data('bolded', true);
  }

  function unboldFirstWord(selector) {
    var $target = selector.jquery ? selector : $(selector);
    if ($target.data('spanned') && $target.data('bolded')) {
      $target.find('span').css("fontWeight", "normal");
      $target.data('bolded', false);
    }
  }
});

<div id='target'>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sagittis nunc non nisi venenatis auctor. Aliquam consectetur pretium sapien, eget congue purus egestas nec. Maecenas sed purus ut turpis varius dictum. Praesent a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sagittis nunc non nisi venenatis auctor. Aliquam consectetur pretium sapien, eget congue purus egestas nec. Maecenas sed purus ut turpis varius dictum. Praesent a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sagittis nunc non nisi venenatis auctor. Aliquam consectetur pretium sapien, eget congue purus egestas nec. Maecenas sed purus ut turpis varius dictum. Praesent a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sagittis nunc non nisi venenatis auctor. Aliquam consectetur pretium sapien, eget congue purus egestas nec. Maecenas sed purus ut turpis varius dictum. Praesent a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sagittis nunc non nisi venenatis auctor. Aliquam consectetur pretium sapien, eget congue purus egestas nec. Maecenas sed purus ut turpis varius dictum. Praesent a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere.</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>


问:
How to return a list of keys corresponding to the smallest value in dictionary
Let say I have a dictionary of total of fruits:

```<code>Fruits = {"apple":8, "banana":3, "lemon":5, "pineapple":2,}
</code>```

And I want the output to be

```<code>["pineapple"]
</code>```

because pineapple has the least value. Or if I have this:

```<code>Colour = {"blue":5, "green":2, "purple":6, "red":2}
</code>```

The output will be:

```<code>["green","red"]
</code>```

because green and red has both the least value.

So how do I return the smallest value in dictionary?

答:
```<code>minimum = []      # creates empty list for all possible minimum keys
def min(dict):    # defines a function called minimum taking a argument dict
    m= min(dict.values())     # stating minimum value in dict
    for key, values in dict.items():     # iterating through key and values in items of dictionary
        if value == m:        # checking if value is minimum
            minimum.append(key)      # appending minimum values to the empty list created
    return minimum         # returning the list
</code>```

Body:
Let say I have a dictionary of total of fruits:

Fruits = {"apple":8, "banana":3, "lemon":5, "pineapple":2,}

And I want the output to be

["pineapple"]

because pineapple has the least value. Or if I have this:

Colour = {"blue":5, "green":2, "purple":6, "red":2}

The output will be:

["green","red"]

because green and red has both the least value.

So how do I return the smallest value in dictionary?


问:
Ruby on Rails omniauth and carrierwave
I'm using omniauth ( omniauth-facebook) in my ruby on rails application. I would like to know whether I can retrieve user's city, country and gender information. And how can I take user profile photo with carrierwave,

Thanks.

答:
Using the (Carrierwave Documentation)[https://github.com/carrierwaveuploader/carrierwave] as my reference, you would need to modify your user model to add a new fields to support the carrierwave gem functionality.

Typically this means:

```<code>class User < ActiveRecord::Base
  mount_uploader :avatar, AvatarUploader
end
</code>```

But it will vary if you are using MongoDB instead of an SQL/ActiveRecord.

You can test this new field exists by initializing a new object in the rails console and examining the fields available.

```<code>bundle exec rails c

u = User.new
u.(tab twice quickly to see the available options)
# You are looking for the avatar field
u.avatar
</code>```

You can set it from console to test it using

```<code>File.open('somewhere') do |f|
  u.avatar = f
end
</code>```

Then finally you would add it to the form field in your views once you tested it. You typically have a CRUD for your user so in the Create/Update forms in the views, you modify these forms to include a file form (this is HTML not specifically rails, so you can look up more information using HTML in your search), and once it is added, you will need to modify the corresponding controllers to whitelist the value so it can be saved using these controller actions.

The process is similar to adding other fields to your user object after the initial generation of the user model.

Title: Ruby on Rails omniauth and carrierwave

Body:
Using the (Carrierwave Documentation)[https://github.com/carrierwaveuploader/carrierwave] as my reference, you would need to modify your user model to add a new fields to support the carrierwave gem functionality.

Typically this means:

class User < ActiveRecord::Base
  mount_uploader :avatar, AvatarUploader
end

But it will vary if you are using MongoDB instead of an SQL/ActiveRecord.

You can test this new field exists by initializing a new object in the rails console and examining the fields available.

bundle exec rails c

u = User.new
u.(tab twice quickly to see the available options)
# You are looking for the avatar field
u.avatar

You can set it from console to test it using

File.open('somewhere') do |f|
  u.avatar = f
end

Then finally you would add it to the form field in your views once you tested it. You typically have a CRUD for your user so in the Create/Update forms in the views, you modify these forms to include a file form (this is HTML not specifically rails, so you can look up more information using HTML in your search), and once it is added, you will need to modify the corresponding controllers to whitelist the value so it can be saved using these controller actions.

The process is similar to adding other fields to your user object after the initial generation of the user model.


问:
Copy Cell, then Apply formula on original cell
I am searching for a keyword then copying the row contents from the found keyword into my current sheet.  I am then firstly trying to copy the contents from cell D to cell Z in order to then carry out the formula:

"=RIGHT(Z2,LEN(Z2)-FIND(""_"",Z2))"

I have the code in another separate Sub as

Range("D1:D" & LastRow).Copy Range("Z1:Z" & LastRow)
Range("D2:D" & LastRow).Formula = "=RIGHT(Z2,LEN(Z2)-FIND(""_"",Z2))"

How to incorporate this formula so that on each write in the Private Sub the D cell gets firstly copied to cell Z, then put the formula in cell D?

Here is the default code:

```<code>Sub SearchFolders()
'UpdatebySUPERtoolsforExcel2016
    Dim xFso As Object
    Dim xFld As Object
    Dim xUpdate As Boolean
    Dim xCount As Long
    On Error GoTo ErrHandler
    Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
    xFileDialog.AllowMultiSelect = False
    xFileDialog.Title = "Select a folder"
    If xFileDialog.Show = -1 Then
        xStrPath = xFileDialog.SelectedItems(1)
    End If
    If xStrPath = "" Then Exit Sub
    xStrSearch = "failed"
    xUpdate = Application.ScreenUpdating
    Application.ScreenUpdating = False
    Set xOut = wsReport
    xRow = 1
    With xOut
        .Cells(xRow, 1) = "Workbook"
        .Cells(xRow, 2) = "Worksheet"
        .Cells(xRow, 8) = "Unit"
        .Cells(xRow, 9) = "Status"
        Set xFso = CreateObject("Scripting.FileSystemObject")
        Set xFld = xFso.GetFolder(xStrPath)
        xStrFile = Dir(xStrPath & "\*.xlsx")
        Do While xStrFile <> ""
            Set xWb = Workbooks.Open(Filename:=xStrPath & "\" & xStrFile, UpdateLinks:=0, ReadOnly:=True, AddToMRU:=False)
            For Each xWk In xWb.Worksheets
                Set xFound = xWk.UsedRange.Find(xStrSearch, LookIn:=xlValues)
                If Not xFound Is Nothing Then
                    xStrAddress = xFound.Address
                End If
                Do
                    If xFound Is Nothing Then
                        Exit Do
                    Else

                        xCount = xCount + 1
                        xRow = xRow + 1
                        .Cells(xRow, 1) = xWb.Name
                        .Cells(xRow, 2) = xWk.Name
                        .Cells(xRow, 3) = xFound.Address
                        WriteDetails rCellwsReport, xFound

                    End If
                    Set xFound = xWk.Cells.FindNext(After:=xFound)
                Loop While xStrAddress <> xFound.Address
            Next
            xWb.Close (False)
            xStrFile = Dir
        Loop
        .Columns("A:I").EntireColumn.AutoFit
        .Rows(xCount).EntireRow.AutoFit
    End With

    MsgBox xCount & "cells have been found", , "SUPERtools for Excel"
ExitHandler:
    Set xOut = Nothing

    Application.ScreenUpdating = xUpdate
    Exit Sub
ErrHandler:
    MsgBox Err.Description, vbExclamation
    Resume ExitHandler
End Sub

Private Sub WriteDetails(ByRef xReceiver As Range, ByRef xDonor As Range)
  xReceiver.Value = xDonor.Parent.Name
  xReceiver.Offset(, 1).Value = xDonor.Address

  ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
  ' Copy the row of the Donor to the receiver starting from column D.
  ' Since you want to preserve formats, we use the .Copy method
    xDonor.EntireRow.Resize(, 100).Copy xReceiver.Offset(, 2)
  ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
  Set xReceiver = xReceiver.Offset(1)

End Sub
</code>```

答:
```<code>xDonor.EntireRow.Resize(, 100).Copy xReceiver.Offset(, 2)
</code>```

May be you need to add the following after the above line:

```<code>With xReceiver.Parent.Cells(xReceiver.row, "D")
  .Copy xReceiver.Parent.Cells(xReceiver.row, "Z")
  .Formula = "=RIGHT(Z" & .row & ",LEN(Z" & .row & ")-FIND(""_"",Z" & .row & "))"
End With
</code>```

Body:
I am searching for a keyword then copying the row contents from the found keyword into my current sheet.  I am then firstly trying to copy the contents from cell D to cell Z in order to then carry out the formula:

"=RIGHT(Z2,LEN(Z2)-FIND(""_"",Z2))"

I have the code in another separate Sub as

Range("D1:D" & LastRow).Copy Range("Z1:Z" & LastRow)
Range("D2:D" & LastRow).Formula = "=RIGHT(Z2,LEN(Z2)-FIND(""_"",Z2))"

How to incorporate this formula so that on each write in the Private Sub the D cell gets firstly copied to cell Z, then put the formula in cell D?

Here is the default code:

Sub SearchFolders()
'UpdatebySUPERtoolsforExcel2016
    Dim xFso As Object
    Dim xFld As Object
    Dim xUpdate As Boolean
    Dim xCount As Long
    On Error GoTo ErrHandler
    Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
    xFileDialog.AllowMultiSelect = False
    xFileDialog.Title = "Select a folder"
    If xFileDialog.Show = -1 Then
        xStrPath = xFileDialog.SelectedItems(1)
    End If
    If xStrPath = "" Then Exit Sub
    xStrSearch = "failed"
    xUpdate = Application.ScreenUpdating
    Application.ScreenUpdating = False
    Set xOut = wsReport
    xRow = 1
    With xOut
        .Cells(xRow, 1) = "Workbook"
        .Cells(xRow, 2) = "Worksheet"
        .Cells(xRow, 8) = "Unit"
        .Cells(xRow, 9) = "Status"
        Set xFso = CreateObject("Scripting.FileSystemObject")
        Set xFld = xFso.GetFolder(xStrPath)
        xStrFile = Dir(xStrPath & "\*.xlsx")
        Do While xStrFile <> ""
            Set xWb = Workbooks.Open(Filename:=xStrPath & "\" & xStrFile, UpdateLinks:=0, ReadOnly:=True, AddToMRU:=False)
            For Each xWk In xWb.Worksheets
                Set xFound = xWk.UsedRange.Find(xStrSearch, LookIn:=xlValues)
                If Not xFound Is Nothing Then
                    xStrAddress = xFound.Address
                End If
                Do
                    If xFound Is Nothing Then
                        Exit Do
                    Else

                        xCount = xCount + 1
                        xRow = xRow + 1
                        .Cells(xRow, 1) = xWb.Name
                        .Cells(xRow, 2) = xWk.Name
                        .Cells(xRow, 3) = xFound.Address
                        WriteDetails rCellwsReport, xFound

                    End If
                    Set xFound = xWk.Cells.FindNext(After:=xFound)
                Loop While xStrAddress <> xFound.Address
            Next
            xWb.Close (False)
            xStrFile = Dir
        Loop
        .Columns("A:I").EntireColumn.AutoFit
        .Rows(xCount).EntireRow.AutoFit
    End With

    MsgBox xCount & "cells have been found", , "SUPERtools for Excel"
ExitHandler:
    Set xOut = Nothing

    Application.ScreenUpdating = xUpdate
    Exit Sub
ErrHandler:
    MsgBox Err.Description, vbExclamation
    Resume ExitHandler
End Sub

Private Sub WriteDetails(ByRef xReceiver As Range, ByRef xDonor As Range)
  xReceiver.Value = xDonor.Parent.Name
  xReceiver.Offset(, 1).Value = xDonor.Address

  ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
  ' Copy the row of the Donor to the receiver starting from column D.
  ' Since you want to preserve formats, we use the .Copy method
    xDonor.EntireRow.Resize(, 100).Copy xReceiver.Offset(, 2)
  ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
  Set xReceiver = xReceiver.Offset(1)

End Sub

Body:
xDonor.EntireRow.Resize(, 100).Copy xReceiver.Offset(, 2)

May be you need to add the following after the above line:

With xReceiver.Parent.Cells(xReceiver.row, "D")
  .Copy xReceiver.Parent.Cells(xReceiver.row, "Z")
  .Formula = "=RIGHT(Z" & .row & ",LEN(Z" & .row & ")-FIND(""_"",Z" & .row & "))"
End With


问:
Safari Web inspector keeps disconnecting
I've Safari 8.0.6 with iOS 8.3 on my iPad, while debugging through Web Inspector on my Mac (10.10.3), the connection keeps on disconnecting (I don't see the device name under Develop menu upon disconnection) but can resume if I quit safari followed by a relaunch then I'm able to refresh and inspect remotely again.

答:
The most recent Safari Technology preview appears to have solved it for me.

https://developer.apple.com/safari/technology-preview/


问:
chrome.tabs.captureVisibleTab captures wrong area
I am trying to create chrome extension which will take a screenshot of a large page.

Here is a  my simple extension that should scroll to and capture some parts of a page.

manifest.json

```<code>    {

      "manifest_version": 2,
      "name": "screenshot_test",
      "version": "1.0",

      "permissions": [
        "tabs",
        "<all_urls>"
      ],

      "background": {
        "scripts": ["background.js"]
      },

      "browser_action": {
        "default_icon":  "icon.png"
      }

    }
</code>```

background.js

```<code>chrome.browserAction.onClicked.addListener(capture)
function capture(){

    function scroll(point, callback){
        chrome.tabs.executeScript({
            code: 'window.scrollTo('+JSON.stringify((point.x))+','+JSON.stringify(point.y)+')',
        }, callback)
    }

    function capturetab(){
        chrome.tabs.captureVisibleTab(function(imageUri){
            shots.push(imageUri);
        });
    }

    var shots=[];
    var points=[{x: 0, y: 0}, {x: 500, y: 500},{x: 1000, y: 1000}];

    for (var i=0; i<3; i++) scroll(points[i], capturetab);
    console.log(shots);
}
</code>```

The issue is that shots[], the array of imageuris, contains some identical imageuris, like if capturevisibletab captures the same area several times.

In firefox that exact same code works just fine, with the exception that in firefox capturevisibletab returns promise and callback is not an obligatory.

答:
Your scroll() function assumes that the tab is scrolled before callback() is invoked.

There is no such guarantee because the API is asynchronous.

I guess it works for you now only because your FF still runs in single-process mode.

Specify the callback in executeScript so that it's called back after the script is actually executed.

```<code>  function scroll(point, callback){
    chrome.tabs.executeScript({
      code: 'window.scrollTo('+JSON.stringify((point.x))+','+JSON.stringify(point.y)+')'
    }, callback);
  }
</code>```

Body:
I am trying to create chrome extension which will take a screenshot of a large page.

Here is a  my simple extension that should scroll to and capture some parts of a page.

manifest.json

    {

      "manifest_version": 2,
      "name": "screenshot_test",
      "version": "1.0",

      "permissions": [
        "tabs",
        "<all_urls>"
      ],

      "background": {
        "scripts": ["background.js"]
      },

      "browser_action": {
        "default_icon":  "icon.png"
      }

    }

background.js

chrome.browserAction.onClicked.addListener(capture)
function capture(){

    function scroll(point, callback){
        chrome.tabs.executeScript({
            code: 'window.scrollTo('+JSON.stringify((point.x))+','+JSON.stringify(point.y)+')',
        }, callback)
    }

    function capturetab(){
        chrome.tabs.captureVisibleTab(function(imageUri){
            shots.push(imageUri);
        });
    }

    var shots=[];
    var points=[{x: 0, y: 0}, {x: 500, y: 500},{x: 1000, y: 1000}];

    for (var i=0; i<3; i++) scroll(points[i], capturetab);
    console.log(shots);
}

The issue is that shots[], the array of imageuris, contains some identical imageuris, like if capturevisibletab captures the same area several times.

In firefox that exact same code works just fine, with the exception that in firefox capturevisibletab returns promise and callback is not an obligatory.

Body:
Your scroll() function assumes that the tab is scrolled before callback() is invoked.

There is no such guarantee because the API is asynchronous.

I guess it works for you now only because your FF still runs in single-process mode.

Specify the callback in executeScript so that it's called back after the script is actually executed.

  function scroll(point, callback){
    chrome.tabs.executeScript({
      code: 'window.scrollTo('+JSON.stringify((point.x))+','+JSON.stringify(point.y)+')'
    }, callback);
  }


问:
cv2.imshow command doesn't work properly in opencv-python
I'm using opencv 2.4.2, python 2.7
The following simple code created a window of the correct name, but its content is just blank and doesn't show the image:

```<code>import cv2
img=cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('ImageWindow',img)
</code>```

does anyone knows about this issue?

答:
If you have not made this working, you better put

```<code>import cv2
img=cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('Window',img)
cv2.waitKey(0)
</code>```

into one file and run it.

Body:
I'm using opencv 2.4.2, python 2.7
The following simple code created a window of the correct name, but its content is just blank and doesn't show the image:

import cv2
img=cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('ImageWindow',img)

does anyone knows about this issue?

Body:
If you have not made this working, you better put

import cv2
img=cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('Window',img)
cv2.waitKey(0)

into one file and run it.


问:
SSL InsecurePlatform error when using Requests package
Im using Python 2.7.3 and Requests. I installed Requests via pip. I believe it's the latest version. I'm running on Debian Wheezy.

I've used Requests lots of times in the past and never faced this issue, but it seems that when making https requests with Requests I get an InsecurePlatform exception.

The error mentions urllib3, but I don't have that installed. I did install it to check if it resolved the error, but it didn't.

```<code>/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3
/util/ssl_.py:79: InsecurePlatformWarning: A true SSLContext object is not
available. This prevents urllib3 from configuring SSL appropriately and
may cause certain SSL connections to fail. For more information, see
https://urllib3.readthedocs.org/en/latest
/security.html#insecureplatformwarning.
</code>```

Any ideas as to why I'm getting this? I've checked the docs, as specified in the error message, but the docs are saying to import urllib3 and either disable the warning, or provide a certificate.

答:
Below is how it's working for me on Python 3.6:</p>

```<code>import requests
import urllib3

# Suppress InsecureRequestWarning: Unverified HTTPS
urllib3.disable_warnings()
</code>```

Body:
Im using Python 2.7.3 and Requests. I installed Requests via pip. I believe it's the latest version. I'm running on Debian Wheezy.

I've used Requests lots of times in the past and never faced this issue, but it seems that when making https requests with Requests I get an InsecurePlatform exception.

The error mentions urllib3, but I don't have that installed. I did install it to check if it resolved the error, but it didn't.

/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3
/util/ssl_.py:79: InsecurePlatformWarning: A true SSLContext object is not
available. This prevents urllib3 from configuring SSL appropriately and
may cause certain SSL connections to fail. For more information, see
https://urllib3.readthedocs.org/en/latest
/security.html#insecureplatformwarning.

Any ideas as to why I'm getting this? I've checked the docs, as specified in the error message, but the docs are saying to import urllib3 and either disable the warning, or provide a certificate.

Body:
Below is how it's working for me on Python 3.6:

import requests
import urllib3

# Suppress InsecureRequestWarning: Unverified HTTPS
urllib3.disable_warnings()


问:
Remove markup in tests
When I run tests which fail I get a huge output with a lot of markup hiding the error.

Example:

```<code>$ perl script/my_prove.pl t/2410-topinfo.t
t/2410-topinfo.t .. 1/?
#   Failed test '200 OK'
#   at t/2410-topinfo.t line 12.
#          got: '500'
#     expected: '200'

#   Failed test 'similar match for selector "h1"'
#   at t/2410-topinfo.t line 12.
#                   ''
#     doesn't match '(?^:Flatinfo\ Business\-Apartment\ Hietzing)'

#   Failed test 'content is similar'
#   at t/2410-topinfo.t line 12.
#                   '<!DOCTYPE html>
# <html>
#   <head>
#     <title>Server error (development mode)</title>
#     <meta http-equiv="Pragma" content="no-cache">
#     <meta http-equiv="Expires" content="-1">
#     <script src="/mojo/jquery/jquery.js"></script>
#     <script src="/mojo/prettify/run_prettify.js"></script>
#     <link href="/mojo/prettify/prettify-mojo-dark.css" rel="stylesheet">
#     <style>
#       a img { border: 0 }
#       body {
#
#   ........... lots of lines removed here ...........
#
#     <div id="wrapperlicious">
#         <div id="nothing" class="box spaced"></div>
#         <div id="showcase" class="box code spaced">
#           <pre id="error">Can't call method "name" on an undefined value at template extern/topinfo/show.html.ep line 2.
# ```
#
#    .... lots of lines follow here ............
```

<p>The error seems to be a single line: </p>

``` Can't call method "name" on an undefined value at template extern/topinfo/show.html.ep line 2
```

<p>The test-script producing this output is:</p>

```use Mojo::Base -strict;

use Test::More;
use Test::Mojo;

use FindBin;
require "$FindBin::Bin/../script/ba_db";
my $t = Test::Mojo->new( 'BaDb' );
$t->ua->max_redirects(1);

$t->get_ok('/info/penx2')
    ->status_is(200)
    ->text_like('h1' => qr/\QFlatinfo Business-Apartment Hietzing\E/)
    ->content_like( qr/\QSelected language: German\E/ )
    # ...
;
done_testing();
```

Is there a way to tell Mojolicious to respond without all this HTML-Markup so that I can see the error-mesage immediately?

答:
There are two things at play here.

The large debug output with the full page source is because the content_like method from Test::Mojo didn't find a match, and it's telling you in which string it was looking. That's a convenience method, but if the page is large, it's a lot of text. This might tell you that the test failed because the content was wrong. But in this specific case it didn't.

The real problem is that the test failed because you had a syntax error. You can already see that from the very first test.

```<code>$t->get_ok('/info/penx2')
    ->status_is(200)
</code>```

This test also failed. (It's a bit confusing for people who are used to Test::WWW::Mechanize because there get_ok will also check if the response was 200 OK).

```<code>#   Failed test '200 OK'
#   at t/2410-topinfo.t line 12.
#          got: '500'
#     expected: '200'
</code>```

The actual error message should be there without all that HTML markup somewhere else, because while it was doing the get_ok it would have encountered the error, which should have gone to the application log. In a unit-test, that probably is STDERR.

I don't know if you've not included it, or if it's omitted. The log should be there too I believe.

Getting back to the HTML and the actual question, the reason it's output is because Test::Mojo's content_like (and most other of its methods) uses Test::More under hood. It just dispatches to like from Test::More and passes along the page content. This in turn will always display the full string it was matching against.

In recent Test::More versions, it already uses Test2 under the hood. The relevant part that outputs the full string is here.

Unfortunately there is not much you can do about it. I'd focus on finding out why it doesn't show a proper log during the unit tests (possibly because you didn't run prove with -v), and maybe find a way to make errors come out in color, which would make it easier to read. There is a color logger for the Dancer2 framework (which I maintain), but I can't find one for Mojo there wasn't one for Mojo.

Now there is Mojo::Log::Colored, which can color individual log lines based on their log level.

```<code>use Mojo::Log::Colored;

# Log to STDERR
$app->log(
    Mojo::Log::Colored->new(

        # optionally set the colors
        colors => {
            debug => "bold bright_white",
            info  => "bold bright_blue",
            warn  => "bold green",
            error => "bold yellow",
            fatal => "bold yellow on_red",
        }
    )
);
</code>```

This will give you nice colorful output to the console. Here's an example script.

```<code>$ MOJO_LOG_LEVEL=debug perl -Mojo -MMojo::Log::Colored \
  -e 'a(
      "/" => sub {
          app->log->$_("hello world") for qw/debug info warn error fatal/;
          shift->render(text=>"ok");
      })->log( Mojo::Log::Colored->new )->start' \
  daemon
</code>```

And the output if called with $ curl localhost:3000.

Title: Remove markup in tests

Body:
When I run tests which fail I get a huge output with a lot of markup hiding the error.

Example:

$ perl script/my_prove.pl t/2410-topinfo.t
t/2410-topinfo.t .. 1/?
#   Failed test '200 OK'
#   at t/2410-topinfo.t line 12.
#          got: '500'
#     expected: '200'

#   Failed test 'similar match for selector "h1"'
#   at t/2410-topinfo.t line 12.
#                   ''
#     doesn't match '(?^:Flatinfo\ Business\-Apartment\ Hietzing)'

#   Failed test 'content is similar'
#   at t/2410-topinfo.t line 12.
#                   '<!DOCTYPE html>
#
#
#     <title>Server error (development mode)</title>
#     <meta http-equiv="Pragma" content="no-cache">
#     <meta http-equiv="Expires" content="-1">
#
#
#     <link href="/mojo/prettify/prettify-mojo-dark.css" rel="stylesheet">
#

Body:
There are two things at play here.

The large debug output with the full page source is because the content_like method from Test::Mojo didn't find a match, and it's telling you in which string it was looking. That's a convenience method, but if the page is large, it's a lot of text. This might tell you that the test failed because the content was wrong. But in this specific case it didn't.

The real problem is that the test failed because you had a syntax error. You can already see that from the very first test.

$t->get_ok('/info/penx2')
    ->status_is(200)

This test also failed. (It's a bit confusing for people who are used to Test::WWW::Mechanize because there get_ok will also check if the response was 200 OK).

#   Failed test '200 OK'
#   at t/2410-topinfo.t line 12.
#          got: '500'
#     expected: '200'

The actual error message should be there without all that HTML markup somewhere else, because while it was doing the get_ok it would have encountered the error, which should have gone to the application log. In a unit-test, that probably is STDERR.

I don't know if you've not included it, or if it's omitted. The log should be there too I believe.

Getting back to the HTML and the actual question, the reason it's output is because Test::Mojo's content_like (and most other of its methods) uses Test::More under hood. It just dispatches to like from Test::More and passes along the page content. This in turn will always display the full string it was matching against.

In recent Test::More versions, it already uses Test2 under the hood. The relevant part that outputs the full string is here.

Unfortunately there is not much you can do about it. I'd focus on finding out why it doesn't show a proper log during the unit tests (possibly because you didn't run prove with -v), and maybe find a way to make errors come out in color, which would make it easier to read. There is a color logger for the Dancer2 framework (which I maintain), but I can't find one for Mojo there wasn't one for Mojo.

Now there is Mojo::Log::Colored, which can color individual log lines based on their log level.

use Mojo::Log::Colored;

# Log to STDERR
$app->log(
    Mojo::Log::Colored->new(

        # optionally set the colors
        colors => {
            debug => "bold bright_white",
            info  => "bold bright_blue",
            warn  => "bold green",
            error => "bold yellow",
            fatal => "bold yellow on_red",
        }
    )
);

This will give you nice colorful output to the console. Here's an example script.

$ MOJO_LOG_LEVEL=debug perl -Mojo -MMojo::Log::Colored \
  -e 'a(
      "/" => sub {
          app->log->$_("hello world") for qw/debug info warn error fatal/;
          shift->render(text=>"ok");
      })->log( Mojo::Log::Colored->new )->start' \
  daemon

And the output if called with $ curl localhost:3000.


问:
Spring MVC LocalDate parameter has wrong format
I'm using Spring Boot 1.5.3, Spring Data REST, Spring JPA, Hibernate.
I'm working in UTC with java.time.* in the server, and my clients are supposed to send back dates in UTC too.
I customized a bit my REST configuration:

```<code>@Configuration
public class RestConfig extends RepositoryRestConfigurerAdapter {

@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
    return new Jackson2ObjectMapperBuilderCustomizer() {

        @Override
        public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {

            jacksonObjectMapperBuilder.serializers(InstantSerializer.INSTANCE);
            jacksonObjectMapperBuilder.serializers(new ZonedDateTimeSerializer(ISO_FIXED_FORMAT));
            jacksonObjectMapperBuilder
                    .serializers(new LocalDateSerializer(new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd").toFormatter()));
            jacksonObjectMapperBuilder.serializers(new LocalDateTimeSerializer(
                    new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").toFormatter()));
        }

    };
}
</code>```

}

I created a custom method in a repository:

```<code>@Transactional
@PreAuthorize("isAuthenticated()")
public interface DailyCodeRepository extends PagingAndSortingRepository<DailyCode, Long> {

    @Query("SELECT d FROM DailyCode d WHERE (:code IS NULL OR code=:code) AND (:from IS NULL OR date>=:from) AND (:to IS NULL OR date<=:to)")
    public Page<DailyCode> findAllWithParameter(@Param("code") @RequestParam(value = "code", required = false) String code,
            @Param("from") @RequestParam(value = "from", required = false) @DateTimeFormat(iso=ISO.DATE) LocalDate from,
            @Param("to") @RequestParam(value = "to", required = false) @DateTimeFormat(iso=ISO.DATE) LocalDate to, Pageable pageable);
}
</code>```

The first problem is that the method accept the ISO format only if I put the annotation @DateTimeFormat(iso=ISO.DATE), otherwise it picks the format of my locale (Italy). I want to set it globally as done for the response (see my Jackson2ObjectMapperBuilderCustomizer).

The second problem is that date parameters sent from the client are interpreted like 1 day before, so a request like this:

```<code>http://localhost:8080/api/v1/dailyCodes/search/findAllWithParameter?from=2017-07-07&to=2017-07-07
</code>```

causes this query on the database:

```<code>select dailycode0_.`id` as id1_7_, dailycode0_.`created_by` as created_2_7_, dailycode0_.`created_date` as created_3_7_, dailycode0_.`last_modified_by` as last_mod4_7_, dailycode0_.`last_modified_date` as last_mod5_7_, dailycode0_.`sid` as sid6_7_, dailycode0_.`version` as version7_7_, dailycode0_.`code` as code8_7_, dailycode0_.`date` as date9_7_ from `daily_code` dailycode0_ where (null is null or dailycode0_.`code`=null) and ('2017-07-06' is null or dailycode0_.`date`>='2017-07-06') and ('2017-07-06' is null or dailycode0_.`date`<='2017-07-06') limit 20
</code>```

So it queries 1 day before and it's wrong. I guess it's a timezone problem but I can't figure out how to solve that.

This is the relevant part of my properties file:

```<code>spring.mvc.date-format= `yyyy-MM-dd`
# REST
spring.data.rest.default-page-size= 20
spring.data.rest.base-path=/api/v1
spring.data.rest.enable-enum-translation=true

#Jackson

# to avoid an error loading lazy objects
spring.jackson.serialization.fail-on-empty-beans=false
spring.jackson.serialization.write-dates-as-timestamps=false
spring.jackson.mapper.infer-property-mutators=false
spring.jpa.properties.hibernate.jdbc.time_zone = UTC
</code>```

答:
You've several issues in your code:

The first problem is that the method accept the ISO format only

You need a OffsetDateTime (not ZonedDateTime, read this) and custom converter. Read this.

date parameters sent from the client are interpreted like 1 day before

Why? What time zone are you interpreting this date for? Your local time zone may be different from the server's which may be different from the client's.

Jackson2ObjectMapperBuilderCustomizer

What's this used for?

spring.mvc.date-format=yyyy-MM-dd

This shouldn't be necessary, and I don't think does anything for Spring data anyway.

Body:
I'm using Spring Boot 1.5.3, Spring Data REST, Spring JPA, Hibernate.
I'm working in UTC with java.time.* in the server, and my clients are supposed to send back dates in UTC too.
I customized a bit my REST configuration:

@Configuration
public class RestConfig extends RepositoryRestConfigurerAdapter {

@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
    return new Jackson2ObjectMapperBuilderCustomizer() {

        @Override
        public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {

            jacksonObjectMapperBuilder.serializers(InstantSerializer.INSTANCE);
            jacksonObjectMapperBuilder.serializers(new ZonedDateTimeSerializer(ISO_FIXED_FORMAT));
            jacksonObjectMapperBuilder
                    .serializers(new LocalDateSerializer(new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd").toFormatter()));
            jacksonObjectMapperBuilder.serializers(new LocalDateTimeSerializer(
                    new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").toFormatter()));
        }

    };
}

}

I created a custom method in a repository:

@Transactional
@PreAuthorize("isAuthenticated()")
public interface DailyCodeRepository extends PagingAndSortingRepository<DailyCode, Long> {

    @Query("SELECT d FROM DailyCode d WHERE (:code IS NULL OR code=:code) AND (:from IS NULL OR date>=:from) AND (:to IS NULL OR date<=:to)")
    public Page<DailyCode> findAllWithParameter(@Param("code") @RequestParam(value = "code", required = false) String code,
            @Param("from") @RequestParam(value = "from", required = false) @DateTimeFormat(iso=ISO.DATE) LocalDate from,
            @Param("to") @RequestParam(value = "to", required = false) @DateTimeFormat(iso=ISO.DATE) LocalDate to, Pageable pageable);
}

The first problem is that the method accept the ISO format only if I put the annotation @DateTimeFormat(iso=ISO.DATE), otherwise it picks the format of my locale (Italy). I want to set it globally as done for the response (see my Jackson2ObjectMapperBuilderCustomizer).

The second problem is that date parameters sent from the client are interpreted like 1 day before, so a request like this:

http://localhost:8080/api/v1/dailyCodes/search/findAllWithParameter?from=2017-07-07&to=2017-07-07

causes this query on the database:

select dailycode0_.`id` as id1_7_, dailycode0_.`created_by` as created_2_7_, dailycode0_.`created_date` as created_3_7_, dailycode0_.`last_modified_by` as last_mod4_7_, dailycode0_.`last_modified_date` as last_mod5_7_, dailycode0_.`sid` as sid6_7_, dailycode0_.`version` as version7_7_, dailycode0_.`code` as code8_7_, dailycode0_.`date` as date9_7_ from `daily_code` dailycode0_ where (null is null or dailycode0_.`code`=null) and ('2017-07-06' is null or dailycode0_.`date`>='2017-07-06') and ('2017-07-06' is null or dailycode0_.`date`<='2017-07-06') limit 20

So it queries 1 day before and it's wrong. I guess it's a timezone problem but I can't figure out how to solve that.

This is the relevant part of my properties file:

spring.mvc.date-format= `yyyy-MM-dd`
# REST
spring.data.rest.default-page-size= 20
spring.data.rest.base-path=/api/v1
spring.data.rest.enable-enum-translation=true

#Jackson

# to avoid an error loading lazy objects
spring.jackson.serialization.fail-on-empty-beans=false
spring.jackson.serialization.write-dates-as-timestamps=false
spring.jackson.mapper.infer-property-mutators=false
spring.jpa.properties.hibernate.jdbc.time_zone = UTC


问:
Database management for product release
In our company we are developing a product.

We are relying on the tfs to manage the release issues by using branching and merging.

We still have a problem with the SQL database on how to track changes and send them to the customer.

答:
We use LiquiBase:

Liquibase is an open source (Apache
  2.0 Licensed), database-independent library for tracking, managing and
  applying database changes.

ContentLicense: CC BY-SA 2.5

Title: Database management for product release


问:
Incorrrect Merge, Instead of merging A to B I merged B to A in GIT LAB
Instead of merging B (Branch) to A(Feature) I merged A(Feature) to B(Branch) in GIT LAB.
Here is a graphical representation of what I did.
I have this as below. With this the "Branch A2" merges into "feature B2" which is not what i intended.
ISSUE: Now if i continue development, the Branch that will have to continue on is "feature B2" instead of "Branch A2"

```<code>Branch          A ----A1------ A2 <-- last commit
                 \              \  (merge into feature)
Branch(feature)   B -- -B1- - -- B2 <-- feature now contains Branch "A2" edits.
</code>```

This is what I wanted. To merged "feature B2" into "Branch A2"; In this way when I continue my development it would be on the "Branch A2" and not "feature B2"

```<code>Branch(feature) B ----B1------ B2 <-- last feature commit
                 \              \  (merge into Branch)
Branch            A -- -A1- - -- A2 <-- Branch now contains "B2" feature edits.
</code>```

What is the most clean way of fixing this so I can get Scenario 2 and continue working on "A2" Branch branch instead of "B2" feature branch?
Function wise, they both achieve the same thing whether you merged A2->B2 or B2->A2!

One way comes to mind is that I can rename the Merged branch and call it Branch A2

答: You should be able to revert to the commit before the merge in your branch (see How to revert Git repository to a previous commit?) and then redo the merge in the correct direction.</p>

Body:
Instead of merging B (Branch) to A(Feature) I merged A(Feature) to B(Branch) in GIT LAB.
Here is a graphical representation of what I did.
I have this as below. With this the "Branch A2" merges into "feature B2" which is not what i intended.
ISSUE: Now if i continue development, the Branch that will have to continue on is "feature B2" instead of "Branch A2"

Branch          A ----A1------ A2 <-- last commit
                 \              \  (merge into feature)
Branch(feature)   B -- -B1- - -- B2 <-- feature now contains Branch "A2" edits.

This is what I wanted. To merged "feature B2" into "Branch A2"; In this way when I continue my development it would be on the "Branch A2" and not "feature B2"

Branch(feature) B ----B1------ B2 <-- last feature commit
                 \              \  (merge into Branch)
Branch            A -- -A1- - -- A2 <-- Branch now contains "B2" feature edits.

What is the most clean way of fixing this so I can get Scenario 2 and continue working on "A2" Branch branch instead of "B2" feature branch?
Function wise, they both achieve the same thing whether you merged A2->B2 or B2->A2!

One way comes to mind is that I can rename the Merged branch and call it Branch A2


问:
how to migrate from ionic3 to ionic2 and also from ionic2 back to ionic3
I want to know how to exchange between ionic 3 and 2 or 2 to 3 with keep same project

im use WINDOWS. in the  first time, I install

```<code>npm install -g ionic Cordova
</code>```

and for starting a new project i insert like following docs in ionicframework.com :

```<code>ionic start [myproject] blank
</code>```

and

```<code> cd [myproject]
 ionic serve
</code>```

i don't know what the version ionic was installed? is the latest version by default or what?
because of this article here :
https://www.joshmorony.com/using-http-to-fetch-remote-data-from-a-server-in-ionic-2/

tell should install v2 in the first time and then we want to move to 3 !!

and I want to know how can moving between the version 2>>3 or 3>>2 without any crash.
and I'm afraid if I'm using v3 by default and give something wrong while coding

plizzz someone explain carefully my issue

答:
what you can do is to use a node version manager or nvm for short, which would let you handle different versions of node. By having different versions of node you can have ionic 3 on node X.X version and ionic 2 in a different one.

since you are using windows you can use this one.

Body:
I want to know how to exchange between ionic 3 and 2 or 2 to 3 with keep same project

im use WINDOWS. in the  first time, I install

npm install -g ionic Cordova

and for starting a new project i insert like following docs in ionicframework.com :

ionic start [myproject] blank

and

 cd [myproject]
 ionic serve

i don't know what the version ionic was installed? is the latest version by default or what?
because of this article here :
https://www.joshmorony.com/using-http-to-fetch-remote-data-from-a-server-in-ionic-2/

tell should install v2 in the first time and then we want to move to 3 !!

and I want to know how can moving between the version 2>>3 or 3>>2 without any crash.
and I'm afraid if I'm using v3 by default and give something wrong while coding

plizzz someone explain carefully my issue


问:
Keras(theano) error while gpu
Already long time I try to understand with a problem. Please help me.

I'm trying to run the 'Keras' example from the standard example git lib (there).

If I use CPU, then everything will works fine; But, If I try to use GPU acceleration, it will crash WITHOUT catching any errors:

```<code># build the model: a single LSTM
print('Build model...')
print('   1')
model = Sequential()
print('   2')
model.add(LSTM(128, input_shape=(maxlen, len(chars))))
print('   3')
model.add(Dense(len(chars)))
print('   4')
model.add(Activation('softmax'))

print('   5')
optimizer = RMSprop(lr=0.01)

print('   Compilling')
model.compile(loss='categorical_crossentropy', optimizer=optimizer)
</code>```

I put some print() for better understand the place of error.
And what I get:

```<code>runfile('C:/Users/kostya/Desktop/temp/python/test.py', wdir='C:/Users/kostya/Desktop/temp/python/')
Using Theano backend.
Using cuDNN version 5110 on context None
Preallocating 1638/2048 Mb (0.800000) on cuda
Mapped name None to device cuda: GeForce GTX 650 (0000:01:00.0)
WARNING: Preallocating too much memory can prevent cudnn and cublas from working properly
DEVICE: cuda
corpus length: 206433
total chars: 79
nb sequences: 68798
Vectorization...
Build model...
   1
   2

Ядро остановилось, перезапуск *(It means: The Core has stopped, restarting)*
</code>```

I will take Similar error, if I run it througth standatr python console. (python.exe emergency stops)

I use: Win 10-64, Python 3.6.1, Anaconda with activated separate enviroment, CUDA 8.0, cuRNN 5.1, mkl 2017.0.3, numpy 1.13.0, theano 0.9.0, conda-forge.keras 2.0.2, m2w64-openblas 0.2.19, conda-forge.pygpu 0.6.8, VC 14.0 etc.

That's my .theanorc.txt configurational file. (I'm sure this can catch him. If I put the device = cpu - it works fine (but slowly))

```<code>[global]
floatX = float32
device = cuda
optimizer_including = cudnn

[nvcc]
flags=-LC:\Users\kostya\Anaconda3\envs\keras\libs
compiler_bindir=C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin

[cuda]
root = C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0

[dnn]
library_path = C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\lib\x64
include_path = C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\include

[gpuarray]
preallocate = 0.8
</code>```

答:
You trying to use gpuarray backend option (preallocate) with CUDA backend. From Theano doc:

This value allocates GPU memory ONLY when using (GpuArray Backend). For the old backend, please see config.lib.cnmem

Try replace in your Theano config

```<code>[gpuarray]
preallocate = 0.8
</code>```

with

```<code>[lib]
cnmem = 0.8
</code>```

Title: Keras(theano) error while gpu

Body:
Already long time I try to understand with a problem. Please help me.

I'm trying to run the 'Keras' example from the standard example git lib (there).

If I use CPU, then everything will works fine; But, If I try to use GPU acceleration, it will crash WITHOUT catching any errors:

# build the model: a single LSTM
print('Build model...')
print('   1')
model = Sequential()
print('   2')
model.add(LSTM(128, input_shape=(maxlen, len(chars))))
print('   3')
model.add(Dense(len(chars)))
print('   4')
model.add(Activation('softmax'))

print('   5')
optimizer = RMSprop(lr=0.01)

print('   Compilling')
model.compile(loss='categorical_crossentropy', optimizer=optimizer)

I put some print() for better understand the place of error.
And what I get:

runfile('C:/Users/kostya/Desktop/temp/python/test.py', wdir='C:/Users/kostya/Desktop/temp/python/')
Using Theano backend.
Using cuDNN version 5110 on context None
Preallocating 1638/2048 Mb (0.800000) on cuda
Mapped name None to device cuda: GeForce GTX 650 (0000:01:00.0)
WARNING: Preallocating too much memory can prevent cudnn and cublas from working properly
DEVICE: cuda
corpus length: 206433
total chars: 79
nb sequences: 68798
Vectorization...
Build model...
   1
   2

Ядро остановилось, перезапуск *(It means: The Core has stopped, restarting)*

I will take Similar error, if I run it througth standatr python console. (python.exe emergency stops)

I use: Win 10-64, Python 3.6.1, Anaconda with activated separate enviroment, CUDA 8.0, cuRNN 5.1, mkl 2017.0.3, numpy 1.13.0, theano 0.9.0, conda-forge.keras 2.0.2, m2w64-openblas 0.2.19, conda-forge.pygpu 0.6.8, VC 14.0 etc.

That's my .theanorc.txt configurational file. (I'm sure this can catch him. If I put the device = cpu - it works fine (but slowly))

[global]
floatX = float32
device = cuda
optimizer_including = cudnn

[nvcc]
flags=-LC:\Users\kostya\Anaconda3\envs\keras\libs
compiler_bindir=C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin

[cuda]
root = C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0

[dnn]
library_path = C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\lib\x64
include_path = C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\include

[gpuarray]
preallocate = 0.8

Body:
You trying to use gpuarray backend option (preallocate) with CUDA backend. From Theano doc:

This value allocates GPU memory ONLY when using (GpuArray Backend). For the old backend, please see config.lib.cnmem

Try replace in your Theano config

[gpuarray]
preallocate = 0.8

with

[lib]
cnmem = 0.8


问:
Get-AzureRmResource returns different data depending on how it was called
This just blew my mind.  I run these commands to access a particular resource and print out its location:

```<code>PS H:\> $hmm = Get-AzureRmResource -ResourceGroupName "RG_NAME" -ResourceName "R_NAME" -ResourceType "Microsoft.ServiceBus/namespaces"
PS H:\> $hmm.Location
East US 2
</code>```

But if I run these commands I get different data for the same field:

```<code>PS H:\> $hmm2 = Get-AzureRmResource | Where-Object {$_.ResourceName -match "R_NAME"}
PS H:\> $hmm2.Location
eastus2
</code>```

Before you ask, I only have one resource whose name is "R_NAME".

Why is the Azure API returning different values depending on how I try to access the data?  Is there some kind of conversion happening in the background on Azure that's normalizing the data or something?

答: No one except for the devs will be able to answer this question (why this happens exactly). But probably this happens because when you do a get against the subscription you are talking to an Azure Resource provider and when talking to a single resource you are talking to a servicebus provider. And their responses differ. This can happen. Microsoft is a huge company. things like this happen all the time.</p>

Body:
This just blew my mind.  I run these commands to access a particular resource and print out its location:

PS H:\> $hmm = Get-AzureRmResource -ResourceGroupName "RG_NAME" -ResourceName "R_NAME" -ResourceType "Microsoft.ServiceBus/namespaces"
PS H:\> $hmm.Location
East US 2

But if I run these commands I get different data for the same field:

PS H:\> $hmm2 = Get-AzureRmResource | Where-Object {$_.ResourceName -match "R_NAME"}
PS H:\> $hmm2.Location
eastus2

Before you ask, I only have one resource whose name is "R_NAME".

Why is the Azure API returning different values depending on how I try to access the data?  Is there some kind of conversion happening in the background on Azure that's normalizing the data or something?


问:
Invalid parameter number: parameter was not defined in {path}
Here is my query:

```<code>SELECT qa.id,
       qa.subject,
       qa.category cat,
       qa.keywords tags,
       qa.body_html,
       qa.amount,
       qa.author_id author,
       qa.visibility,
       qa.date_time,
       COALESCE(u.reputation, 'N') reputation,
       COALESCE(CONCAT(u.user_fname, ' ', u.user_lname), 'ناشناس') name,
       COALESCE(u.avatar, 'anonymous.png') avatar,

  (SELECT COALESCE(sum(vv.value),0)
   FROM votes vv
   WHERE qa.id = vv.post_id
     AND 15 = vv.table_code) AS total_votes,

  (SELECT COALESCE(sum(vt.total_viewed),0)
   FROM viewed_total vt
   WHERE qa.id = vt.post_id
     AND 15 = vt.table_code
   LIMIT 1) AS total_viewed
FROM qanda qa
INNER JOIN qanda_tags qt ON qt.qanda_id = qa.id
INNER JOIN tags ON tags.id = qt.tag_id
LEFT JOIN users u ON qa.author_id = u.id
AND qa.visibility = 1
WHERE qa.type = 0
  AND tags.name = :t
ORDER BY total_votes DESC,
         qa.id DESC
LIMIT :j,
      11;
</code>```

And this is print_r() the result of parameters' array: (which I pass it to the query as execute() argument)

```<code>Array ( [:t] => برچسب1 [:j] => 0 )
</code>```

And when I execute the query, it throws this error:

Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in C:\xampp\htdocs\myweb\others\questions.php:140 Stack trace: #0 C:\xampp\htdocs\myweb\others\questions.php(140): PDOStatement->execute(Array) #1 C:\xampp\htdocs\myweb\application\other.php(21): questions->index() #2 C:\xampp\htdocs\myweb\index.php(149): require_once('C:\xampp\htdocs...') #3 {main} thrown in C:\xampp\htdocs\myweb\others\questions.php on line 140

Can anybody find the problem? It's 1 hour I'm staring at it, and it seems fine to me.

答:
You might be running into problems with the way PDO emulates parameters.

See my answer here: Parametrized PDO query and `LIMIT` clause - not working

So you should either turn off emulated parameters:

```<code>$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
</code>```

Or else you MUST bind a PHP integer, and specify it as an integer:

```<code>$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
...
$stmt->bindValue('j', (int) $int, PDO::PARAM_INT);
</code>```

Body:
Here is my query:

SELECT qa.id,
       qa.subject,
       qa.category cat,
       qa.keywords tags,
       qa.body_html,
       qa.amount,
       qa.author_id author,
       qa.visibility,
       qa.date_time,
       COALESCE(u.reputation, 'N') reputation,
       COALESCE(CONCAT(u.user_fname, ' ', u.user_lname), 'ناشناس') name,
       COALESCE(u.avatar, 'anonymous.png') avatar,

  (SELECT COALESCE(sum(vv.value),0)
   FROM votes vv
   WHERE qa.id = vv.post_id
     AND 15 = vv.table_code) AS total_votes,

  (SELECT COALESCE(sum(vt.total_viewed),0)
   FROM viewed_total vt
   WHERE qa.id = vt.post_id
     AND 15 = vt.table_code
   LIMIT 1) AS total_viewed
FROM qanda qa
INNER JOIN qanda_tags qt ON qt.qanda_id = qa.id
INNER JOIN tags ON tags.id = qt.tag_id
LEFT JOIN users u ON qa.author_id = u.id
AND qa.visibility = 1
WHERE qa.type = 0
  AND tags.name = :t
ORDER BY total_votes DESC,
         qa.id DESC
LIMIT :j,
      11;

And this is print_r() the result of parameters' array: (which I pass it to the query as execute() argument)

Array ( [:t] => برچسب1 [:j] => 0 )

And when I execute the query, it throws this error:

Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in C:\xampp\htdocs\myweb\others\questions.php:140 Stack trace: #0 C:\xampp\htdocs\myweb\others\questions.php(140): PDOStatement->execute(Array) #1 C:\xampp\htdocs\myweb\application\other.php(21): questions->index() #2 C:\xampp\htdocs\myweb\index.php(149): require_once('C:\xampp\htdocs...') #3 {main} thrown in C:\xampp\htdocs\myweb\others\questions.php on line 140

Can anybody find the problem? It's 1 hour I'm staring at it, and it seems fine to me.

Body:
You might be running into problems with the way PDO emulates parameters.

See my answer here: Parametrized PDO query and `LIMIT` clause - not working

So you should either turn off emulated parameters:

$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

Or else you MUST bind a PHP integer, and specify it as an integer:

$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
...
$stmt->bindValue('j', (int) $int, PDO::PARAM_INT);


问:
Delete line from text file if line contains one of few specified strings Python
I presently have code that deletes all lines from a text file that contain one specific string. Here it is:

```<code>import os
with open(r"oldfile") as f, open(r"workfile", "w") as working:
    for line in f:
       if "string1" not in line:
           working.write(line)
os.remove(r"oldfile")
os.rename(r"workfile", r"oldfile")
</code>```

My question is: how can I include other strings? In other words, I want to tell the script that if a line contains "string1" or some other string "string2", then delete that line. I know I could just repeat the code I put above for every such string, but I'm certain there's some shorter and more efficient way to write that.

Many thanks in advance!

答:
```<code>if "string1" in line or "string2" in line:
</code>```

This should work I think

Body:
I presently have code that deletes all lines from a text file that contain one specific string. Here it is:

import os
with open(r"oldfile") as f, open(r"workfile", "w") as working:
    for line in f:
       if "string1" not in line:
           working.write(line)
os.remove(r"oldfile")
os.rename(r"workfile", r"oldfile")

My question is: how can I include other strings? In other words, I want to tell the script that if a line contains "string1" or some other string "string2", then delete that line. I know I could just repeat the code I put above for every such string, but I'm certain there's some shorter and more efficient way to write that.

Many thanks in advance!

Body:
if "string1" in line or "string2" in line:

This should work I think


问:
Jquery hack to change video for safari and other browsers
I am adding a video in my website but its not working on safari. I am using 'webm' video format. and i need to put 'mov' video format in safari.

Please suggest a hack in JQuery so that when safari opens, then 'mov' video is played and for other browsers 'webm' video is played.

答:
The HTML5 <video> tag accepts multiple <source> tags. Browsers will play the first one they recognize. All you should need is:

```<code><video autoplay loop muted playsinline="" preload="auto" id="newVideo">
    <source src="assets/vid/FinalLandingVideo.webm" type="video/webm"></source>
    <source src="assets/vid/FinalLandingVideo.mov" type="video/mov"></source>
</video>
</code>```

Body:
The HTML5 <video> tag accepts multiple <source> tags. Browsers will play the first one they recognize. All you should need is:

<video autoplay loop muted playsinline="" preload="auto" id="newVideo">
    <source src="assets/vid/FinalLandingVideo.webm" type="video/webm"></source>
    <source src="assets/vid/FinalLandingVideo.mov" type="video/mov"></source>
</video>


问:
Alter hive table add or drop column
I have orc table in hive I want to drop column from this table

```<code>ALTER TABLE table_name drop  col_name;
</code>```

but I am getting the following exception

Error occurred executing hive query: OK FAILED: ParseException line 1:35 mismatched input 'user_id1' expecting PARTITION near 'drop' in drop partition statement

Can any one help me or provide any idea to do this? Note, I am using hive 0.14

答:
ALTER TABLE is not yet supported for non-native tables; i.e. what you get with CREATE TABLE when a STORED BY clause is specified.

check this https://cwiki.apache.org/confluence/display/Hive/StorageHandlers

Title: Alter hive table add or drop column

Body:
I have orc table in hive I want to drop column from this table

ALTER TABLE table_name drop  col_name;

but I am getting the following exception

Error occurred executing hive query: OK FAILED: ParseException line 1:35 mismatched input 'user_id1' expecting PARTITION near 'drop' in drop partition statement

Can any one help me or provide any idea to do this? Note, I am using hive 0.14


问:
Find pairs of files in one directory with a specific pattern
I need to find pairs of files with a specific pattern in one directory:

HU_IP_number_something.bam & HU_inp_number_something.bam
  NOC_IP_number_something.bam & NOC_inp_number_something.bam

Numbers are 1...N for each pair

I have a solution but it works only for one set of files HU_* or NOC_* in one directory.
How can I improve it to find pairs, when both HU_* and NOC_* are in one directory?

```<code>for ip in *IP*.bam
   do
        num=$(echo $ip | sed 's/[^0-9]//g')
        input=$(find -name *_inp_${num}*.bam)
        echo ip sample: $ip
        echo input sample: $input
   done
</code>```

Examples of files in one directory:

```<code>HU_inp_1-sorted.bam
HU_IP_1-sorted.bam
NOC_inp_1-sorted.bam
NOC_IP_1-sorted.bam
</code>```

for 1,2,3,...N

答:
Do you only want to match HU to HU and NOC to NOC? If so:

If you add a line

```<code>pre=$(echo $ip | awk -F "_" '{print $1}')
</code>```

then change you input to

```<code>input=$(find -name $pre_inp_${num}*.bam)
</code>```

Body:
I need to find pairs of files with a specific pattern in one directory:

HU_IP_number_something.bam & HU_inp_number_something.bam
  NOC_IP_number_something.bam & NOC_inp_number_something.bam

Numbers are 1...N for each pair

I have a solution but it works only for one set of files HU_* or NOC_* in one directory.
How can I improve it to find pairs, when both HU_* and NOC_* are in one directory?

for ip in *IP*.bam
   do
        num=$(echo $ip | sed 's/[^0-9]//g')
        input=$(find -name *_inp_${num}*.bam)
        echo ip sample: $ip
        echo input sample: $input
   done

Examples of files in one directory:

HU_inp_1-sorted.bam
HU_IP_1-sorted.bam
NOC_inp_1-sorted.bam
NOC_IP_1-sorted.bam

for 1,2,3,...N

Body:
Do you only want to match HU to HU and NOC to NOC? If so:

If you add a line

pre=$(echo $ip | awk -F "_" '{print $1}')

then change you input to

input=$(find -name $pre_inp_${num}*.bam)


问:
Getting error "AMQ8101: WebSphere MQ error (10806228) has occurred" when trying to start the command server in MQ
I'm Getting error AMQ8101: WebSphere MQ error (10806228) has occurred when trying to start the command server in MQ.

The MQ version which we are using is 7.1.0.6 and the environment is SunOS.

Please need your suggestions.

Below is the FDC file created:

```<code>+-----------------------------------------------------------------------------+
|                                                                             |
| WebSphere MQ First Failure Symptom Report                                   |
| =========================================                                   |
|                                                                             |
| Date/Time         :- Sun July 09 2017 15:15:37 MEST                         |
| UTC Time          :- 1499606137.840536                                      |
| UTC Time Offset   :- 120 (MET)                                              |
| Host Name         :- abcd                                             |
| Operating System  :- SunOS 5.10                                             |
| PIDS              :- 5724H7223                                              |
| LVLS              :- 7.1.0.6                                                |
| Product Long Name :- WebSphere MQ for Solaris (SPARC platform)              |
| Vendor            :- IBM                                                    |
| Installation Path :- /opt/mqm                                               |
| Installation Name :- Installation1    (1)                                   |
| Probe Id          :- ZT160001                                               |
| Application Name  :- MQM                                                    |
| Component         :- zusStartManager                                        |
| SCCS Info         :- lib/zu/amqzupt0.c, 1.54.1.2                            |
| Line Number       :- 1887                                                   |
| Build Date        :- Nov 14 2014                                            |
| CMVC level        :- p710-006-141112                                        |
| Build Type        :- IKAP - (Production)                                    |
| Effective UserID  :- 325 (mqm)                                              |
| Real UserID       :- 0 (root)                                               |
| ProjectID         :- 0                                                      |
| Program Name      :- strmqcsv                                               |
| Arguments         :- QM.XYZ.                                             |
| Addressing mode   :- 64-bit                                                 |
| LANG              :-                                                        |
| Process           :- 9398                                                   |
| Thread            :- 1                                                      |
| QueueManager      :- QM.XYZ                                             |
| UserApp           :- FALSE                                                  |
| ConnId(1) IPCC    :- 280898                                                 |
| ConnId(3) QM-P    :- 72653                                                  |
| Last HQC          :- 3.0.0-18240                                            |
| Last HSHMEMB      :- 1.0.0-4454576                                          |
| Major Errorcode   :- xecX_W_DAEMON_UNAVAILABLE                              |
| Minor Errorcode   :- OK                                                     |
| Probe Type        :- INCORROUT                                              |
| Probe Severity    :- 3                                                      |
| Probe Description :- AMQ6125: An internal WebSphere MQ error has occurred.  |
| FDCSequenceNumber :- 0                                                      |
| Arith1            :- 9495 (0x2517)                                          |
| Arith2            :- 50 (0x32)                                              |
| Comment1          :- Timed-out waiting for process manager to start.        |
|                                                                             |
+-----------------------------------------------------------------------------+
</code>```

答:
I'll start off by mentioning that IBM MQ v7.1 went out of support on April 30th 2017.  I would recommend that you move to a supported level of IBM MQ.  Keep in mind that IBM MQ v7.5 goes out of support on April 30th 2018.  Dates have not been announced for v8 or v9 yet, but IBM commits to at least 5 years of support which would give them support until at least June 2019 for v8 and June 2021 for v9.

The IBM MQ Technote "Common WebSphere MQ messages and most likely causes
" indicates a FDC may be created in /var/mqm/errors when a AMQ8101 is returned.  If a FDC is created can you please edit your question and add the top portion of the FDC file?

If you run mqrc against that error code as a hex error code it comes back with the following:

```<code>$ mqrc 0x10806228

 276849192  0x10806228  xecX_W_DAEMON_UNAVAILABLE
</code>```

IBM has stated to me in past PMRs that IBM MQ "... traditionally dumps out the hex value for return codes that it does not know about.  When this happens then it normally means we have hit an error path that we didn't expect and so we should try to fix this by adding a new message."

In APAR IT16270 they described a different unexpected error being returned as "a coding error resulted in an internal undocumented error code ... being returned to the application."

Based on this if it reproducible in a supported version of IBM MQ or if you have a extended support contract for v7.1 I would suggest opening a PMR with IBM to troubleshoot the issue.

UPDATE 2017-07-10

Based on the FDC indicating Timed-out waiting for process manager to start and further information from the OP that a restart of the queue manager solved the problem, I believe the amqzmur0 process was hung and not responding, this is the "Restartable process manager". Restarting the queue manager would have restarted this process.

Body:
I'm Getting error AMQ8101: WebSphere MQ error (10806228) has occurred when trying to start the command server in MQ.

The MQ version which we are using is 7.1.0.6 and the environment is SunOS.

Please need your suggestions.

Below is the FDC file created:

+-----------------------------------------------------------------------------+
|                                                                             |
| WebSphere MQ First Failure Symptom Report                                   |
| =========================================                                   |
|                                                                             |
| Date/Time         :- Sun July 09 2017 15:15:37 MEST                         |
| UTC Time          :- 1499606137.840536                                      |
| UTC Time Offset   :- 120 (MET)                                              |
| Host Name         :- abcd                                             |
| Operating System  :- SunOS 5.10                                             |
| PIDS              :- 5724H7223                                              |
| LVLS              :- 7.1.0.6                                                |
| Product Long Name :- WebSphere MQ for Solaris (SPARC platform)              |
| Vendor            :- IBM                                                    |
| Installation Path :- /opt/mqm                                               |
| Installation Name :- Installation1    (1)                                   |
| Probe Id          :- ZT160001                                               |
| Application Name  :- MQM                                                    |
| Component         :- zusStartManager                                        |
| SCCS Info         :- lib/zu/amqzupt0.c, 1.54.1.2                            |
| Line Number       :- 1887                                                   |
| Build Date        :- Nov 14 2014                                            |
| CMVC level        :- p710-006-141112                                        |
| Build Type        :- IKAP - (Production)                                    |
| Effective UserID  :- 325 (mqm)                                              |
| Real UserID       :- 0 (root)                                               |
| ProjectID         :- 0                                                      |
| Program Name      :- strmqcsv                                               |
| Arguments         :- QM.XYZ.                                             |
| Addressing mode   :- 64-bit                                                 |
| LANG              :-                                                        |
| Process           :- 9398                                                   |
| Thread            :- 1                                                      |
| QueueManager      :- QM.XYZ                                             |
| UserApp           :- FALSE                                                  |
| ConnId(1) IPCC    :- 280898                                                 |
| ConnId(3) QM-P    :- 72653                                                  |
| Last HQC          :- 3.0.0-18240                                            |
| Last HSHMEMB      :- 1.0.0-4454576                                          |
| Major Errorcode   :- xecX_W_DAEMON_UNAVAILABLE                              |
| Minor Errorcode   :- OK                                                     |
| Probe Type        :- INCORROUT                                              |
| Probe Severity    :- 3                                                      |
| Probe Description :- AMQ6125: An internal WebSphere MQ error has occurred.  |
| FDCSequenceNumber :- 0                                                      |
| Arith1            :- 9495 (0x2517)                                          |
| Arith2            :- 50 (0x32)                                              |
| Comment1          :- Timed-out waiting for process manager to start.        |
|                                                                             |
+-----------------------------------------------------------------------------+

Body:
I'll start off by mentioning that IBM MQ v7.1 went out of support on April 30th 2017.  I would recommend that you move to a supported level of IBM MQ.  Keep in mind that IBM MQ v7.5 goes out of support on April 30th 2018.  Dates have not been announced for v8 or v9 yet, but IBM commits to at least 5 years of support which would give them support until at least June 2019 for v8 and June 2021 for v9.

The IBM MQ Technote "Common WebSphere MQ messages and most likely causes
" indicates a FDC may be created in /var/mqm/errors when a AMQ8101 is returned.  If a FDC is created can you please edit your question and add the top portion of the FDC file?

If you run mqrc against that error code as a hex error code it comes back with the following:

$ mqrc 0x10806228

 276849192  0x10806228  xecX_W_DAEMON_UNAVAILABLE

IBM has stated to me in past PMRs that IBM MQ "... traditionally dumps out the hex value for return codes that it does not know about.  When this happens then it normally means we have hit an error path that we didn't expect and so we should try to fix this by adding a new message."

In APAR IT16270 they described a different unexpected error being returned as "a coding error resulted in an internal undocumented error code ... being returned to the application."

Based on this if it reproducible in a supported version of IBM MQ or if you have a extended support contract for v7.1 I would suggest opening a PMR with IBM to troubleshoot the issue.

UPDATE 2017-07-10

Based on the FDC indicating Timed-out waiting for process manager to start and further information from the OP that a restart of the queue manager solved the problem, I believe the amqzmur0 process was hung and not responding, this is the "Restartable process manager". Restarting the queue manager would have restarted this process.


答:
might be good to have a function</p>

```<code>def contains(list_of_strings_to_check,line):
  for string in list_of_strings_to_check:
    if string in line:
      return False
  return True

list_of_strings = ["string1","string2",...]
...
for line in f:
       if contains(list_of_strings,line):
</code>```

Title: Delete line from text file if line contains one of few specified strings Python

Body:
might be good to have a function

def contains(list_of_strings_to_check,line):
  for string in list_of_strings_to_check:
    if string in line:
      return False
  return True

list_of_strings = ["string1","string2",...]
...
for line in f:
       if contains(list_of_strings,line):