问:
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!

答:
First, you need to fully qualify all range references (see the dots below) otherwise they may refer to different sheets which will cause an error. Eg

```<code>With Backup.Sheets(ShtNm)
  .Range(.Range("N2"), .Range("N2").End(xlDown)).Copy
End With
</code>```

Second, what is the Values property? Your final formulation looks to me ok as long as you declare TotPrm as Variant.

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:
First, you need to fully qualify all range references (see the dots below) otherwise they may refer to different sheets which will cause an error. Eg

With Backup.Sheets(ShtNm)
  .Range(.Range("N2"), .Range("N2").End(xlDown)).Copy
End With

Second, what is the Values property? Your final formulation looks to me ok as long as you declare TotPrm as Variant.


来源: stackexchange

问:
casperjs capturing a "loading.gif" on ajax call
I use casperjs 1.1 (phantom 1.9.8) for loggin a website.

After login, there's the spinning throbber and I have:

```<code><div id=throbber style='display: block'></div>
<div id=main style='display: none'></div>
</code>```

Some dynamic content is loaded in the main div, so after loading:

```<code><div id=throbber style='display: none'></div>
<div id=main style='display: block'>some content</div>
</code>```

I tried to get a screenshot of the loaded content, since I need to perform clicks and operations, but I always get the throbber picture. I tried to wait 30 seconds, to waitforselector, waitfor document.getElementById('throbber').style.display == 'none' but without luck...

I use the alwex/php-casperjs wrapper (with some handmade additions) so my last try looks like this:

```<code>$casper->click('button[type="submit"]');
$casper->waitFor("document.getElementById('throbber').style.display == 'none'"); //implicit 5000 timeout
$casper->capture($screenshot_large, time().'.png');
</code>```

This particular try returns "'null' is not an object (evaluating 'document.getElementById('throbber').style')" but I'm opened to any alternative.

Thank you for any suggestion or alternative.

答:
casperjs demonstrated to be unreliable with such webpages.

A different solution based on Selenium perfectly worked.

ContentLicense: CC BY-SA 3.0

Body:
I use casperjs 1.1 (phantom 1.9.8) for loggin a website.

After login, there's the spinning throbber and I have:

Some dynamic content is loaded in the main div, so after loading:

some content

I tried to get a screenshot of the loaded content, since I need to perform clicks and operations, but I always get the throbber picture. I tried to wait 30 seconds, to waitforselector, waitfor document.getElementById('throbber').style.display == 'none' but without luck...

I use the alwex/php-casperjs wrapper (with some handmade additions) so my last try looks like this:

$casper->click('button[type="submit"]');
$casper->waitFor("document.getElementById('throbber').style.display == 'none'"); //implicit 5000 timeout
$casper->capture($screenshot_large, time().'.png');

This particular try returns "'null' is not an object (evaluating 'document.getElementById('throbber').style')" but I'm opened to any alternative.

Thank you for any suggestion or alternative.


问:
Finding intersection of sets in Vertica
I'm trying to sort out how to find the intersection of a pair of sets in Vertica (and a better way to do it).

I have 2 sets the first set is larger and stored in a single column table:

```<code>San Francisco
New York
Chicago
London
Rome
</code>```

The second set is stored as a delimited string in a Varchar field and can include items not in set 1 each set is a single string entry per row

```<code>San Francisco,Chicago,Tampa
Tampa,New Orleans,Miami
</code>```

What I need to be able to do is efficiently choose the members of the second set that are in the first set and then get the intersection of the two sets for further processing so for the second set I need it to return:

```<code>{San Francisco,Chicago}
{}
</code>```

So I need to be able to go through the table containing the set 2s and get that information then do something else for each instance of an intersection with the row that contains it.

Suggestions, please!

答:
I get as far as generating a tabular output containing what you are looking for. Exporting that in JSON format, as you seem to expect, is, in my eyes, the front end's job, not the database's.

Having said that, see here:

```<code>-- input 1: one city per column
WITH city(city) AS (
          SELECT 'San Francisco'
UNION ALL SELECT 'New York'
UNION ALL SELECT 'Chicago'
UNION ALL SELECT 'London'
UNION ALL SELECT 'Rome'
)
,
-- input 2: many cities per column
cities(cities) AS (
          SELECT 'San Francisco,Chicago,Tampa'
UNION ALL SELECT 'Tampa,New Orleans,Miami'
)
,
-- end of input. Start "real" WITH clause here.
i(i) AS ( -- index for SPLIT_PART()
          SELECT  1
UNION ALL SELECT  2
UNION ALL SELECT  3
UNION ALL SELECT  4
UNION ALL SELECT  5
UNION ALL SELECT  6
UNION ALL SELECT  7
UNION ALL SELECT  8
UNION ALL SELECT  9
UNION ALL SELECT 10
)
,
-- verticalise all those side-by-side cities, using SPLIT_PART()
-- and the index table above
pivot_cities AS (
  SELECT DISTINCT
    SPLIT_PART(cities,',',i) AS city
  FROM cities CROSS JOIN i
)
-- INNER JOIN input 1 with the distinct verticalised cities of input 2
SELECT
  city.city
FROM city
JOIN pivot_cities USING(city)
;

-- result:
city
-------------
Chicago
San Francisco
</code>```

Title: Finding intersection of sets in Vertica

Body:
I'm trying to sort out how to find the intersection of a pair of sets in Vertica (and a better way to do it).

I have 2 sets the first set is larger and stored in a single column table:

San Francisco
New York
Chicago
London
Rome

The second set is stored as a delimited string in a Varchar field and can include items not in set 1 each set is a single string entry per row

San Francisco,Chicago,Tampa
Tampa,New Orleans,Miami

What I need to be able to do is efficiently choose the members of the second set that are in the first set and then get the intersection of the two sets for further processing so for the second set I need it to return:

{San Francisco,Chicago}
{}

So I need to be able to go through the table containing the set 2s and get that information then do something else for each instance of an intersection with the row that contains it.

Suggestions, please!

Body:
I get as far as generating a tabular output containing what you are looking for. Exporting that in JSON format, as you seem to expect, is, in my eyes, the front end's job, not the database's.

Having said that, see here:

-- input 1: one city per column
WITH city(city) AS (
          SELECT 'San Francisco'
UNION ALL SELECT 'New York'
UNION ALL SELECT 'Chicago'
UNION ALL SELECT 'London'
UNION ALL SELECT 'Rome'
)
,
-- input 2: many cities per column
cities(cities) AS (
          SELECT 'San Francisco,Chicago,Tampa'
UNION ALL SELECT 'Tampa,New Orleans,Miami'
)
,
-- end of input. Start "real" WITH clause here.
i(i) AS ( -- index for SPLIT_PART()
          SELECT  1
UNION ALL SELECT  2
UNION ALL SELECT  3
UNION ALL SELECT  4
UNION ALL SELECT  5
UNION ALL SELECT  6
UNION ALL SELECT  7
UNION ALL SELECT  8
UNION ALL SELECT  9
UNION ALL SELECT 10
)
,
-- verticalise all those side-by-side cities, using SPLIT_PART()
-- and the index table above
pivot_cities AS (
  SELECT DISTINCT
    SPLIT_PART(cities,',',i) AS city
  FROM cities CROSS JOIN i
)
-- INNER JOIN input 1 with the distinct verticalised cities of input 2
SELECT
  city.city
FROM city
JOIN pivot_cities USING(city)
;

-- result:
city
-------------
Chicago
San Francisco


问:
Obtaining the number of comments of a list of youtube videos
I have been coding a simple python script for obtaining number of views and number of comments of a list of videos. Using csv, I have converted a tab-separated table into a list of lists, and then I tried to obtain both elements. Inspecting number of views, the element is "div", {"class":"watch-view-count"}. It works as intended

```<code>r = requests.get(list_youtube_reading[n][0]) # it retrieves each video URL from a csv
soup = BeautifulSoup(r.text)
for element in soup.findAll("div", {"class":"watch-view-count"}):
    patternviews = re.compile('^(.*?) .*')
    scissorviews = patternviews.match(element.text.encode("utf-8"))
    views = re.sub('\.','', tijeraviews.group(1))
</code>```

However, element for number of comments is

    Comments
    " • 6"

When I tried to obtain it, with

```<code>for element in soup.findAll("h2", {"class":"comment-section-header-renderer"}):
    comments = element.text.encode("utf-8")
    print comments
</code>```

nothing happens, and actually soupdoesn't contain any
 tag

What can I do in order to retrieve number of comments? I tried to use youtube v3 data API, but for no avail

thanks in advance

答:
It appears the comments section is loaded in a separate ajax request to a URL like this:

https://www.youtube.com/watch_fragments2_ajax?v=zlYDDLCorNw&tr=time&distiller=1&ctoken=EhYSC3psWURETENvck53wAEAyAEA4AEBGAY%253D&frags=comments&spf=load

That returns some json like this:

```<code>{
  "name": "other",
  "foot": "<script>...</script>",
  "body": {
    "watch-discussion": " ... <h2 class=\"comment-section-header-renderer\" tabindex=\"0\">\n<b>Comments</b> • 2<span class=\"alternate-content-link\"> ..."
  }
}
</code>```

In that json is where you'll find the HTML section showing the comment count (in body.watch-discussion).

Body:
I have been coding a simple python script for obtaining number of views and number of comments of a list of videos. Using csv, I have converted a tab-separated table into a list of lists, and then I tried to obtain both elements. Inspecting number of views, the element is "div", {"class":"watch-view-count"}. It works as intended

r = requests.get(list_youtube_reading[n][0]) # it retrieves each video URL from a csv
soup = BeautifulSoup(r.text)
for element in soup.findAll("div", {"class":"watch-view-count"}):
    patternviews = re.compile('^(.*?) .*')
    scissorviews = patternviews.match(element.text.encode("utf-8"))
    views = re.sub('\.','', tijeraviews.group(1))

However, element for number of comments is

    Comments
    " • 6"

When I tried to obtain it, with

for element in soup.findAll("h2", {"class":"comment-section-header-renderer"}):
    comments = element.text.encode("utf-8")
    print comments

nothing happens, and actually soupdoesn't contain any
 tag

What can I do in order to retrieve number of comments? I tried to use youtube v3 data API, but for no avail

thanks in advance

Body:
It appears the comments section is loaded in a separate ajax request to a URL like this:

https://www.youtube.com/watch_fragments2_ajax?v=zlYDDLCorNw&tr=time&distiller=1&ctoken=EhYSC3psWURETENvck53wAEAyAEA4AEBGAY%253D&frags=comments&spf=load

That returns some json like this:

{
  "name": "other",
  "foot": "<script>...</script>",
  "body": {
    "watch-discussion": " ... <h2 class=\"comment-section-header-renderer\" tabindex=\"0\">\n<b>Comments</b> • 2<span class=\"alternate-content-link\"> ..."
  }
}

In that json is where you'll find the HTML section showing the comment count (in body.watch-discussion).


问:
What tools are built using themselves?
I am curious about what tools are used to build the next version of themselves.

For example, Delphi has long claimed that "Delphi is written in Delphi".

I assume Visual Studio is written using Visual Studio.

What are some other examples of tools that written in themselves?

答:
For the AmigaOS there was a third party Basic interpreter (don't remember the name) for which you could later buy a compiler. The compiler was delivered as source, so you had to use the interpreter to run the compiler to compile itself...

To cite Kent Beck:

...it may seem a bit like performing brain surgery on yourself.

OwnerDisplayName: kogus

ContentLicense: CC BY-SA 2.5

Title: What tools are built using themselves?

LastEditorDisplayName: kogus

OwnerDisplayName: EricSchaefer


问:
After Adding "readonly" attribute on text box not able to remove it in one event
Steps to repro

USE Internet Explorer

Check unlimited check box

Click on text box (It will remove tick/check from check box)

Try to enter text in text box

We cannot enter in the text box

4. Click again on the text box. Now we will be able to enter text in the text box

We tried by

1. Making attribute readOnly to flase i.e.  $('#myinput').attr('readOnly', false);

2. Calling $('#myinput').click();

Below is the HTML code

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Make input read only</title>
    <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.4.min.js"></script>
</head>
<body>
    <input id="myinput" type="text" />
    <input id="mycheck" type="checkbox" />
    <script type="text/javascript">
        /*oncheck box click*/
        $('#mycheck').click(function () {
            if ($(this).attr('checked')) {
                $('#myinput').attr('readOnly', 'readOnly');
            }
            else {
                $('#myinput').removeAttr('readOnly');
                /* also tried
                 * $('#myinput').attr('readOnly', false);
                 * $('#myinput').attr('readOnly', '');
                 */
            }
        });
        /*on text box click*/
        $('#myinput').click(function () {
            $('#mycheck').removeAttr('checked');
            $('#myinput').removeAttr('readOnly');
            /* also tried
             * $('#myinput').attr('readOnly', false);
             * $('#myinput').attr('readOnly', '');
             */
        });
    </script>
</body>
</html>
</code>```

Live copy

答:
I had this same issue, and reported it on stackoverflow as well, one sec while I find it...

Edit: Found it.

If you read my post, it also explains what is happening. In fact, the textbox actually got unlocked (unlike what Tyde tried). The problem relates to focus/selection.

OwnerDisplayName: Sreedhar K

LastEditorDisplayName: Sreedhar K

Body:
Steps to repro

USE Internet Explorer

Check unlimited check box

Click on text box (It will remove tick/check from check box)

Try to enter text in text box

We cannot enter in the text box

4. Click again on the text box. Now we will be able to enter text in the text box

We tried by

1. Making attribute readOnly to flase i.e.  $('#myinput').attr('readOnly', false);

2. Calling $('#myinput').click();

Below is the HTML code

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

    <title>Make input read only</title>

    <input id="myinput" type="text" />
    <input id="mycheck" type="checkbox" />

Live copy


问:
How to decrypt a file using gpg without knowing its type before encrypting
I know how to decrypt a file:

gpg --passphrase mySecretPass -o /home/me/dummy.xml -d /home/me/dummy.gpg

but in my case this dummy.gpg can be xml or zip before encryption.

How could I save the output with the proper extension?

答:
You don't need to know the extension before decrypting. You can run:

gpg --passphrase mySecretPass -o /home/me/dummy -d /home/me/dummy.gpg

And then run:
file /home/me/dummy

The file command will return the file type based on the header.
You can also use mimetype


问:
How to remove Warning "This application was created by another user, not by Google" in Google Apps for Education
We set up a Google Apps Script-based Intranet in our organization, which benefits from Google Apps for Education. We've been using for months:

doGet()

HtmlService.createTemplate(...)

Publish > Deploy as Web App and setting:

"Execute the app as:" admin@ourdomain.com

"Who has access to the app:" Any member of ourdomain.com

Everything worked ok up to now.

However today (July 7th. 2017) the HTML pages to be shown to the intranet users include an inconvenient Warning added by Google at the top claiming that This application was created by another user, not by Google., which is really annoying. I understand that this warning must be shown when the Script is created by an unkown users. But in my case, I (the admin) is offering the Script to the users of my organization.

The conclusion in other past threads is that going Google Business or Education everything gets fixed. Unfortunately, it's not true anymore.

Does anybody know how to avoid such warning in Google Apps Script for the users of our domain that run our own coded scripts?

答:
Same thing has been happening to us.  We have a G Suite for Nonprofit account (formerly Business) and have published webapps for several years via this account without the warning showing up.  Users began telling me yesterday July 6 2017 that the warning now appears across all our webapps.

I just created a test webapp where "Execute the app as" is set to an admin of our account and "Who has access to the app" is set to "Anyone, even anonymous".  As you can see https://script.google.com/macros/s/AKfycbxrKgPol_-eEskKzqRzN4WAMj-NiPm7iFavjZu-_vWtTJPyAEkK/exec does display the warning.

Something I just noticed, the generated webapp script's url now starts with script.google.com/macros/s/ whereas before it would have included our organization name (e.g. script.google.com/a/macros/rchsks.org/s/).  So, the url will change if I go back to redeploy one of our existing webapps -- that will screw up several things, the least of which are bit.ly links pointing to the old url.

Not having these warnings appear was one of the benefits I read about when we considered signing up for what was then called a Google Apps account.  I'm an admin of our account and received several G Suite alert emails on July 6 2017 about problems occuring with Google Drive, Calendar, Hangouts, etc.  Maybe those are connected?


问:
how to build JSONobject request to use in HttpPost
I here is an example that I need to build:

```<code>{
  "sendSmsRequest": {
  "to": "5511982694404",
  "msg": "funcionou"
  }
}
</code>```

In order to do this, I have used JSONobject:

```<code>JSONObject jsonObject = new JSONObject();
jsonObject.put("to", "123456789");
jsonObject.put("msg", "Mensagem Teste");
StringEntity input = new StringEntity(jsonObject.toString());
</code>```

Here is the request:

```<code>post.setHeader("Accept", "application/json");
post.setHeader("Content-Type", "application/json");
post.setEntity(input);
</code>```

But I dont know how put the "header" - "sendSmsRequest"...
There is any way to do This without using String??

```<code>String teste = "{\"sendSmsRequest\": { \"to\": \"123456789\",\"msg\": \"funcionou\"}}";
</code>```

答:
You can do it like this:

```<code>JSONObject jsonObject = new JSONObject();
jsonObject.put("to", "123456789");
jsonObject.put("msg", "Mensagem Teste");
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("sendSmsRequest", jsonObject);

StringEntity input = new StringEntity(jsonObject1.toString());
</code>```

Like this you can have a JSONObject inside another JSONObject.

Body:
I here is an example that I need to build:

{
  "sendSmsRequest": {
  "to": "5511982694404",
  "msg": "funcionou"
  }
}

In order to do this, I have used JSONobject:

JSONObject jsonObject = new JSONObject();
jsonObject.put("to", "123456789");
jsonObject.put("msg", "Mensagem Teste");
StringEntity input = new StringEntity(jsonObject.toString());

Here is the request:

post.setHeader("Accept", "application/json");
post.setHeader("Content-Type", "application/json");
post.setEntity(input);

But I dont know how put the "header" - "sendSmsRequest"...
There is any way to do This without using String??

String teste = "{\"sendSmsRequest\": { \"to\": \"123456789\",\"msg\": \"funcionou\"}}";

Body:
You can do it like this:

JSONObject jsonObject = new JSONObject();
jsonObject.put("to", "123456789");
jsonObject.put("msg", "Mensagem Teste");
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("sendSmsRequest", jsonObject);

StringEntity input = new StringEntity(jsonObject1.toString());

Like this you can have a JSONObject inside another JSONObject.


问:
Unresolved dependencies in Akka http
I keep getting unresolved dependencies with the code below. Any clue what I can do to clear the error?

```<code>name := "AkkaDemo"

version := "1.0"

scalaVersion := "2.11.8"

val scalaTestVersion = "3.0.1"

resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/"

lazy val akkademoService = project.settings (libraryDependencies ++= Seq(
  "mysql" % "mysql-connector-java" % "5.1.25",
  "com.typesafe.slick" %% "slick"% "3.1.0",
  "com.typesafe.slick" %% "slick-hikaricp" % "3.1.0",
  "com.typesafe.akka" %% "akka-actor" % "2.4.16",
  "com.typesafe.akka" %% "akka-http" % "10.0.1",
  "com.typesafe.akka" % "akka-slf4j" % "2.3.14"

)).
  dependsOn(instanceConfig)

lazy val instanceConfig = project

lazy val AkkaDemo =  project.in(file(".")).aggregate(instanceConfig, akkademoService)
</code>```

Here is the sbt output for the sbt run:

```<code>Error:Error while importing SBT project:<br/>...<br/>```[info]
Resolving org.fusesource.jansi#jansi;1.4 ...
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: com.typesafe.akka#akka-actor_2.10;2.4.16: not found
[warn]  :: com.typesafe.akka#akka-slf4j;2.3.14: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
```

答: This was solved by adding build.sbt with the scalaversion to use to each module. Apparently each module, without a build.sbt specifying the version to use, default to 2.10.</p>

Title: Unresolved dependencies in Akka http

Body:
I keep getting unresolved dependencies with the code below. Any clue what I can do to clear the error?

name := "AkkaDemo"

version := "1.0"

scalaVersion := "2.11.8"

val scalaTestVersion = "3.0.1"

resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/"

lazy val akkademoService = project.settings (libraryDependencies ++= Seq(
  "mysql" % "mysql-connector-java" % "5.1.25",
  "com.typesafe.slick" %% "slick"% "3.1.0",
  "com.typesafe.slick" %% "slick-hikaricp" % "3.1.0",
  "com.typesafe.akka" %% "akka-actor" % "2.4.16",
  "com.typesafe.akka" %% "akka-http" % "10.0.1",
  "com.typesafe.akka" % "akka-slf4j" % "2.3.14"

)).
  dependsOn(instanceConfig)

lazy val instanceConfig = project

lazy val AkkaDemo =  project.in(file(".")).aggregate(instanceConfig, akkademoService)

Here is the sbt output for the sbt run:

Error:Error while importing SBT project:
...

[info]
Resolving org.fusesource.jansi#jansi;1.4 ...
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: com.typesafe.akka#akka-actor_2.10;2.4.16: not found
[warn]  :: com.typesafe.akka#akka-slf4j;2.3.14: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::


问:
How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?
I am populating a DataGridView control on a Windows Form (C# 2.0 not WPF).

My goal is to display a grid that neatly fills all available width with cells - i.e. no unused (dark grey) areas down the right and sizes each column appropriately according to the data it contains, but also allows the user to resize any of the columns to their liking.

I am attempting to achieve this by setting the AutoSizeMode of each column to be DataGridViewAutoSizeColumnMode.AllCells except for one of the columns which I set to DataGridViewAutoSizeColumnMode.Fill in order to ensure the entire area of the grid is neatly filled with data. (I don't mind that when the user attempt to resize this column it springs back to a size that ensures the horizontal space is always used.)

However, as I mentioned, once loaded I would like to allow the user to resize the columns to suit their own requirements - in setting these AutoSizeMode values for each column it appears the user is then unable to then resize those columns.

I've tried not setting the AutoSizeMode of all the columns which does allow resizing BUT doesn't set the initial size according to the data the cells contain. The same result occurs when changing the grid's AutoSizeMode back to "Not Set" after loading the data.

Is there a setting I'm missing here which allows automatic setting of default column widths AND user resizing or is there another technique I must use when populating the DataGridView control?

答:
I had to do this in VB and prefer to split it out to a method that I placed in a Module. You can add the Fill column as another ByRef parameter if desired.</p>

```<code>''' <summary>
''' Makes all columns in a DataGridView autosize based on displayed cells,
''' while leaving the column widths user-adjustable.
''' </summary>
''' <param name="dgv">A DataGridView to adjust</param>
Friend Sub MakeAdjustableAutoSizedGridCols(ByRef dgv As DataGridView)
    Dim width As Integer

    For Each col As DataGridViewColumn In dgv.Columns
        col.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
        width = col.Width
        col.AutoSizeMode = DataGridViewAutoSizeColumnMode.None
        col.Width = width
    Next
    dgv.AllowUserToResizeColumns = True
End Sub
</code>```

Body:
I had to do this in VB and prefer to split it out to a method that I placed in a Module. You can add the Fill column as another ByRef parameter if desired.

''' <summary>
''' Makes all columns in a DataGridView autosize based on displayed cells,
''' while leaving the column widths user-adjustable.
''' </summary>
''' <param name="dgv">A DataGridView to adjust</param>
Friend Sub MakeAdjustableAutoSizedGridCols(ByRef dgv As DataGridView)
    Dim width As Integer

    For Each col As DataGridViewColumn In dgv.Columns
        col.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
        width = col.Width
        col.AutoSizeMode = DataGridViewAutoSizeColumnMode.None
        col.Width = width
    Next
    dgv.AllowUserToResizeColumns = True
End Sub


问:
Change a variable name in all places in Python
I have written a code in Python3 using the IDE Wing, but I want to change a variable name, e.g., var_1, to var_2 in all places in my file. In MATLAB, when you change a variable name in one place, by Shift+Enter it is automatically done for all other occurrences of that variable in the file. Is there any similar way to do it in Python?

答: If you're using the Python Idle(GUI) you can Ctrl + H and select Replace All.</p>


问:
How to achieve s3 server side encryption, when using s3 with AWS SQS?
We have a use case where we have to manage SQS messages using S3 as described here. In this case how do we implement Server Side encryption(SSE) of messages sent to S3?. In the page it says to create an AmazonS3Client and use it to create AmazonSQSExtendedClient. But I don't see any option where we can specify that we need messages in S3 to be encrypted using  SSE.

This link talks about encryption of SQS message payloads in S3 using S3 Client encryption. But is it possible to achieve Server Side Encryption of SQS message payloads in S3 ?

答:
Currently AmazonSQSExtendedClient does not support S3 server side encryption.

Have a look at the Extended Client Source Code. In the code the method constructing S3 put object request,

```<code>private void storeTextInS3(String s3Key, String messageContentStr, Long messageContentSize) {
        InputStream messageContentStream = new ByteArrayInputStream(messageContentStr.getBytes(StandardCharsets.UTF_8));
        ObjectMetadata messageContentStreamMetadata = new ObjectMetadata();
        messageContentStreamMetadata.setContentLength(messageContentSize);
        PutObjectRequest putObjectRequest = new PutObjectRequest(clientConfiguration.getS3BucketName(), s3Key,
                messageContentStream, messageContentStreamMetadata);
        try {
            clientConfiguration.getAmazonS3Client().putObject(putObjectRequest);
        } catch (AmazonServiceException e) {
            String errorMessage = "Failed to store the message content in an S3 object. SQS message was not sent.";
            LOG.error(errorMessage, e);
            throw new AmazonServiceException(errorMessage, e);
        } catch (AmazonClientException e) {
            String errorMessage = "Failed to store the message content in an S3 object. SQS message was not sent.";
            LOG.error(errorMessage, e);
            throw new AmazonClientException(errorMessage, e);
        }
    }
</code>```

It does not include the extension for setting server side encryption. If you plan to modify the source code of the extended client, you can include server side encryption support as shown below.

```<code>PutObjectRequest putRequest = new PutObjectRequest(
                                      bucketName, keyName, file);

// Request server-side encryption.
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setSSEAlgorithm(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION);
putRequest.setMetadata(objectMetadata);
</code>```

For more details of S3 server side encryption using Java SDK have a look at this link.

Body:
Currently AmazonSQSExtendedClient does not support S3 server side encryption.

Have a look at the Extended Client Source Code. In the code the method constructing S3 put object request,

private void storeTextInS3(String s3Key, String messageContentStr, Long messageContentSize) {
        InputStream messageContentStream = new ByteArrayInputStream(messageContentStr.getBytes(StandardCharsets.UTF_8));
        ObjectMetadata messageContentStreamMetadata = new ObjectMetadata();
        messageContentStreamMetadata.setContentLength(messageContentSize);
        PutObjectRequest putObjectRequest = new PutObjectRequest(clientConfiguration.getS3BucketName(), s3Key,
                messageContentStream, messageContentStreamMetadata);
        try {
            clientConfiguration.getAmazonS3Client().putObject(putObjectRequest);
        } catch (AmazonServiceException e) {
            String errorMessage = "Failed to store the message content in an S3 object. SQS message was not sent.";
            LOG.error(errorMessage, e);
            throw new AmazonServiceException(errorMessage, e);
        } catch (AmazonClientException e) {
            String errorMessage = "Failed to store the message content in an S3 object. SQS message was not sent.";
            LOG.error(errorMessage, e);
            throw new AmazonClientException(errorMessage, e);
        }
    }

It does not include the extension for setting server side encryption. If you plan to modify the source code of the extended client, you can include server side encryption support as shown below.

PutObjectRequest putRequest = new PutObjectRequest(
                                      bucketName, keyName, file);

// Request server-side encryption.
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setSSEAlgorithm(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION);
putRequest.setMetadata(objectMetadata);

For more details of S3 server side encryption using Java SDK have a look at this link.


问:
New functions in module not 'seen' by iPython notebook
I recently got a new computer (my first Mac, I had a PC before). I have a module full of data analysis functions I use for my research, and I hadn't had any cause to edit the module until now. But suddenly, when I import the module in a Jupyter notebook, the new functions aren't 'seen'.

```<code>import altdata as alt
alt.retrieve_data_from_umiami_latlonam('GISS','AQUA', 'ts')
</code>```

And this raises the following error:

```<code>-----------------------------------------------------------------------
----
AttributeError                            Traceback (most recent call
last)
<ipython-input-3-9ccbc97fd6b8> in <module>()
1
 ----> 2 alt.retrieve_data_from_umiami_latlonam('GISS','AQUA', 'ts')

AttributeError: 'module' object has no attribute 'retrieve_data_from_umiami_latlonam'
</code>```

I cannot for the life of me figure out what the problem is. When try through the command line it works perfectly, but for some reason the new functions don't work in a notebook. Any ideas?

UPDATE

It seems that when I open the notebook in the directory where the module is located (/mymodules) it works.

When I open it in the directory that contains mymodules and use

```<code>import sys
sys.path.append(r'/mymodules')
import altdata as alt
</code>```

I get the error. Any ideas?

答: Have you modified you module after starting the notebook and importing the module for the for first time in that notebook? In that case, you could try to reload it, e.g,.  importlib.reload(module). If this doesn't help, try restarting the notebook and re-import the module to check if this solves the problem.

Body:
I recently got a new computer (my first Mac, I had a PC before). I have a module full of data analysis functions I use for my research, and I hadn't had any cause to edit the module until now. But suddenly, when I import the module in a Jupyter notebook, the new functions aren't 'seen'.

import altdata as alt
alt.retrieve_data_from_umiami_latlonam('GISS','AQUA', 'ts')

And this raises the following error:

-----------------------------------------------------------------------
----
AttributeError                            Traceback (most recent call
last)
<ipython-input-3-9ccbc97fd6b8> in <module>()
1
 ----> 2 alt.retrieve_data_from_umiami_latlonam('GISS','AQUA', 'ts')

AttributeError: 'module' object has no attribute 'retrieve_data_from_umiami_latlonam'

I cannot for the life of me figure out what the problem is. When try through the command line it works perfectly, but for some reason the new functions don't work in a notebook. Any ideas?

UPDATE

It seems that when I open the notebook in the directory where the module is located (/mymodules) it works.

When I open it in the directory that contains mymodules and use

import sys
sys.path.append(r'/mymodules')
import altdata as alt

I get the error. Any ideas?


问:
How to query json data in angular 2
I want to query JSON data based on some conditions using angular2

My json is:

```<code>{
"logsArray":[
    {
        "Id": "1",
        "ProjectName": "Project01",
        "ModuleName": "Module01",
        "MethodName": "Method01",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "2",
        "ProjectName": "Project02",
        "ModuleName": "Module01",
        "MethodName": "Method03",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "3",
        "ProjectName": "Project03",
        "ModuleName": "Module05",
        "MethodName": "Method01",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "4",
        "ProjectName": "Project01",
        "ModuleName": "Module07",
        "MethodName": "Method01",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "5",
        "ProjectName": "Project03",
        "ModuleName": "Module01",
        "MethodName": "Method10",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "6",
        "ProjectName": "Project06",
        "ModuleName": "Module01",
        "MethodName": "Method05",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "7",
        "ProjectName": "Project03",
        "ModuleName": "Module03",
        "MethodName": "Method07",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "8",
        "ProjectName": "Project04",
        "ModuleName": "Module03",
        "MethodName": "Method05",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    }
]
}
</code>```

I want to get the particular property based on some conditions like

Distinct ProjectNames where PojectName = Project03

Distincts ModuleNames where ModuleName = Module02 && MethodName = Method01

Distinct Method Names ProjectName = Project01

答:
Have you checked out the Angular2 Json API library?

Once you have it setup, it looks something like this:

```<code>this.datastore.findRecord(logsArray, '1').subscribe(
   (post: logsArray) => console.log(post)
);
</code>```

Title: How to query json data in angular 2

Body:
I want to query JSON data based on some conditions using angular2

My json is:

{
"logsArray":[
    {
        "Id": "1",
        "ProjectName": "Project01",
        "ModuleName": "Module01",
        "MethodName": "Method01",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "2",
        "ProjectName": "Project02",
        "ModuleName": "Module01",
        "MethodName": "Method03",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "3",
        "ProjectName": "Project03",
        "ModuleName": "Module05",
        "MethodName": "Method01",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "4",
        "ProjectName": "Project01",
        "ModuleName": "Module07",
        "MethodName": "Method01",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "5",
        "ProjectName": "Project03",
        "ModuleName": "Module01",
        "MethodName": "Method10",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "6",
        "ProjectName": "Project06",
        "ModuleName": "Module01",
        "MethodName": "Method05",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "7",
        "ProjectName": "Project03",
        "ModuleName": "Module03",
        "MethodName": "Method07",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    },
    {
        "Id": "8",
        "ProjectName": "Project04",
        "ModuleName": "Module03",
        "MethodName": "Method05",
        "Message": "MessageMessage",
        "MessageDetails": "MessageDetailsMessageDetails",
        "LogType": "LogType",
        "CreatedDate": "Fri May 04 2012 01:17:07 GMT-0700 (PDT)",
        "CreatedBy": "User01"
    }
]
}

I want to get the particular property based on some conditions like

Distinct ProjectNames where PojectName = Project03

Distincts ModuleNames where ModuleName = Module02 && MethodName = Method01

Distinct Method Names ProjectName = Project01

Body:
Have you checked out the Angular2 Json API library?

Once you have it setup, it looks something like this:

this.datastore.findRecord(logsArray, '1').subscribe(
   (post: logsArray) => console.log(post)
);


问:
How to route an array of params in Rails
So I want to pass through an array of params to a "testers" route in Rails. My table for testers currently looks like this:

```<code>class CreateTesters < ActiveRecord::Migration[5.1]
  def change
    create_table :testers do |t|
      t.integer :testerID
      t.string :firstName
      t.string :lastName
      t.string :country
      t.datetime :lastLogin

      t.timestamps
    end
  end
end
</code>```

The url I want to make a request to looks like this: http://localhost:3000/testers?tester_id[]=1&tester_id[]=2&country[]=US

My server is correctly identifying that I've passed an array of params, but my issue is that it's hitting the index route and simply returning all the testers in my database.

How do I either get Rails to recognize this as a 'show` request, or create a custom route for this type of url?

答:
In the view:

```<code>= link_to 'Testers', testers_path(ids: @selected_testers.pluck(:id))
</code>```

In the controller:

```<code>@testers = Tester.find(params[:ids])
</code>```

As opposed to using where, find makes sure that there's a record for every given ID. So if an ID 1337 comes in as part of the params[:ids] array and there is no tester with ID 1337 in the database, it raises an an error (similar to when you call Tester.find(1337)).

Body:
So I want to pass through an array of params to a "testers" route in Rails. My table for testers currently looks like this:

class CreateTesters < ActiveRecord::Migration[5.1]
  def change
    create_table :testers do |t|
      t.integer :testerID
      t.string :firstName
      t.string :lastName
      t.string :country
      t.datetime :lastLogin

      t.timestamps
    end
  end
end

The url I want to make a request to looks like this: http://localhost:3000/testers?tester_id[]=1&tester_id[]=2&country[]=US

My server is correctly identifying that I've passed an array of params, but my issue is that it's hitting the index route and simply returning all the testers in my database.

How do I either get Rails to recognize this as a 'show` request, or create a custom route for this type of url?

Body:
In the view:

= link_to 'Testers', testers_path(ids: @selected_testers.pluck(:id))

In the controller:

@testers = Tester.find(params[:ids])

As opposed to using where, find makes sure that there's a record for every given ID. So if an ID 1337 comes in as part of the params[:ids] array and there is no tester with ID 1337 in the database, it raises an an error (similar to when you call Tester.find(1337)).


问:
Unable to connect to ftp server java
I should be able to successfully send and receive file to/from FTP server.

But then, no changes occurred in the code and I started getting this :

Error: java.net.ConnectException: Connection timed out: connect

What I am doing is:

```<code>FTPClient ftp = new FTPClient();

ftp.connect( IPADDRESS of FTP server);
</code>```

connect() is giving this execption. I am not understanding the cause for it.

答:
The error message is telling you that the OS's attempt to connect to the server timed out.  This typically means that:

the remote server has dropped off the network, or

something (e.g. a firewall) is "black holing" packets sent to the server on the FTP port.

Title: Unable to connect to ftp server java

Body:
I should be able to successfully send and receive file to/from FTP server.

But then, no changes occurred in the code and I started getting this :

Error: java.net.ConnectException: Connection timed out: connect

What I am doing is:

FTPClient ftp = new FTPClient();

ftp.connect( IPADDRESS of FTP server);

connect() is giving this execption. I am not understanding the cause for it.


问:
FreeTDS problem connecting to SQL Server on Mac (Unexpected EOF from the server)
I have setup FreeTDS to connect to SQL Server database.  When I try to open TSQL in terminal on Mac (lion) I get this error:

```<code>locale is "en_US.UTF-8"
locale charset is "UTF-8"
using default charset "UTF-8"
Error 20017 (severity 9):
    Unexpected EOF from the server
    OS error 36, "Operation now in progress"
Error 20002 (severity 9):
    Adaptive Server connection failed
There was a problem connecting to the server
</code>```

Does anybody have a clue what could be causing this?

答:
I was having the same problem.  In my situation, the username for the Microsoft SQL Server database was in the form, DOMAIN\userid.  However, when I typed it on the command line, I think it was interpreting the slash as an escape character.  When I tried putting the slash the other direction, it still failed.  Finally, I tried putting two slashes in the original direction and it worked.  Thus the following worked for me:

```<code>tsql -S myhost -U DOMAIN\\userid
</code>```

Body:
I have setup FreeTDS to connect to SQL Server database.  When I try to open TSQL in terminal on Mac (lion) I get this error:

locale is "en_US.UTF-8"
locale charset is "UTF-8"
using default charset "UTF-8"
Error 20017 (severity 9):
    Unexpected EOF from the server
    OS error 36, "Operation now in progress"
Error 20002 (severity 9):
    Adaptive Server connection failed
There was a problem connecting to the server

Does anybody have a clue what could be causing this?

Body:
I was having the same problem.  In my situation, the username for the Microsoft SQL Server database was in the form, DOMAIN\userid.  However, when I typed it on the command line, I think it was interpreting the slash as an escape character.  When I tried putting the slash the other direction, it still failed.  Finally, I tried putting two slashes in the original direction and it worked.  Thus the following worked for me:

tsql -S myhost -U DOMAIN\\userid


问:
Side-by-side boxplots with Pandas
I need to plot comparison of five variable, stored in pandas dataframe. I used an example from here, it worked, but now I need to change the axes and titles, but I'm struggling to do so.

Here is my data:

```<code>df1.groupby('cls').head()
Out[171]:
   sensitivity  specificity  accuracy       ppv       auc       cls
0     0.772091     0.824487  0.802966  0.799290  0.863700       sig
1     0.748931     0.817238  0.776366  0.785910  0.859041       sig
2     0.774016     0.805909  0.801975  0.789840  0.853132       sig
3     0.826670     0.730071  0.795715  0.784150  0.850024       sig
4     0.781112     0.803839  0.824709  0.791530  0.863411       sig
0     0.619048     0.748290  0.694969  0.686138  0.713899  baseline
1     0.642348     0.702076  0.646216  0.674683  0.712632  baseline
2     0.567344     0.765410  0.710650  0.665614  0.682502  baseline
3     0.644046     0.733645  0.754621  0.683485  0.734299  baseline
4     0.710077     0.653871  0.707933  0.684313  0.732997  baseline
</code>```

Here is my code:

```<code>>> fig, axes = plt.subplots(ncols=5, figsize=(12, 5), sharey=True)
>> df1.query("cls in ['sig', 'baseline']").boxplot(by='cls', return_type='axes', ax=axes)
</code>```

And the resulting pictures are:

How to:

change the title ('Boxplot groupped by cls')

get rid of annoying [cls] plotted along the horizontal line

reorder the plotted categories as they appear in df1? (first sensitivity, followed by speci...)

答:
Maybe this helps you:</p>

```<code>fig, axes = pyplot.subplots(ncols=4, figsize=(12, 5), sharey=True)
df.query("E in [1, 2]").boxplot(by='E', return_type='axes', ax=axes, column=list('bcda')) # Keeping original columns order
pyplot.suptitle('Boxplot') # Changing title
[ax.set_xlabel('') for ax in axes] # Changing xticks for all plots
</code>```

Title: Side-by-side boxplots with Pandas

Body:
I need to plot comparison of five variable, stored in pandas dataframe. I used an example from here, it worked, but now I need to change the axes and titles, but I'm struggling to do so.

Here is my data:

df1.groupby('cls').head()
Out[171]:
   sensitivity  specificity  accuracy       ppv       auc       cls
0     0.772091     0.824487  0.802966  0.799290  0.863700       sig
1     0.748931     0.817238  0.776366  0.785910  0.859041       sig
2     0.774016     0.805909  0.801975  0.789840  0.853132       sig
3     0.826670     0.730071  0.795715  0.784150  0.850024       sig
4     0.781112     0.803839  0.824709  0.791530  0.863411       sig
0     0.619048     0.748290  0.694969  0.686138  0.713899  baseline
1     0.642348     0.702076  0.646216  0.674683  0.712632  baseline
2     0.567344     0.765410  0.710650  0.665614  0.682502  baseline
3     0.644046     0.733645  0.754621  0.683485  0.734299  baseline
4     0.710077     0.653871  0.707933  0.684313  0.732997  baseline

Here is my code:

>> fig, axes = plt.subplots(ncols=5, figsize=(12, 5), sharey=True)
>> df1.query("cls in ['sig', 'baseline']").boxplot(by='cls', return_type='axes', ax=axes)

And the resulting pictures are:

How to:

change the title ('Boxplot groupped by cls')

get rid of annoying [cls] plotted along the horizontal line

reorder the plotted categories as they appear in df1? (first sensitivity, followed by speci...)

Body:
Maybe this helps you:

fig, axes = pyplot.subplots(ncols=4, figsize=(12, 5), sharey=True)
df.query("E in [1, 2]").boxplot(by='E', return_type='axes', ax=axes, column=list('bcda')) # Keeping original columns order
pyplot.suptitle('Boxplot') # Changing title
[ax.set_xlabel('') for ax in axes] # Changing xticks for all plots


问:
multiple if statements in Swift
```<code>@IBAction func addtoCart(_ sender: Any) {
    if UserDataSingleton.sharedDataContainer.is_guest == "guest"  {
        //segue, user is a guest
    }

    if sizebtn.isHidden == false {
        if Size.selectedItem == nil {
            // show alert , nothing is selected from items
        }
    } else {
        // do API call
    }
}
</code>```

The code above skips api calls if the user is not a guest and has selected something from item. How can I check if :

user is not a guest

if UIButton isn't hidden and user has selected from item

答:
You can use guard statement to do validations:

```<code>@IBAction func addtoCart(_ sender: Any) {
   guard UserDataSingleton.sharedDataContainer.is_guest != "guest" else {
       //segue, user is a guest
       return
   }

   guard sizebtn.isHidden && Size.selectedItem == nil else {
       // show alert , nothing is selected from items
       return
   }

    // do API call
}
</code>```

Title: multiple if statements in Swift

Body:
@IBAction func addtoCart(_ sender: Any) {
    if UserDataSingleton.sharedDataContainer.is_guest == "guest"  {
        //segue, user is a guest
    }

    if sizebtn.isHidden == false {
        if Size.selectedItem == nil {
            // show alert , nothing is selected from items
        }
    } else {
        // do API call
    }
}

The code above skips api calls if the user is not a guest and has selected something from item. How can I check if :

user is not a guest

if UIButton isn't hidden and user has selected from item

Body:
You can use guard statement to do validations:

@IBAction func addtoCart(_ sender: Any) {
   guard UserDataSingleton.sharedDataContainer.is_guest != "guest" else {
       //segue, user is a guest
       return
   }

   guard sizebtn.isHidden && Size.selectedItem == nil else {
       // show alert , nothing is selected from items
       return
   }

    // do API call
}


问:
Linux - Giving all users access to a folder (and all folders and files below)
I know this seems like its a question I could just google, but I've tried and to be honest I'm still stuck.

The question I'm trying to solve asks...

Your current directory is sample_dir. Add the permission (using
  symbolic) for gen_ed so that all users can access the file cars2:

The path is stenton/gen_ed/cars2 from the working directory.

So naturally, I assumed it was:

chmod -R ugo+r stenton/gen_ed, however that fails. I've tried a ton of iterations on the same line of thinking, but they've all failed.

Can someone please end this torment!

答:
For anyone who is still searching for the correct answer for this question, it is: </p>

```<code>chmod a+x stenton/gen_ed
</code>```

Body:
For anyone who is still searching for the correct answer for this question, it is:

chmod a+x stenton/gen_ed


问:
paralell_rspec with options --exclude-pattern
Trying to exclude the specs in the /home dir during the parallel run.

Tried a few things similar to the following:

parallel_rspec myproj -n 4 -o '--exclude-pattern "myproj/spec/home/*_spec.rb"'

parallel_rspec ./myproj -n 4 -o '--exclude-pattern "./myproj/spec/home/*_spec.rb"'

But it does not exclude specs in the /home dir. It runs all specs in myproj.

The following commands do exclude specs in /home dir but I need to run them in parallel:

rspec myproj --exclude-pattern "myproj/spec/home/*_spec.rb"

rspec ./myproj --exclude-pattern "./myproj/spec/home/*_spec.rb"

答:
I ended up using the parallel_test gem.

I added the following to the .rspec_parallel file:

```<code>--tag ~tagname1
--tag ~tagname2
--tag ~tagname3
</code>```

This excluded the specs tagged with tagname1,2,3.

Body:
I ended up using the parallel_test gem.

I added the following to the .rspec_parallel file:

--tag ~tagname1
--tag ~tagname2
--tag ~tagname3

This excluded the specs tagged with tagname1,2,3.


答: If you're using the PyCharm IDE use Mayus + F6 on the variable that you want change and write the new name variable.</p>

Title: Change a variable name in all places in Python

Body: I have written a code in Python3 using the IDE Wing, but I want to change a variable name, e.g., var_1, to var_2 in all places in my file. In MATLAB, when you change a variable name in one place, by Shift+Enter it is automatically done for all other occurrences of that variable in the file. Is there any similar way to do it in Python?


问:
Identify all possible combinations of a variable, including if values are missing in R
I'm curious about the total number of ways people could have completed a training in a 'choose your own adventure format'

For example, there are 10 different levels to the training in total (i.e., level 1, 2 ... 10). People can complete 1:10; 10:1; 1,2,3,5,10; 2,1,3,5,4,6,7,9,8,10; or any combination of the levels using all, some, or none of the levels before taking their exit test.

I'm hoping to find a way to make these combinations into a categorical variable because I'm wondering if sequence matters in the users likelihood of passing the exit test.

I'd like to know how to do this in R, but if anyone has other creative solutions to offer regarding better ways to use sequence as a variable, I'm all ears for that too.

Thanks!

答:
You may want to look at expand.grid  </p>

```<code>dat <- expand.grid(1:10, 1:10)

library(tidyr)

unite(dat, perms = Var1, Var2, sep=".")
</code>```

Body:
You may want to look at expand.grid

dat <- expand.grid(1:10, 1:10)

library(tidyr)

unite(dat, perms = Var1, Var2, sep=".")


问:
creating a method to return a range of random values
Consider the following code. The basic idea is to return a comma separated list of 20 numbers any of which can be a value between 0 and the max allowed value. On each pass through the loop the potential max value allowed for the next value in the list reduces by whatever last random value picked was.

So it works... but it sucks. The problem being it's always going to produce output like this:

"22,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"

"17,3,3,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"

"23,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"

How could it be modified to allow for a more even distribution of values across the range?

```<code>    public static string RandomRangeOfValuesMaker(int total)
    {
        var remainingTotal = total + 1;

        const int numberOfValues = 20;

        var rand = new Random();

        var builder = new StringBuilder();

        for (var i = 1; i < numberOfValues + 1; i++)
        {
            var currentRandomNumber = rand.Next(remainingTotal);

            remainingTotal = remainingTotal - currentRandomNumber;

            builder.Append(currentRandomNumber + ",");
        }

        var rangeOfValues = builder.ToString().Remove(builder.ToString().Length - 1);

        return rangeOfValues;
    }
</code>```

答:
I'll preface this with: Read the answer from Eric Lippert - what he says is almost certainly more correct than me (pssst.. he studied Mathematics at University AND worked on the C# compiler, amongst other things, at Microsoft!).

A rudimentary implementation of your requirement that the function return X values that sum to Y could be written as:

```<code>public static string StringyRandomNumbersThatAddUpToMaxNumber(int sumOfRandomNumbers, int numberOfValuesToReturn)
{
    var randomNumbers = RandomNumbersThatAddUpToMaxNumber(new List<int>(), sumOfRandomNumbers, numberOfValuesToReturn);
    return string.Join(",", randomNumbers);
}

public static IEnumerable<int> RandomNumbersThatAddUpToMaxNumber(List<int> randomNumbers, int sumOfRandomNumbers, int numberOfValuesToReturn)
{
    var randomNumberGenerator = new Random();

    while (randomNumbers.Sum() < sumOfRandomNumbers)
    {
        var ceiling = (randomNumbers.Any() ? randomNumbers.Sum() : sumOfRandomNumbers) / 2;
        var newNumber = randomNumberGenerator.Next(ceiling);

        if (randomNumbers.Sum() + newNumber <= sumOfRandomNumbers)
        {
            randomNumbers.Add(newNumber);
        }
    }

    if (numberOfValuesToReturn > randomNumbers.Count())
    {
        randomNumbers.Remove(randomNumbers.Max());

        return RandomNumbersThatAddUpToMaxNumber(randomNumbers, sumOfRandomNumbers, numberOfValuesToReturn);
    }

    return randomNumbers;
}
</code>```

In theory, it may never return or throw a StackOverflowException, but in practice it's likely that it will.

I'm not in any way, shape, or form confident that the resultant numbers could be considered to be truly random (as it eliminates the highest value on each recursion to allow it more "working space" to find more values to satisfy the requirement that they all add up to Y), so please take this code with that note.

Body:
Consider the following code. The basic idea is to return a comma separated list of 20 numbers any of which can be a value between 0 and the max allowed value. On each pass through the loop the potential max value allowed for the next value in the list reduces by whatever last random value picked was.

So it works... but it sucks. The problem being it's always going to produce output like this:

"22,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"

"17,3,3,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"

"23,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"

How could it be modified to allow for a more even distribution of values across the range?

    public static string RandomRangeOfValuesMaker(int total)
    {
        var remainingTotal = total + 1;

        const int numberOfValues = 20;

        var rand = new Random();

        var builder = new StringBuilder();

        for (var i = 1; i < numberOfValues + 1; i++)
        {
            var currentRandomNumber = rand.Next(remainingTotal);

            remainingTotal = remainingTotal - currentRandomNumber;

            builder.Append(currentRandomNumber + ",");
        }

        var rangeOfValues = builder.ToString().Remove(builder.ToString().Length - 1);

        return rangeOfValues;
    }

Body:
I'll preface this with: Read the answer from Eric Lippert - what he says is almost certainly more correct than me (pssst.. he studied Mathematics at University AND worked on the C# compiler, amongst other things, at Microsoft!).

A rudimentary implementation of your requirement that the function return X values that sum to Y could be written as:

public static string StringyRandomNumbersThatAddUpToMaxNumber(int sumOfRandomNumbers, int numberOfValuesToReturn)
{
    var randomNumbers = RandomNumbersThatAddUpToMaxNumber(new List<int>(), sumOfRandomNumbers, numberOfValuesToReturn);
    return string.Join(",", randomNumbers);
}

public static IEnumerable<int> RandomNumbersThatAddUpToMaxNumber(List<int> randomNumbers, int sumOfRandomNumbers, int numberOfValuesToReturn)
{
    var randomNumberGenerator = new Random();

    while (randomNumbers.Sum() < sumOfRandomNumbers)
    {
        var ceiling = (randomNumbers.Any() ? randomNumbers.Sum() : sumOfRandomNumbers) / 2;
        var newNumber = randomNumberGenerator.Next(ceiling);

        if (randomNumbers.Sum() + newNumber <= sumOfRandomNumbers)
        {
            randomNumbers.Add(newNumber);
        }
    }

    if (numberOfValuesToReturn > randomNumbers.Count())
    {
        randomNumbers.Remove(randomNumbers.Max());

        return RandomNumbersThatAddUpToMaxNumber(randomNumbers, sumOfRandomNumbers, numberOfValuesToReturn);
    }

    return randomNumbers;
}

In theory, it may never return or throw a StackOverflowException, but in practice it's likely that it will.

I'm not in any way, shape, or form confident that the resultant numbers could be considered to be truly random (as it eliminates the highest value on each recursion to allow it more "working space" to find more values to satisfy the requirement that they all add up to Y), so please take this code with that note.


答:
Visual Studio Code is Ctrl + Shift + L and begin typing.
Sublime/Atom are alt + F3. </p>


问:
Pick up connection if there is a disconnect
I make use of this specific version: https://github.com/patriksimek/node-mssql/tree/v3.3.0#multiple-connections of the SQL Server npm package.

I have been looking through the documentation of tedious (the underlying lib) and Microsofts documentation (see the github link above).

I couldn't find anything that does something simple like getCurrentConnection, or getConnectionStatus or anything similar.

I had two ways to solve this problem but I'm not happy with both of them so that's why I'm asking here.

My first approach was to set a timeout and let the connect function call itself on each catch(err).

The second one was to handle this in the middleware but then if all is working fine it will make a connection to SQL on every request and closing that connection again.

My middleware function:

```<code>api.use(function(err, req, res, next){
   sql.close();
   sql.connect(config.database).then(() => {
     next();
   }).catch(function(err) {
     sql.close();
     server.main();
   });
});
</code>```

I want to, if possible pick up the connection instead of closing and starting a new one with regards to when the server or the database crashes I still have some data from the existing function.

答:
If I understood you correctly, you basically want to reuse connections. Tedious has built-in connection pooling, so you don't have to worry about re-using them:

```<code>var config = {
    user: '...',
    password: '...',
    server: 'localhost',
    database: '...',
    pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
    }
}
</code>```

In the example above (just copied from the GitHub URL you've posted), there will be 10 connections in the pool ready to use. Here's the beauty: the pool manager will handle all connection use and re-use for you, i.e., the number of connections are elastic based on your app's needs.

As you've mentioned, what about DB crashes? That too is built-in: connection health-check:

Internally, each Connection instance is a separate pool of TDS
  connections. Once you create a new Request/Transaction/Prepared
  Statement, a new TDS connection is acquired from the pool and reserved
  for desired action. Once the action is complete, connection is
  released back to the pool. Connection health check is built-in so once
  the dead connection is discovered, it is immediately replaced with a
  new one.

I hope this helps!

ContentLicense: CC BY-SA 4.0

Body:
I make use of this specific version: https://github.com/patriksimek/node-mssql/tree/v3.3.0#multiple-connections of the SQL Server npm package.

I have been looking through the documentation of tedious (the underlying lib) and Microsofts documentation (see the github link above).

I couldn't find anything that does something simple like getCurrentConnection, or getConnectionStatus or anything similar.

I had two ways to solve this problem but I'm not happy with both of them so that's why I'm asking here.

My first approach was to set a timeout and let the connect function call itself on each catch(err).

The second one was to handle this in the middleware but then if all is working fine it will make a connection to SQL on every request and closing that connection again.

My middleware function:

api.use(function(err, req, res, next){
   sql.close();
   sql.connect(config.database).then(() => {
     next();
   }).catch(function(err) {
     sql.close();
     server.main();
   });
});

I want to, if possible pick up the connection instead of closing and starting a new one with regards to when the server or the database crashes I still have some data from the existing function.

Body:
If I understood you correctly, you basically want to reuse connections. Tedious has built-in connection pooling, so you don't have to worry about re-using them:

var config = {
    user: '...',
    password: '...',
    server: 'localhost',
    database: '...',
    pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
    }
}

In the example above (just copied from the GitHub URL you've posted), there will be 10 connections in the pool ready to use. Here's the beauty: the pool manager will handle all connection use and re-use for you, i.e., the number of connections are elastic based on your app's needs.

As you've mentioned, what about DB crashes? That too is built-in: connection health-check:

Internally, each Connection instance is a separate pool of TDS
  connections. Once you create a new Request/Transaction/Prepared
  Statement, a new TDS connection is acquired from the pool and reserved
  for desired action. Once the action is complete, connection is
  released back to the pool. Connection health check is built-in so once
  the dead connection is discovered, it is immediately replaced with a
  new one.

I hope this helps!


问:
How to get version id of a S3 object by ruby?
I have implemented aws-sdk library and can download and upload files successfully. I have enabled the versioning on S3. How could I get the version id of a S3 object by ruby? Could you show me a example? Thank you.</p>

答:
Problem solved.

```<code>bucket.objects[key].versions.latest
</code>```

can return the latest version id of an object

reference: http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/S3/S3Object.html

Body:
Problem solved.

bucket.objects[key].versions.latest

can return the latest version id of an object

reference: http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/S3/S3Object.html


问:
Scrapy : selecting table row using 'role'

I'm trying to select a table row that looks like (also screenshot):

```<code><tr data-uid="65724478-5102-4fa3-8de1-17b54dd7909c" role="row"><td role="gridcell"><input id="tesT1" name="tesT1" onchange="SelectedYearDetailck({id:'R12684_2016',TaxDue:231.33,TaxYr:2016,AgEntityID:072000})" type="checkbox" value="true" checked="checked"><input name="tesT1" type="hidden" value="false"><label for="tesT1" class="cklabel"></label><input type="hidden" id="ck_2016" value="ck_R12684"><div id="grid-wait_R12684" style="display:none;" class="grid-wait"><img src="../Content/Images/25(1).GIF"></div></td><td role="gridcell">2016</td><td style="text-align:right;" role="gridcell">$231.33</td><td style="text-align:right;" role="gridcell">$327.58</td></tr>
</code>```

I've tried:

```<code>response.selector.xpath("//tr[contains(@role,'row')]")
Out[2]: []
response.selector.xpath("//tr[(@role='row')]")
Out[3]: []
</code>```

How can I select this row using its role attribute?

答:
Like this:</p>

```<code>>>> from scrapy.selector import Selector
>>> HTML = '''\
... <tr data-uid="65724478-5102-4fa3-8de1-17b54dd7909c" role="row">
...     <td role="gridcell">...</td>
...     <td role="gridcell">2016</td>
... </tr>'''
>>> selector = Selector(text=HTML)
>>> selector.xpath('.//tr[@role="row"]').extract()
['<tr data-uid="65724478-5102-4fa3-8de1-17b54dd7909c" role="row">\n\t<td role="gridcell">...</td>\n\t<td role="gridcell">2016</td>\n</tr>']
</code>```

Body:
I'm trying to select a table row that looks like (also screenshot):

<input id="tesT1" name="tesT1" onchange="SelectedYearDetailck({id:'R12684_2016',TaxDue:231.33,TaxYr:2016,AgEntityID:072000})" type="checkbox" value="true" checked="checked"><input name="tesT1" type="hidden" value="false"><input type="hidden" id="ck_2016" value="ck_R12684">

	2016	$231.33	$327.58

I've tried:

response.selector.xpath("//tr[contains(@role,'row')]")
Out[2]: []
response.selector.xpath("//tr[(@role='row')]")
Out[3]: []

How can I select this row using its role attribute?

Body:
Like this:

>>> from scrapy.selector import Selector
>>> HTML = '''\
... <tr data-uid="65724478-5102-4fa3-8de1-17b54dd7909c" role="row">
...     <td role="gridcell">...</td>
...     <td role="gridcell">2016</td>
... </tr>'''
>>> selector = Selector(text=HTML)
>>> selector.xpath('.//tr[@role="row"]').extract()
['<tr data-uid="65724478-5102-4fa3-8de1-17b54dd7909c" role="row">\n\t<td role="gridcell">...</td>\n\t<td role="gridcell">2016</td>\n</tr>']


问:
What's the simplest way to intercept a method call for added functionality?
Suppose i have a repository that returns a list of Posts. The repository interface has a GetAll() method which does what it suggests.

Now in keeping with the theory that i shouldn't be putting domain logic in the repository, i want to intercept calls to the concrete GetAll() method such that i can add the following logic to the GetAll() result:

```<code>return GetAll().OrderByDescending(p => p.Posted).ToList();
</code>```

The reason i want to intercept this is because (1) i don't want to have the client remember to call an extension method (OrderByDescending or some useless wrapper of that), i want it called every time and (2) i don't want to have all my concrete implementations have to remember to order the GetAll() result - i want this logic in a single place external to any repository.

What's the easiest way to do this?

I'm already using StructureMap so if i can intercept with this it might be a low cost option. But i don't think SM intercepts method calls, just the creation of the object instance?

Do i need to go to a proxy or mixin pattern? Do i need to go all-in with Castle Dynamic Proxy? Or is there another method i should consider or perhaps a combination?

I'm really interested in a concrete suggestion to my particular example above. I'm novice to AOP so please be gentle.

答:
AFAIK, StructureMap only intercepts object construction, so using it it's not going to work.

I don't know Castle, but I think that the idea - here - is to apply Decorator pattern, so you could also do it by yourself without recurring to a third party library by following the steps described in the previous link.

That's how I'd do it, since I'm not a big fan of AOP.

HTH

Body:
Suppose i have a repository that returns a list of Posts. The repository interface has a GetAll() method which does what it suggests.

Now in keeping with the theory that i shouldn't be putting domain logic in the repository, i want to intercept calls to the concrete GetAll() method such that i can add the following logic to the GetAll() result:

return GetAll().OrderByDescending(p => p.Posted).ToList();

The reason i want to intercept this is because (1) i don't want to have the client remember to call an extension method (OrderByDescending or some useless wrapper of that), i want it called every time and (2) i don't want to have all my concrete implementations have to remember to order the GetAll() result - i want this logic in a single place external to any repository.

What's the easiest way to do this?

I'm already using StructureMap so if i can intercept with this it might be a low cost option. But i don't think SM intercepts method calls, just the creation of the object instance?

Do i need to go to a proxy or mixin pattern? Do i need to go all-in with Castle Dynamic Proxy? Or is there another method i should consider or perhaps a combination?

I'm really interested in a concrete suggestion to my particular example above. I'm novice to AOP so please be gentle.


问:
"You may not remove the user from their primary group."
Once upon a time I created a newuser.

```<code>sudo adduser newuser --ingroup admin
</code>```

and I didn't want them as an admin any longer

```<code>sudo deluser newuser admin
</code>```

/usr/sbin/deluser: You may not remove the user from their primary group.

Then the wicked witch of the west came and stopped me from removing them from that group. I tried adding a new group for them, but it didn't seem to matter. Even if they are in two groups, I cannot do this command.

答:
I had the same problem.
First I used:

```<code>usermod -g group user
</code>```

to give the user user, his primary group, group.

Then I used:

```<code>deluser user group
</code>```

Body:
Once upon a time I created a newuser.

sudo adduser newuser --ingroup admin

and I didn't want them as an admin any longer

sudo deluser newuser admin

/usr/sbin/deluser: You may not remove the user from their primary group.

Then the wicked witch of the west came and stopped me from removing them from that group. I tried adding a new group for them, but it didn't seem to matter. Even if they are in two groups, I cannot do this command.

Body:
I had the same problem.
First I used:

usermod -g group user

to give the user user, his primary group, group.

Then I used:

deluser user group


问:
ModelState.IsValid is always true
As is typical in MVC, I have a View, a Model, and a Controller.

The View contains a form:

```<code>@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(m => m.Id)
    <ul class="fieldlist">
        <li>
            @Html.LabelFor(m =>m.Email)
            @Html.TextBoxFor(m => m.Email)
            @Html.ValidationMessageFor(m => m.Email)
        </li>
        <li>
            <div class="row">
                <div class="col-md-6">
                    @Html.LabelFor(m => m.FirstName)
                    @Html.TextBoxFor(m => m.FirstName)
                    @Html.ValidationMessageFor(m => m.FirstName)
                </div>
                <div class="col-md-6">
                    @Html.LabelFor(m => m.LastName)
                    @Html.TextBoxFor(m => m.LastName)
                    @Html.ValidationMessageFor(m => m.LastName)
                </div>
            </div>
        </li>
        <li>
            @Html.LabelFor(m => m.PhoneNumber)
            @Html.TextBoxFor(m => m.PhoneNumber)
            @Html.ValidationMessageFor(m => m.PhoneNumber)
        </li>
        <li>
            <div Class="row">
                <div Class="col-md-2">
                    <input type="submit" value="Save" />
                </div>
            </div>
        </li>
    </ul>
}
</code>```

The model looks like this:

```<code>public class UserAdminUserViewModel
{
    [Display(Name = "User Database ID"), DataType(DataType.Text)]
    public string Id { get; set; }
    [Display(Name = "Full Name")]
    public string Name { get { return FirstName + " " + LastName; } }
    [Required()]
    [Display(Name = "First Name"), DataType(DataType.Text)]
    public string FirstName { get; set; }
    [Required()]
    [Display(Name = "Last Name"), DataType(DataType.Text)]
    public string LastName { get; set; }
    [Required()]
    [Display(Name = "Email Address"), DataType(DataType.EmailAddress)]
    public string Email { get; set; }
    [Display(Name = "Telephone Number"), DataType(DataType.Text)]
    public string PhoneNumber { get; set; }
}
</code>```

And the controller to receive the updates:

```<code>[HttpPost,ValidateAntiForgeryToken]
public ActionResult User(UserAdminUserViewModel model)
{
    if (ModelState.IsValid)
    {
        // do something, apply the updates to the database, presumably
    }
    return View(model);
}
</code>```

...but ModelState.IsValid is always true. The controller is receiving the entered information, but it appears that no validation is taking place. I have tried:

```<code>TryUpdateModel<UserAdminUserViewModel>(model);
</code>```

and

```<code>UpdateModel<UserAdminUserViewModel>(model);
</code>```

I'm not sure I see how these would work, but they were the first suggestions I came across. No dice. Still valid regardless of the data in 'model'. I also tried:

```<code>System.ComponentModel.DataAnnotations.Validator.ValidateObject(model, new System.ComponentModel.DataAnnotations.ValidationContext(model));
</code>```

More promising, but still doesn't work. I also tried the more verbose approach:

```<code>System.ComponentModel.DataAnnotations.ValidationContext valContext = new System.ComponentModel.DataAnnotations.ValidationContext(model, null, null);
List<System.ComponentModel.DataAnnotations.ValidationResult> valResults = new List<System.ComponentModel.DataAnnotations.ValidationResult>();
System.ComponentModel.DataAnnotations.Validator.TryValidateObject(model, valContext, valResults, true);
foreach(System.ComponentModel.DataAnnotations.ValidationResult result in valResults)
{
    this.ModelState.AddModelError(result.MemberNames.FirstOrDefault() ?? string.Empty, result.ErrorMessage);
}
</code>```

...which also didn't work. 'valResults', which should contain any errors in the state of the model, is never filled; no validation is happening.

答:
If the problem with incorrect email address, here's the solution:

```<code>[Email(ErrorMessage = "Invalid Email Address")]
[Required()]
[Display(Name = "Email Address"), DataType(DataType.EmailAddress)]
public string Email { get; set; }
</code>```

DataType(DataType.EmailAddress) means only how to show textbox on client-side, while Email attribute does actual validation.

Title: ModelState.IsValid is always true

Body:
As is typical in MVC, I have a View, a Model, and a Controller.

The View contains a form:

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(m => m.Id)

            @Html.LabelFor(m =>m.Email)
            @Html.TextBoxFor(m => m.Email)
            @Html.ValidationMessageFor(m => m.Email)

                    @Html.LabelFor(m => m.FirstName)
                    @Html.TextBoxFor(m => m.FirstName)
                    @Html.ValidationMessageFor(m => m.FirstName)

                    @Html.LabelFor(m => m.LastName)
                    @Html.TextBoxFor(m => m.LastName)
                    @Html.ValidationMessageFor(m => m.LastName)

            @Html.LabelFor(m => m.PhoneNumber)
            @Html.TextBoxFor(m => m.PhoneNumber)
            @Html.ValidationMessageFor(m => m.PhoneNumber)

                    <input type="submit" value="Save" />

}

The model looks like this:

public class UserAdminUserViewModel
{
    [Display(Name = "User Database ID"), DataType(DataType.Text)]
    public string Id { get; set; }
    [Display(Name = "Full Name")]
    public string Name { get { return FirstName + " " + LastName; } }
    [Required()]
    [Display(Name = "First Name"), DataType(DataType.Text)]
    public string FirstName { get; set; }
    [Required()]
    [Display(Name = "Last Name"), DataType(DataType.Text)]
    public string LastName { get; set; }
    [Required()]
    [Display(Name = "Email Address"), DataType(DataType.EmailAddress)]
    public string Email { get; set; }
    [Display(Name = "Telephone Number"), DataType(DataType.Text)]
    public string PhoneNumber { get; set; }
}

And the controller to receive the updates:

[HttpPost,ValidateAntiForgeryToken]
public ActionResult User(UserAdminUserViewModel model)
{
    if (ModelState.IsValid)
    {
        // do something, apply the updates to the database, presumably
    }
    return View(model);
}

...but ModelState.IsValid is always true. The controller is receiving the entered information, but it appears that no validation is taking place. I have tried:

TryUpdateModel<UserAdminUserViewModel>(model);

and

UpdateModel<UserAdminUserViewModel>(model);

I'm not sure I see how these would work, but they were the first suggestions I came across. No dice. Still valid regardless of the data in 'model'. I also tried:

System.ComponentModel.DataAnnotations.Validator.ValidateObject(model, new System.ComponentModel.DataAnnotations.ValidationContext(model));

More promising, but still doesn't work. I also tried the more verbose approach:

System.ComponentModel.DataAnnotations.ValidationContext valContext = new System.ComponentModel.DataAnnotations.ValidationContext(model, null, null);
List<System.ComponentModel.DataAnnotations.ValidationResult> valResults = new List<System.ComponentModel.DataAnnotations.ValidationResult>();
System.ComponentModel.DataAnnotations.Validator.TryValidateObject(model, valContext, valResults, true);
foreach(System.ComponentModel.DataAnnotations.ValidationResult result in valResults)
{
    this.ModelState.AddModelError(result.MemberNames.FirstOrDefault() ?? string.Empty, result.ErrorMessage);
}

...which also didn't work. 'valResults', which should contain any errors in the state of the model, is never filled; no validation is happening.

Body:
If the problem with incorrect email address, here's the solution:

[Email(ErrorMessage = "Invalid Email Address")]
[Required()]
[Display(Name = "Email Address"), DataType(DataType.EmailAddress)]
public string Email { get; set; }

DataType(DataType.EmailAddress) means only how to show textbox on client-side, while Email attribute does actual validation.


问:
Can Xcode windows be "document" windows instead of "browser" windows?
Is there any way, any hack, any plugin, anything that can force Xcode to stop shifting window contents and make it work like a 'document editor' instead of a 'web browser'?

Background (not a rant, just clarifying the 'want'):

Back in the old days of MPW, CodeWarrior and ObjectMaster the editor windows of the IDE acted like documents (aka opening a document in MS Word or Pages) instead of shifting their contents like a browser (aka Safari, FireFox).  When you opened a document in the Finder, it opened into it's own document window in your editor (a-la BBEdit, TextWrangler).

Today Xcode seems to want you to have only 1 window open and Xcode wants you to surf your code.  It is a constant battle to keep a organized workspace of 5, 10 or more "documents" open across my 3 monitors or even the single MacBook Pro screen.  When opening an Xcode source code "document" from the Finder, Xcode seemly randomly decides to replace the contents of the browsers and I loose context of my workspace. Clicking on a new "document" in the "Project Navigator" changes the content of the "browser" instead of opening up a new "document" window.

Yes, there is the option-command-click to get a new browser window instead of changing the current browser context, but there is nothing that keeps that content tied to that window.

What I am looking for is a way to reverse the Xcode editor metaphor and make "browser" an option and "document" the norm editing code. Ideally option-command-click would instead trigger browsing (which I would never use :-)

答:
I'm not aware of any hack, but is tabbing not enough? On the first tab i mostly use as file browser and other tabs just coding in specific files.

There is also shortcut keys for jumping back and fort.

I hope I could help.

PS: create Tab: File-> new -> tab or just press CMD+T


问:
How to escape quotations marks in a hyperlink
The link I must get to must be http://localhost:8088/imageInfo.php?id=4

 I started with this and no matter how I tried to escape I couldn't do it so any help would be appreciated

```<code>."<a href='imageInfo.php?id=<?php echo $image_id;?>'>".
</code>```

答:
It should be html code and should not be echoed again

```<code> <a href='imageInfo.php?id=<?php echo $image_id;?>'>Image Link</a>
</code>```

Or,

```<code> "<a href='imageInfo.php?id=". $image_id ."'>Image Link</a>"
</code>```

Body:
The link I must get to must be http://localhost:8088/imageInfo.php?id=4

 I started with this and no matter how I tried to escape I couldn't do it so any help would be appreciated

."<a href='imageInfo.php?id=<?php echo $image_id;?>'>".

Body:
It should be html code and should not be echoed again

 <a href='imageInfo.php?id=<?php echo $image_id;?>'>Image Link</a>

Or,

 "<a href='imageInfo.php?id=". $image_id ."'>Image Link</a>"


问:
Cobol technical demonstration
I'm working as a COBOL programmer - have a 6 months work experience - for a consulting firm . Today, with the rest the COBOL "department", I had a meeting with the new director of my company.

After an initial analysis made by the new team in charge, they noticed that, comparing to the other services/technologies our company has to offer - Java, C++, Objective-C, etc - COBOL was lacking "advertisement". He stated that whenever members of other teams are in-between projects they implement small demos which then can be shown to our clients whenever there is a presentation of our company. He gave examples of widgets for mobile devices in Objective-C, cool web-pages with HTML5, etc.
And noticed that there is nothing in COBOL like that. So he wants us to develop some kind of tool/app to show what our competences.

We already told him that COBOL is used under the hood, and doesn't have bells and whistles to show. Also that when hiring a COBOL programmer/analyst the most important for the client is that he shows he has "business logic" knowledge.

I know that the coding part is very important but after a two weeks introduction to the mainframe environment and to COBOL I was capable of doing my programming tasks easily. But with a 6 months experience working in a bank I find myself having to, nearly everyday, ask questions regarding "business logic" to the "gurus" just so that I don't end up changing the logic of the process when performing some maintenance task.

Can we really make something (tool/app) that shows or future clients that we have something different to offer than all the other company's which provide the same services? Or if not, is there anything that we can say to our manager so that he understands that COBOL is different from the other languages and it's purpose is not to display pretty graphics on the screen.

Thank you!

答:
I think you're absolutely right - the "curly brace" languages have had a lot of marketing of the brand from IBM , Oracle/Sun and Microsoft over the last 20 years.

Micro Focus is trying to do something about this. They just relaunched www.cobol.com which includes a nice set of video testimonial to the power of COBOL.

There's a great video available  showing some of the demos Micro Focus built as part of the development of the soon to be released "Visual COBOL R3" product. These demos include web services, rich browser-based clients, parallel processing and more (they aren't all shown in the video). Micro Focus will shortly be launching new resources for COBOL developers that will include these samples.

Title: Cobol technical demonstration