问:
Batch script for loop won't set variable correctly
I have following code but I see variables inside for loop are not set correctly. I tried using ! mark too still that doesn't work.

```<code>set dev_root=.\
set prod_root=..\prod\
setlocal disableDelayedExpansion

for /f "tokens=1* delims=\" %%A in ('forfiles /s /m *.txt /c "cmd /c echo @relpath"') do for %%F in (^"%%B) do (
    set "file=%%~F"
    set dev_filepath="%dev_root%%file%"
    set prod_filepath="%prod_root%%file%"

    if exist %prod_filepath% (
            fc /b %dev_filepath% %prod_filepath% > nul
        if errorlevel 1 (
            sd edit %prod_filepath%
            echo f | xcopy /f /y %dev_filepath% %prod_filepath%
        )
    ) else (
        echo f | xcopy /f /y %dev_filepath% %prod_filepath%
            sd add %prod_filepath%
    )
)

endlocal
</code>```

答:
There are several things that I would change. The main thing is to replace forfiles by xcopy /L to retrieve relative paths, because the latter is much faster. Here is the reworked code containing a lot of explanatory rem remarks:

@echo off
setlocal DisableDelayedExpansion

rem /* Use the quoted `set` syntax (the `""` do not become part of the value);
rem    do not include the trailing `\` here, do that later when building paths: */
set "dev_root=."
set "prod_root=..\prod"

rem /* You should change to a dedicated working directory, because you are only
rem    using relative paths later: */
cd /D "%~dp0." & rem // (this is the script's parent directory, just as an example)

rem /* Use `xcopy /L` rather than `forfiles` to retrieve list of relative paths;
rem    `/L` avoids to copy anything; the output is preceded by the drive letter
rem    (e. g., `C:`), which is split off by the `for /F` options; the summary text
rem    `?? File(s)` is not enumerated by `for /F` as it does not contain a `:`;
rem    the returned items are not preceded by `.\` and are not in between `""`: */
for /F "tokens=2 delims=:" %%F in ('xcopy /L /S /I "*.txt" "%TEMP%"') do (
    rem /* Build source and target paths; there is no interim variable `file`
    rem    necessary, use `%%F` immediately; include path separators `\` here;
    rem    at this point, delayed expansion is still disabled: */
    set "dev_filepath=%dev_root%\%%F"
    set "prod_filepath=%prod_root%\%%F"
    rem /* Now let us enable delayed expansion at this point in order to be able
    rem    to read the previously built file paths; avoid immediate `%` expansion
    rem    and `for` variables beyond this point in order not to lose `!`: */
    setlocal EnableDelayedExpansion
    rem /* Always use quoted file paths in order to avoid trouble with white-spaces
    rem    and other special characters (`^`, `&`, `(`, `)`,...): */
    if exist "!prod_filepath!" (
        rem /* You can use the `||` operator to execute commands only if the
        rem    previous one failed, hence its exit is not zero: */
        fc /B "!dev_filepath!" "!prod_filepath!" > nul || (
            rem // I do not know the `sd` command, so I keep it, with quoted path:
            sd edit "!prod_filepath!"
            rem /* For copying a single file, you should use `copy` rather than
            rem    `xcopy`, because the former does not prompt for file/directory
            rem    (`F`/`D`); keep in mind the prompt is language-dependent;
            rem    before copying, create the destination directory: */
            md "!prod_filepath!\.." 2> nul
            copy /Y "!dev_filepath!" "!prod_filepath!"
        )
    ) else (
        rem /* Again use `copy` rather than `xcopy` to copy a single file: */
        md "!prod_filepath!\.." 2> nul
        copy /Y "!dev_filepath!" "!prod_filepath!"
        rem // I do not know the `sd` command, so I keep it, but with quoted path:
        sd add "!prod_filepath!"
    )
    rem /* End environment localisation at the end of the loop iteration in order
    rem    to have delayed expansion disabled at the beginning of the next loop
    rem    iteration and to avoid execeeding the nesting limit of `setlocal`: */
    endlocal

endlocal
exit /B
```

Body:
I have following code but I see variables inside for loop are not set correctly. I tried using ! mark too still that doesn't work.

set dev_root=.\
set prod_root=..\prod\
setlocal disableDelayedExpansion

for /f "tokens=1* delims=\" %%A in ('forfiles /s /m *.txt /c "cmd /c echo @relpath"') do for %%F in (^"%%B) do (
    set "file=%%~F"
    set dev_filepath="%dev_root%%file%"
    set prod_filepath="%prod_root%%file%"

    if exist %prod_filepath% (
            fc /b %dev_filepath% %prod_filepath% > nul
        if errorlevel 1 (
            sd edit %prod_filepath%
            echo f | xcopy /f /y %dev_filepath% %prod_filepath%
        )
    ) else (
        echo f | xcopy /f /y %dev_filepath% %prod_filepath%
            sd add %prod_filepath%
    )
)

endlocal


来源: stackexchange

问:
Accessing properties in Google API Client Libraries (PHP)
I'm using the Google API Client Libraries for PHP (Beta) to make changes to a Google Sheet. I would like to access the first worksheet in the spreadsheet and then make changes to it.

```<code>$service = new Google_Service_Sheets($this->client);
$spreadsheet = $service->spreadsheets->get($google_sheet_id);
$sheets = $spreadsheet->getSheets();
</code>```

Using the code above I have an array of Google_Service_Sheets_Sheet objects. If I var_dump() the contents I can see the property I need in the protected array called modelData. I want to access the sheetId property.

```<code>...
["modelData":protected]=>
array(3) {
  ["properties"]=>
  array(5) {
    ["sheetId"]=>
    int(123456789)
    ["title"]=>
    string(15) "Page Popularity"
    ["index"]=>
    int(0)
    ["sheetType"]=>
    string(4) "GRID"
    ["gridProperties"]=>
    array(2) {
      ["rowCount"]=>
      int(4)
      ["columnCount"]=>
      int(4)
    }
  }
...
</code>```

I've tried everything I can think of including the standard PHP magic get/set syntax and nothing works.

```<code>$id = $sheets[0]->getSheetId(); // fails
$id = $sheets[0]->sheetId; // fails
$id = $sheets[0]->get('sheetId'); // fails
</code>```

How do I access properties on this object?

答:
You might want to check the Reference for Sheets API

In the image above, sheets (object) have properties(object) that contains sheetID (what you want to get). To make it short, it looks like this:

```<code>Sheets->properties->sheetID
</code>```

Or:

```<code>Sheets:{
    properties:{
         "sheetId": number,
         "title": string,
         "index": number,
         ........
 },
............
}
</code>```

Try checking the code from this post:

```<code>sheet_metadata = service.spreadsheets().get(spreadsheetId=spreadsheet_id).execute()
sheets = sheet_metadata.get('sheets', '')
title = sheets[0].get("properties", {}).get("title", "Sheet1")
sheet_id = sheets[0].get("properties", {}).get("sheetId", 0)
</code>```

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
I'm using the Google API Client Libraries for PHP (Beta) to make changes to a Google Sheet. I would like to access the first worksheet in the spreadsheet and then make changes to it.

$service = new Google_Service_Sheets($this->client);
$spreadsheet = $service->spreadsheets->get($google_sheet_id);
$sheets = $spreadsheet->getSheets();

Using the code above I have an array of Google_Service_Sheets_Sheet objects. If I var_dump() the contents I can see the property I need in the protected array called modelData. I want to access the sheetId property.

...
["modelData":protected]=>
array(3) {
  ["properties"]=>
  array(5) {
    ["sheetId"]=>
    int(123456789)
    ["title"]=>
    string(15) "Page Popularity"
    ["index"]=>
    int(0)
    ["sheetType"]=>
    string(4) "GRID"
    ["gridProperties"]=>
    array(2) {
      ["rowCount"]=>
      int(4)
      ["columnCount"]=>
      int(4)
    }
  }
...

I've tried everything I can think of including the standard PHP magic get/set syntax and nothing works.

$id = $sheets[0]->getSheetId(); // fails
$id = $sheets[0]->sheetId; // fails
$id = $sheets[0]->get('sheetId'); // fails

How do I access properties on this object?

Body:
You might want to check the Reference for Sheets API

In the image above, sheets (object) have properties(object) that contains sheetID (what you want to get). To make it short, it looks like this:

Sheets->properties->sheetID

Or:

Sheets:{
    properties:{
         "sheetId": number,
         "title": string,
         "index": number,
         ........
 },
............
}

Try checking the code from this post:

sheet_metadata = service.spreadsheets().get(spreadsheetId=spreadsheet_id).execute()
sheets = sheet_metadata.get('sheets', '')
title = sheets[0].get("properties", {}).get("title", "Sheet1")
sheet_id = sheets[0].get("properties", {}).get("sheetId", 0)

Hope this helps.


问:
Json parse to HashMap<ArrayList<>> throwing StackOverflowError in Libgdx?
My Json is:

```<code>{
    "objects":{
        "apple":[
            {"x":3, "y":5},
            {"x":6, "y":9}
        ],
        "car":[
            {"x":7, "y":9},
            {"x":5, "y":8}
        ]
     }
 }
</code>```

import com.badlogic.gdx.utils.Json;
import java.util.ArrayList;
import java.util.HashMap;

public class ClassA{
    public Integer x, y;
}

public class ClassB{
    public HashMap<String, ArrayList<ClassA>> objects;
}

public static void main(String[] args) {
    Json json = new Json();

    ClassB classB = json.fromJson(ClassB.class, "{\n" +
            "            \"objects\":{\n" +
            "                \"apple\":[\n" +
            "                    {\"x\":3, \"y\":5},\n" +
            "                    {\"x\":6, \"y\":9}\n" +
            "                ],\n" +
            "                \"car\":[\n" +
            "                    {\"x\":7, \"y\":9},\n" +
            "                    {\"x\":5, \"y\":8}\n" +
            "                ]\n" +
            "            }\n" +
            "        }");

    System.out.println(json.toJson(classB));
}
```

<p>I use "Libgdx", "json.fromJson" is works fine and when i call "json.toJson(classB)" an exception throws:</p>

<pre class="lang-java prettyprint-override"><code>Exception in thread "main" java.lang.StackOverflowError
at com.badlogic.gdx.utils.JsonWriter$OutputType.quoteValue(JsonWriter.java:187)
at com.badlogic.gdx.utils.JsonWriter.value(JsonWriter.java:88)
at com.badlogic.gdx.utils.Json.writeValue(Json.java:574)
at com.badlogic.gdx.utils.Json.writeFields(Json.java:290)
at com.badlogic.gdx.utils.Json.writeValue(Json.java:580)
at com.badlogic.gdx.utils.Json.writeFields(Json.java:290)
at com.badlogic.gdx.utils.Json.writeValue(Json.java:580)
...
</code>```

When i change "ArrayList" to String(etc) from HashMap in ClassB the code works fine.

So why an exception is thowing when i use "ArrayList" and how can i parse my json to ClassB instance?

答:
Yes, the StackOverflowException itself is a bug.

The libGDX' JSON class expects class type information in certain places, if it can't deduce the type by itself. In this regard it is much less tolerant than other, much larger libraries such as Gson.

see: https://github.com/libgdx/libgdx/wiki/Reading-%26-writing-JSON#writing-object-graphs

The easiest fix in your example is to write your ClassA instances as:

```<code>"    {\"class\": \"net.your.package.ClassA\", \"x\":3, \"y\":5},\n"
</code>```

The class name can be shortened, see Json.setElementType().

In general, as a best practice, for prototyping I recommend the opposite to your approach. Create the structure in code, then write to JSON to see how libGDX "perceives" your data structure, then read back from JSON to verify the output.

Side note: for most cases its recommended to use the libGDX containers, ObjectMap<> and Array<> in your example. Also, ClassA members can probably be int instead of Integer to avoid auto-boxing.

Body:
My Json is:

{
    "objects":{
        "apple":[
            {"x":3, "y":5},
            {"x":6, "y":9}
        ],
        "car":[
            {"x":7, "y":9},
            {"x":5, "y":8}
        ]
     }
 }

import com.badlogic.gdx.utils.Json;
import java.util.ArrayList;
import java.util.HashMap;

public class ClassA{
    public Integer x, y;
}

public class ClassB{
    public HashMap<String, ArrayList<ClassA>> objects;
}

public static void main(String[] args) {
    Json json = new Json();

    ClassB classB = json.fromJson(ClassB.class, "{\n" +
            "            \"objects\":{\n" +
            "                \"apple\":[\n" +
            "                    {\"x\":3, \"y\":5},\n" +
            "                    {\"x\":6, \"y\":9}\n" +
            "                ],\n" +
            "                \"car\":[\n" +
            "                    {\"x\":7, \"y\":9},\n" +
            "                    {\"x\":5, \"y\":8}\n" +
            "                ]\n" +
            "            }\n" +
            "        }");

    System.out.println(json.toJson(classB));
}

I use "Libgdx", "json.fromJson" is works fine and when i call "json.toJson(classB)" an exception throws:

Exception in thread "main" java.lang.StackOverflowError
at com.badlogic.gdx.utils.JsonWriter$OutputType.quoteValue(JsonWriter.java:187)
at com.badlogic.gdx.utils.JsonWriter.value(JsonWriter.java:88)
at com.badlogic.gdx.utils.Json.writeValue(Json.java:574)
at com.badlogic.gdx.utils.Json.writeFields(Json.java:290)
at com.badlogic.gdx.utils.Json.writeValue(Json.java:580)
at com.badlogic.gdx.utils.Json.writeFields(Json.java:290)
at com.badlogic.gdx.utils.Json.writeValue(Json.java:580)
...

When i change "ArrayList" to String(etc) from HashMap in ClassB the code works fine.

So why an exception is thowing when i use "ArrayList" and how can i parse my json to ClassB instance?

Body:
Yes, the StackOverflowException itself is a bug.

The libGDX' JSON class expects class type information in certain places, if it can't deduce the type by itself. In this regard it is much less tolerant than other, much larger libraries such as Gson.

see: https://github.com/libgdx/libgdx/wiki/Reading-%26-writing-JSON#writing-object-graphs

The easiest fix in your example is to write your ClassA instances as:

"    {\"class\": \"net.your.package.ClassA\", \"x\":3, \"y\":5},\n"

The class name can be shortened, see Json.setElementType().

In general, as a best practice, for prototyping I recommend the opposite to your approach. Create the structure in code, then write to JSON to see how libGDX "perceives" your data structure, then read back from JSON to verify the output.

Side note: for most cases its recommended to use the libGDX containers, ObjectMap<> and Array<> in your example. Also, ClassA members can probably be int instead of Integer to avoid auto-boxing.


问:
How to use gherkin-official
I am trying to use python to parse .feature files that are in gherkin syntax.

I ran pip install gherkin-official.

I can now run import gherkin but the object has no methods on it. I don't know how to use it and I can't find any documentation. How can I use this module to parse a file with its contents in gherkin syntax?

答:
You can take a look at the tests to see how it can be used: https://github.com/cucumber/gherkin-python/blob/master/test/gherkin_test.py

Looks like the basics start by importing:

```<code>from gherkin.token_scanner import TokenScanner
from gherkin.parser import Parser
</code>```

and then using it:

```<code>parser = Parser()
feature_file = parser.parse(TokenScanner("Feature: Foo"))
</code>```

Title: How to use gherkin-official

Body:
You can take a look at the tests to see how it can be used: https://github.com/cucumber/gherkin-python/blob/master/test/gherkin_test.py

Looks like the basics start by importing:

from gherkin.token_scanner import TokenScanner
from gherkin.parser import Parser

and then using it:

parser = Parser()
feature_file = parser.parse(TokenScanner("Feature: Foo"))


问:
Copy and paste data from multiple workbooks to a worksheet in another Workbook
I hope you can help. I currently have a piece of code see below. What I would like it to do is allow a user to select folder that contains workbooks. Then open each workbook select a sheet named "SearchCaseResults" from each workbook copy the data from each "SearchCaseResults" from the 2nd row down to the last used row, and paste this data into a worksheet called "Disputes" located in a different workbook in another folder.

So in PIC 1 you can see three Workbooks England, England_2 and England_3 each of these workbooks contain a worksheet "SearchCaseResults" So what I essentially need the code to do is loop through the folder open England workbook select the worksheet "SearchCaseResults" copy the data on this worksheet from row 2 to last used row then paste to the "Disputes" worksheet in the other workbook, in another folder, then select the next Workbook England_2 select the worksheet "SearchCaseResults" in this workbook copy the data on this worksheet from row 2 to last used row then PASTE IT BELOW the data copied from the previous worksheet(England) in the "Disputes" Worksheet and then continue with this copy and paste process until there are no more Workbooks left in the folder.

At the moment the code I have is opening up the workbooks, which is fine and selecting/activating the "SearchCaseResults" worksheet from each, but it is only coping cell A2 from the England sheets and then it is just pasting the data from the last sheet into the destination Worksheet.(I suspect the data from previous sheets is being pasted over) Can my code be amended to copy the data from each "SearhCaseResults" sheet from A2 to last used row and then Pasted into "Disputes" sheet underneath each other.

Here is my code so far as always any and all help is greatly appreciated.

CODE

```<code>Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "C:\Users\CONNELLP\Desktop\Claire Macro\Copy and Paste Disputes\Report Sheet\"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(Filename:=myPath & myFile)

    'Ensure Workbook has opened before moving on to next line of code
      DoEvents

    'Copy data on "SearchCaseResults" sheet to "Disputes" Sheet in other workbook

Dim lRow As Long

Dim ws2 As Worksheet

lRow = Range("A" & Rows.Count).End(xlUp).Row

Set y = Workbooks.Open("C:\Users\CONNELLP\Desktop\Claire Macro\Copy and Paste Disputes\Report Sheet")

Set ws2 = y.Sheets("Disputes")

      wb.Worksheets("SearchCasesResults").Range("A2" & lRow).Copy
      With y

      ws2.Range("A2").PasteSpecial
      End With

    'Save and Close Workbook
      wb.Close SaveChanges:=True

    'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
  Loop

'Message Box when tasks are completed
  MsgBox "Task Complete!"

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub
</code>```

I should point out that the code above is run from a separate workbook with a command button.

See pic 2

PIC 1

PIC 2

答:
Try this. I have corrected a few syntax errors. It's not clear if you are just copying data from column A, which I have assumed, but if not the copy line will need to be amended.</p>

```<code>Sub LoopAllExcelFilesInFolder()

'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim lRow As Long
Dim ws2 As Worksheet
Dim y As Workbook

'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

With FldrPicker
    .Title = "C:\Users\CONNELLP\Desktop\Claire Macro\Copy and Paste Disputes\Report Sheet\"
    .AllowMultiSelect = False
    If .Show <> -1 Then GoTo NextCode
    myPath = .SelectedItems(1) & "\"
End With

'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"

'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)

Set y = Workbooks.Open("C:\Users\CONNELLP\Desktop\Claire Macro\Copy and Paste Disputes\Report Sheet")
Set ws2 = y.Sheets("Disputes")

'Loop through each Excel file in folder
Do While myFile <> ""
    'Set variable equal to opened workbook
    Set wb = Workbooks.Open(Filename:=myPath & myFile)

    'Copy data on "SearchCaseResults" sheet to "Disputes" Sheet in other workbook
    With wb.Sheets("SearchCaseResults")
        lRow = .Range("A" & Rows.Count).End(xlUp).Row
        .Range("A2:M" & lRow).Copy ws2.Range("A" & Rows.Count).End(xlUp)(2)
    End With

    wb.Close SaveChanges:=True
    'Get next file name
    myFile = Dir
Loop

'Message Box when tasks are completed
MsgBox "Task Complete!"

ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True

End Sub
</code>```

Body:
I hope you can help. I currently have a piece of code see below. What I would like it to do is allow a user to select folder that contains workbooks. Then open each workbook select a sheet named "SearchCaseResults" from each workbook copy the data from each "SearchCaseResults" from the 2nd row down to the last used row, and paste this data into a worksheet called "Disputes" located in a different workbook in another folder.

So in PIC 1 you can see three Workbooks England, England_2 and England_3 each of these workbooks contain a worksheet "SearchCaseResults" So what I essentially need the code to do is loop through the folder open England workbook select the worksheet "SearchCaseResults" copy the data on this worksheet from row 2 to last used row then paste to the "Disputes" worksheet in the other workbook, in another folder, then select the next Workbook England_2 select the worksheet "SearchCaseResults" in this workbook copy the data on this worksheet from row 2 to last used row then PASTE IT BELOW the data copied from the previous worksheet(England) in the "Disputes" Worksheet and then continue with this copy and paste process until there are no more Workbooks left in the folder.

At the moment the code I have is opening up the workbooks, which is fine and selecting/activating the "SearchCaseResults" worksheet from each, but it is only coping cell A2 from the England sheets and then it is just pasting the data from the last sheet into the destination Worksheet.(I suspect the data from previous sheets is being pasted over) Can my code be amended to copy the data from each "SearhCaseResults" sheet from A2 to last used row and then Pasted into "Disputes" sheet underneath each other.

Here is my code so far as always any and all help is greatly appreciated.

CODE

Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "C:\Users\CONNELLP\Desktop\Claire Macro\Copy and Paste Disputes\Report Sheet\"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(Filename:=myPath & myFile)

    'Ensure Workbook has opened before moving on to next line of code
      DoEvents

    'Copy data on "SearchCaseResults" sheet to "Disputes" Sheet in other workbook

Dim lRow As Long

Dim ws2 As Worksheet

lRow = Range("A" & Rows.Count).End(xlUp).Row

Set y = Workbooks.Open("C:\Users\CONNELLP\Desktop\Claire Macro\Copy and Paste Disputes\Report Sheet")

Set ws2 = y.Sheets("Disputes")

      wb.Worksheets("SearchCasesResults").Range("A2" & lRow).Copy
      With y

      ws2.Range("A2").PasteSpecial
      End With

    'Save and Close Workbook
      wb.Close SaveChanges:=True

    'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
  Loop

'Message Box when tasks are completed
  MsgBox "Task Complete!"

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub

I should point out that the code above is run from a separate workbook with a command button.

See pic 2

PIC 1

PIC 2

Body:
Try this. I have corrected a few syntax errors. It's not clear if you are just copying data from column A, which I have assumed, but if not the copy line will need to be amended.

Sub LoopAllExcelFilesInFolder()

'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim lRow As Long
Dim ws2 As Worksheet
Dim y As Workbook

'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

With FldrPicker
    .Title = "C:\Users\CONNELLP\Desktop\Claire Macro\Copy and Paste Disputes\Report Sheet\"
    .AllowMultiSelect = False
    If .Show <> -1 Then GoTo NextCode
    myPath = .SelectedItems(1) & "\"
End With

'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"

'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)

Set y = Workbooks.Open("C:\Users\CONNELLP\Desktop\Claire Macro\Copy and Paste Disputes\Report Sheet")
Set ws2 = y.Sheets("Disputes")

'Loop through each Excel file in folder
Do While myFile <> ""
    'Set variable equal to opened workbook
    Set wb = Workbooks.Open(Filename:=myPath & myFile)

    'Copy data on "SearchCaseResults" sheet to "Disputes" Sheet in other workbook
    With wb.Sheets("SearchCaseResults")
        lRow = .Range("A" & Rows.Count).End(xlUp).Row
        .Range("A2:M" & lRow).Copy ws2.Range("A" & Rows.Count).End(xlUp)(2)
    End With

    wb.Close SaveChanges:=True
    'Get next file name
    myFile = Dir
Loop

'Message Box when tasks are completed
MsgBox "Task Complete!"

ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True

End Sub


问:
OCAML function in parameter of another function
I'm trying to pass a function as parameter to another function but I get an error at compilation.

```<code>Error: This function has type 'a -> 'a -> int
       It is applied to too many arguments; maybe you forgot a `;'.
</code>```

My code is:

```<code>let sort to_do my_list =
        let rec change to_do my_list verify newlist = match my_list with
                | Empty -> if verify = newlist then newlist else
                           change to_do newlist newlist Empty
                | Item (elem, next) -> change to_do my_list verify (compare to_do elem newlist)
        in
        change to_do my_list my_list Empty
;;

let rec compare to_do elem my_list = match my_list with
        | Empty -> (elem, my_list)
        | Item (elem1, Empty) -> if to_do elem elem1 > 0 then Item (elem, elem1) else
                                  Item (elem1, elem)
        | Item (elem1, next) -> compare to_do elem next
;;
</code>```

答:
In sort, you are referring to a function named compare. Since the other function compare is below, that will be resolved to Pervasives.compare : 'a -> 'a -> int (which takes two values and compare them).

Moving your compare function above sort may fix the problem.

Body:
I'm trying to pass a function as parameter to another function but I get an error at compilation.

Error: This function has type 'a -> 'a -> int
       It is applied to too many arguments; maybe you forgot a `;'.

My code is:

let sort to_do my_list =
        let rec change to_do my_list verify newlist = match my_list with
                | Empty -> if verify = newlist then newlist else
                           change to_do newlist newlist Empty
                | Item (elem, next) -> change to_do my_list verify (compare to_do elem newlist)
        in
        change to_do my_list my_list Empty
;;

let rec compare to_do elem my_list = match my_list with
        | Empty -> (elem, my_list)
        | Item (elem1, Empty) -> if to_do elem elem1 > 0 then Item (elem, elem1) else
                                  Item (elem1, elem)
        | Item (elem1, next) -> compare to_do elem next
;;


问:
Google Drive: algorithm to compute breadcrumb for a FS where nodes have multiple parents
I'm currently working with Google Drive API and I need to display a breadcrumb of a Google Drive file in my app. Google Drive is not a simple tree and has a particularity that a file/folder may have multiple parents. Google Drive does not have the concept of breadcrumb, so the only way to get a breadcrumb (actually a list of potential breadcrumbs) is to recurse over the list of parents.

I'm currently able to compute a list of all potential breadcrumbs in Scala:

```<code>type GoogleDriveBreadcrumb = List[GoogleDriveFile]

def getAllBreadcrumbs(fileId: String): Try[List[GoogleDriveBreadcrumb]] = Try {

  def getBreadcrumbsRecursive(currentFileId: String): List[GoogleDriveBreadcrumb] = {
    val file = fetchDriveFile(currentFileId)
    file.parentIds.flatMap { parentId =>
      getBreadcrumbsRecursive(parentId)
        .map(parentBreadcrumb => file :: parentBreadcrumb)
    }
  }

  getBreadcrumbsRecursive(fileId)
}
</code>```

This works fine but can be quite expensive and not really usable because:

I don't actually need all the breadcrumbs, I need the most appropriate one because I know in which "context" to compute the breadcrumb. I'd like to be able to provide a rootFolderId parameter to this method, so that it will only return a single breadcrumb (the one having rootFolderId as parent, and this breadcrumb will be truncated at the level of the rootFolderId which means the returned breadcrumb should not include parents of rootFolderId. If rootFolderId is not found in any breadcrumb, the method can return the current file only

It will always compute all the breadcrumbs in all cases. I'd like the computation to be lazy and to stop as soon as a breadcrumb containing rootFolderId is found.

I'd like my method to have this signature:

```<code>def getBreadcrumb(fileId: String,rootFolderId: String): Try[Option[GoogleDriveBreadcrumb]]
</code>```

Now let's imagine I have a this Drive filesystem where File has 3 potential breadcrumbs:

```<code>File < Folder1 < Folder2 < Folder3
File < Folder4 < Folder5 < Folder6
File < Folder7 < Folder8 < Folder9
</code>```

getBreadcrumb(file,folder5Id) should return File < Folder4 < Folder5

getBreadcrumb(file,folder7Id) should return File < Folder7

getBreadcrumb(file,badFolderId) should return File

Any idea on how to rework my algorithm to achieve this goal, so that the algorithm is also efficient (stop as soon as the correct breadcrumb is found)

Thanks

I'm tagging this question with Scala,Java,Javascript because these are languages I am used to. I'd rather like a Scala-based implementation but I'm open for other languages as long as I can understand the solution.

答:
You could try starting from the file then going to the root folder.

If you are using v2, you'll repeat the loop until isRoot becomes true:

File result:

```<code> "parents": [
  {
   "kind": "drive#parentReference",
   "id": "FILEID",
   ........................
   "isRoot": false
  }
 ]
</code>```

Root result:

```<code> "parents": [
  {
   "kind": "drive#parentReference",
   "id": "FILEID",
   ........................
   "isRoot": true
  }
 ]
</code>```

If you are using v3:

If you are using v3, you'll repeat the query loop until parents becomes null or the response does not contain parents object.

File result:

```<code>{
 "id": "FILEID",
 "parents": [
  "PARENTID"
 ]
}
</code>```

Root Result:

```<code>{
 "id": "ROOTID"
}
</code>```

You can also check this Google Apps Script tutorial on how listing it as a file tree (but in your case just the path from file to root)

Hope this helps.

Body:
I'm currently working with Google Drive API and I need to display a breadcrumb of a Google Drive file in my app. Google Drive is not a simple tree and has a particularity that a file/folder may have multiple parents. Google Drive does not have the concept of breadcrumb, so the only way to get a breadcrumb (actually a list of potential breadcrumbs) is to recurse over the list of parents.

I'm currently able to compute a list of all potential breadcrumbs in Scala:

type GoogleDriveBreadcrumb = List[GoogleDriveFile]

def getAllBreadcrumbs(fileId: String): Try[List[GoogleDriveBreadcrumb]] = Try {

  def getBreadcrumbsRecursive(currentFileId: String): List[GoogleDriveBreadcrumb] = {
    val file = fetchDriveFile(currentFileId)
    file.parentIds.flatMap { parentId =>
      getBreadcrumbsRecursive(parentId)
        .map(parentBreadcrumb => file :: parentBreadcrumb)
    }
  }

  getBreadcrumbsRecursive(fileId)
}

This works fine but can be quite expensive and not really usable because:

I don't actually need all the breadcrumbs, I need the most appropriate one because I know in which "context" to compute the breadcrumb. I'd like to be able to provide a rootFolderId parameter to this method, so that it will only return a single breadcrumb (the one having rootFolderId as parent, and this breadcrumb will be truncated at the level of the rootFolderId which means the returned breadcrumb should not include parents of rootFolderId. If rootFolderId is not found in any breadcrumb, the method can return the current file only

It will always compute all the breadcrumbs in all cases. I'd like the computation to be lazy and to stop as soon as a breadcrumb containing rootFolderId is found.

I'd like my method to have this signature:

def getBreadcrumb(fileId: String,rootFolderId: String): Try[Option[GoogleDriveBreadcrumb]]

Now let's imagine I have a this Drive filesystem where File has 3 potential breadcrumbs:

File < Folder1 < Folder2 < Folder3
File < Folder4 < Folder5 < Folder6
File < Folder7 < Folder8 < Folder9

getBreadcrumb(file,folder5Id) should return File < Folder4 < Folder5

getBreadcrumb(file,folder7Id) should return File < Folder7

getBreadcrumb(file,badFolderId) should return File

Any idea on how to rework my algorithm to achieve this goal, so that the algorithm is also efficient (stop as soon as the correct breadcrumb is found)

Thanks

I'm tagging this question with Scala,Java,Javascript because these are languages I am used to. I'd rather like a Scala-based implementation but I'm open for other languages as long as I can understand the solution.

Body:
You could try starting from the file then going to the root folder.

If you are using v2, you'll repeat the loop until isRoot becomes true:

File result:

 "parents": [
  {
   "kind": "drive#parentReference",
   "id": "FILEID",
   ........................
   "isRoot": false
  }
 ]

Root result:

 "parents": [
  {
   "kind": "drive#parentReference",
   "id": "FILEID",
   ........................
   "isRoot": true
  }
 ]

If you are using v3:

If you are using v3, you'll repeat the query loop until parents becomes null or the response does not contain parents object.

File result:

{
 "id": "FILEID",
 "parents": [
  "PARENTID"
 ]
}

Root Result:

{
 "id": "ROOTID"
}

You can also check this Google Apps Script tutorial on how listing it as a file tree (but in your case just the path from file to root)

Hope this helps.


问:
Total size of the contents of all the files in a directory
When I use ls or du, I get the amount of disk space each file is occupying.

I need the sum total of all the data in files and subdirectories I would get if I opened each file and counted the bytes. Bonus points if I can get this without opening each file and counting.

答:
There are at least three ways to get the "sum total of all the data in files and subdirectories" in bytes that work in both Linux/Unix and Git Bash for Windows, listed below in order from fastest to slowest on average. For your reference, they were executed at the root of a fairly deep file system (docroot in a Magento 2 Enterprise installation comprising 71,158 files in 30,027 directories).

1.

```<code>$ time find -type f -printf '%s\n' | awk '{ total += $1 }; END { print total" bytes" }'
748660546 bytes

real    0m0.221s
user    0m0.068s
sys     0m0.160s
</code>```

2.

```<code>$ time echo `find -type f -print0 | xargs -0 stat --format=%s | awk '{total+=$1} END {print total}'` bytes
748660546 bytes

real    0m0.256s
user    0m0.164s
sys     0m0.196s
</code>```

3.

```<code>$ time echo `find -type f -exec du -bc {} + | grep -P "\ttotal$" | cut -f1 | awk '{ total += $1 }; END { print total }'` bytes
748660546 bytes

real    0m0.553s
user    0m0.308s
sys     0m0.416s
</code>```

These two also work, but they rely on commands that don't exist on Git Bash for Windows:

1.

```<code>$ time echo `find -type f -printf "%s + " | dc -e0 -f- -ep` bytes
748660546 bytes

real    0m0.233s
user    0m0.116s
sys     0m0.176s
</code>```

2.

```<code>$ time echo `find -type f -printf '%s\n' | paste -sd+ | bc` bytes
748660546 bytes

real    0m0.242s
user    0m0.104s
sys     0m0.152s
</code>```

If you only want the total for the current directory, then add -maxdepth 1 to find.

Note that some of the suggested solutions don't return accurate results, so I would stick with the solutions above instead.

```<code>$ du -sbh
832M    .

$ ls -lR | grep -v '^d' | awk '{total += $5} END {print "Total:", total}'
Total: 583772525

$ find . -type f | xargs stat --format=%s | awk '{s+=$1} END {print s}'
xargs: unmatched single quote; by default quotes are special to xargs unless you use the -0 option
4390471

$ ls -l| grep -v '^d'| awk '{total = total + $5} END {print "Total" , total}'
Total 968133
</code>```

Body:
There are at least three ways to get the "sum total of all the data in files and subdirectories" in bytes that work in both Linux/Unix and Git Bash for Windows, listed below in order from fastest to slowest on average. For your reference, they were executed at the root of a fairly deep file system (docroot in a Magento 2 Enterprise installation comprising 71,158 files in 30,027 directories).

1.

$ time find -type f -printf '%s\n' | awk '{ total += $1 }; END { print total" bytes" }'
748660546 bytes

real    0m0.221s
user    0m0.068s
sys     0m0.160s

2.

$ time echo `find -type f -print0 | xargs -0 stat --format=%s | awk '{total+=$1} END {print total}'` bytes
748660546 bytes

real    0m0.256s
user    0m0.164s
sys     0m0.196s

3.

$ time echo `find -type f -exec du -bc {} + | grep -P "\ttotal$" | cut -f1 | awk '{ total += $1 }; END { print total }'` bytes
748660546 bytes

real    0m0.553s
user    0m0.308s
sys     0m0.416s

These two also work, but they rely on commands that don't exist on Git Bash for Windows:

1.

$ time echo `find -type f -printf "%s + " | dc -e0 -f- -ep` bytes
748660546 bytes

real    0m0.233s
user    0m0.116s
sys     0m0.176s

2.

$ time echo `find -type f -printf '%s\n' | paste -sd+ | bc` bytes
748660546 bytes

real    0m0.242s
user    0m0.104s
sys     0m0.152s

If you only want the total for the current directory, then add -maxdepth 1 to find.

Note that some of the suggested solutions don't return accurate results, so I would stick with the solutions above instead.

$ du -sbh
832M    .

$ ls -lR | grep -v '^d' | awk '{total += $5} END {print "Total:", total}'
Total: 583772525

$ find . -type f | xargs stat --format=%s | awk '{s+=$1} END {print s}'
xargs: unmatched single quote; by default quotes are special to xargs unless you use the -0 option
4390471

$ ls -l| grep -v '^d'| awk '{total = total + $5} END {print "Total" , total}'
Total 968133


问:
In what cases superclass shouldn't be abstract?
In this thread I found some interesting moment, If class uses only as superclass there isn't rule to make it abstract. Why so?

Thanks

答:
If the class is complete and usable it makes sense that you should be able to instantiate and use the class, even if the user decides to extend it later.

The class should only be abstract if the user needs to implement some logic to make it functional within the framework in which it is being used i.e. where the class designer does not know the exact implementation details of how the class will be used, like the template or command design patterns for example.

ContentLicense: CC BY-SA 2.5


问:
Is it possible to close an infowindow on certain condition
Infowindow should only show when you hover on marker. It should go away when you move your mouse from marker.
It should only stay if you click on the marker. and close on clicking close button of infowindow.</p>

答:
You can try using the using the google.maps.event.addListener:

JavaScript within the browser is event driven, meaning that JavaScript responds to interactions by generating events, and expects a program to listen to interesting events. There are two types of events:

User events (such as "click" mouse events) are propagated from the DOM to the Google Maps JavaScript API. These events are separate and distinct from standard DOM events.

MVC state change notifications reflect changes in Maps JavaScript API objects and are named using a property_changed convention.

Each Maps JavaScript API object exports a number of named events. Programs interested in certain events will register JavaScript event listeners for those events and execute code when those events are received by calling addListener() to register event handlers on the object.

You can try using the code in this post:

```<code>var geocoder;
var map;

function initialize() {
    var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
        center: new google.maps.LatLng(37.4419, -122.1419),
        zoom: 13,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

setMarkers(map,locations);

}
google.maps.event.addDomListener(window, "load", initialize);
var locations = [
  ['Bondi Beach', -33.890542, 151.274856,,, 'Bondi Beach', 4],
  ['Coogee Beach', -33.923036, 151.259052,,,'Coogee Beach', 5],
  ['Cronulla Beach', -34.028249, 151.157507,,,'Cronulla Beach', 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187,,, 'Manly Beach', 2],
  ['Maroubra Beach', -33.950198, 151.259302,,,'Maroubra Beach', 1]
];
function setMarkers(map, locations) {
    var bounds = new google.maps.LatLngBounds();
    for (var i = 0; i < locations.length; i++) {
        var item = locations[i];

        var myLatLng = new google.maps.LatLng(item[1], item[2]);
        bounds.extend(myLatLng);
        var address = item[5];

        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
        });

        var content = address;

        var infowindow = new google.maps.InfoWindow()

        google.maps.event.addListener(marker, 'mouseover', (function (marker, content, infowindow) {
            return function () {
                infowindow.setContent(content);
                infowindow.open(map, marker);
            };
        })(marker, content, infowindow));
        google.maps.event.addListener(marker, 'mouseout', (function (marker, content, infowindow) {
            return function () {
                infowindow.close();
            };
        })(marker, content, infowindow));

    }
    map.fitBounds(bounds);
}
</code>```

This can also be found in jsfiddle. It will work properly as long as your event listener doesn't conflict with other listeners.

Hope this helps.

Body:
You can try using the using the google.maps.event.addListener:

JavaScript within the browser is event driven, meaning that JavaScript responds to interactions by generating events, and expects a program to listen to interesting events. There are two types of events:

User events (such as "click" mouse events) are propagated from the DOM to the Google Maps JavaScript API. These events are separate and distinct from standard DOM events.

MVC state change notifications reflect changes in Maps JavaScript API objects and are named using a property_changed convention.

Each Maps JavaScript API object exports a number of named events. Programs interested in certain events will register JavaScript event listeners for those events and execute code when those events are received by calling addListener() to register event handlers on the object.

You can try using the code in this post:

var geocoder;
var map;

function initialize() {
    var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
        center: new google.maps.LatLng(37.4419, -122.1419),
        zoom: 13,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

setMarkers(map,locations);

}
google.maps.event.addDomListener(window, "load", initialize);
var locations = [
  ['Bondi Beach', -33.890542, 151.274856,,, 'Bondi Beach', 4],
  ['Coogee Beach', -33.923036, 151.259052,,,'Coogee Beach', 5],
  ['Cronulla Beach', -34.028249, 151.157507,,,'Cronulla Beach', 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187,,, 'Manly Beach', 2],
  ['Maroubra Beach', -33.950198, 151.259302,,,'Maroubra Beach', 1]
];
function setMarkers(map, locations) {
    var bounds = new google.maps.LatLngBounds();
    for (var i = 0; i < locations.length; i++) {
        var item = locations[i];

        var myLatLng = new google.maps.LatLng(item[1], item[2]);
        bounds.extend(myLatLng);
        var address = item[5];

        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
        });

        var content = address;

        var infowindow = new google.maps.InfoWindow()

        google.maps.event.addListener(marker, 'mouseover', (function (marker, content, infowindow) {
            return function () {
                infowindow.setContent(content);
                infowindow.open(map, marker);
            };
        })(marker, content, infowindow));
        google.maps.event.addListener(marker, 'mouseout', (function (marker, content, infowindow) {
            return function () {
                infowindow.close();
            };
        })(marker, content, infowindow));

    }
    map.fitBounds(bounds);
}

This can also be found in jsfiddle. It will work properly as long as your event listener doesn't conflict with other listeners.

Hope this helps.


问:
how to update a column containing date(yyyy-mm-dd) into weekday(wd) or weekend(we) in python using pandas
i have a CSV file which contains userid and other user related data in columns and one of which is date , now i want to convert this date column to whether that date is weekend(we) or weekday(wd) which helps me in some Machine learning training ,thank you .</p>

答:
I think you need numpy.where with dayofweek:

```<code>df['day'] = np.where(df['Date'].dt.dayofweek > 4, 'we', 'wd')
</code>```

Sample:

```<code>rng = pd.date_range('2017-04-03', periods=10)
df = pd.DataFrame({'Date': rng, 'a': range(10)})

df['day'] = np.where(df['Date'].dt.dayofweek > 4, 'we', 'wd')
print (df)
        Date  a day
0 2017-04-03  0  wd
1 2017-04-04  1  wd
2 2017-04-05  2  wd
3 2017-04-06  3  wd
4 2017-04-07  4  wd
5 2017-04-08  5  we
6 2017-04-09  6  we
7 2017-04-10  7  wd
8 2017-04-11  8  wd
9 2017-04-12  9  wd
</code>```

If need overwrite column:

```<code>df['Date'] = np.where(df['Date'].dt.dayofweek > 4, 'we', 'wd')
print (df)
  Date  a
0   wd  0
1   wd  1
2   wd  2
3   wd  3
4   wd  4
5   we  5
6   we  6
7   wd  7
8   wd  8
9   wd  9
</code>```

For convert to datetime in read_csv use parameter parse_dates:

```<code>import pandas as pd
from pandas.compat import StringIO

temp=u"""datetime,YEAR
2016-01-19,2016.0
2016-01-20,2016.0
2016-01-21,2016.0
2016-01-22,2016.0
2016-01-23,2016.0
2017-02-02,2017.0"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
df = pd.read_csv(StringIO(temp),  parse_dates=[0])

print (df)
    datetime    YEAR
0 2016-01-19  2016.0
1 2016-01-20  2016.0
2 2016-01-21  2016.0
3 2016-01-22  2016.0
4 2016-01-23  2016.0
5 2017-02-02  2017.0

print (df.dtypes)
datetime    datetime64[ns]
YEAR               float64
dtype: object
</code>```

Body:
I think you need numpy.where with dayofweek:

df['day'] = np.where(df['Date'].dt.dayofweek > 4, 'we', 'wd')

Sample:

rng = pd.date_range('2017-04-03', periods=10)
df = pd.DataFrame({'Date': rng, 'a': range(10)})

df['day'] = np.where(df['Date'].dt.dayofweek > 4, 'we', 'wd')
print (df)
        Date  a day
0 2017-04-03  0  wd
1 2017-04-04  1  wd
2 2017-04-05  2  wd
3 2017-04-06  3  wd
4 2017-04-07  4  wd
5 2017-04-08  5  we
6 2017-04-09  6  we
7 2017-04-10  7  wd
8 2017-04-11  8  wd
9 2017-04-12  9  wd

If need overwrite column:

df['Date'] = np.where(df['Date'].dt.dayofweek > 4, 'we', 'wd')
print (df)
  Date  a
0   wd  0
1   wd  1
2   wd  2
3   wd  3
4   wd  4
5   we  5
6   we  6
7   wd  7
8   wd  8
9   wd  9

For convert to datetime in read_csv use parameter parse_dates:

import pandas as pd
from pandas.compat import StringIO

temp=u"""datetime,YEAR
2016-01-19,2016.0
2016-01-20,2016.0
2016-01-21,2016.0
2016-01-22,2016.0
2016-01-23,2016.0
2017-02-02,2017.0"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
df = pd.read_csv(StringIO(temp),  parse_dates=[0])

print (df)
    datetime    YEAR
0 2016-01-19  2016.0
1 2016-01-20  2016.0
2 2016-01-21  2016.0
3 2016-01-22  2016.0
4 2016-01-23  2016.0
5 2017-02-02  2017.0

print (df.dtypes)
datetime    datetime64[ns]
YEAR               float64
dtype: object


问:
Maps not loading when app compiled on Windows
I have a problem with a simple map viewer app. For some reason my app works fine when I upload it to an Android device via an iMac, but when I upload the exact same app from my Windows computer it loads the MapActivity, but no map tiles. So I do see the raster, and can move it around. Just no tiles.

I have the feeling it's something stupid I overlooked, but those things are often the most annoying to find.

I also checked the Google Maps API key, but came to the conclusion that debugging keys are the same on different computers, so that didn't matter.

Any ideas?

答: Ok, I did the sign up process another time and got another key this time. Now it works. I don't know what went wrong before.


问:
Line breaks in R Markdown text (not code blocks)
Using the tufte_template rmarkdown file, I am trying to make a new paragraph (like \newthought{}, but no caps.) I use two spaces, denoted here by *:

```<code># Introduction

The Tufte-\LaTeX\ [^tufte_latex] document**
**
classes define a style similar to the style Edward Tufte uses in his books...
</code>```

but get this result:

I have tried \n in place of the second pair of spaces (**) as well, but pandoc throws an error.

```<code>pandoc.exe: Error producing PDF from TeX source
Error: pandoc document conversion failed with error 43
</code>```

Finally, I tried using a
 tag, but that seems to have no effect whatsoever - it doesn't print the text or a break to the PDF.

I would like a new paragraph, without the indentation, similar to \newthought{}, but without the capitalization...is there a way?

Update 1 with sessionInfo():

```<code>> sessionInfo()
R version 3.1.2 (2014-10-31)
Platform: x86_64-w64-mingw32/x64 (64-bit)

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] digest_0.6.8    htmltools_0.2.6 rmarkdown_0.5.1 tools_3.1.2     yaml_2.1.13
</code>```

Update 2

This seems to be a problem I encounter specifically when using the Tufte template:

答:
It's a rather old question, but I post an answer since it's the first hit when googling for "line breaks in rmarkdown".

If compiling to pdf, you can use latex macros. Substitute the ** in the new line with \hfill\break:

```<code># Introduction

The Tufte-\LaTeX\ [^tufte_latex] document**
\hfill\break
classes define a style similar to the style Edward Tufte uses in his books...
</code>```

Body:
Using the tufte_template rmarkdown file, I am trying to make a new paragraph (like \newthought{}, but no caps.) I use two spaces, denoted here by *:

# Introduction

The Tufte-\LaTeX\ [^tufte_latex] document**
**
classes define a style similar to the style Edward Tufte uses in his books...

but get this result:

I have tried \n in place of the second pair of spaces (**) as well, but pandoc throws an error.

pandoc.exe: Error producing PDF from TeX source
Error: pandoc document conversion failed with error 43

Finally, I tried using a
 tag, but that seems to have no effect whatsoever - it doesn't print the text or a break to the PDF.

I would like a new paragraph, without the indentation, similar to \newthought{}, but without the capitalization...is there a way?

Update 1 with sessionInfo():

> sessionInfo()
R version 3.1.2 (2014-10-31)
Platform: x86_64-w64-mingw32/x64 (64-bit)

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] digest_0.6.8    htmltools_0.2.6 rmarkdown_0.5.1 tools_3.1.2     yaml_2.1.13

Update 2

This seems to be a problem I encounter specifically when using the Tufte template:

Body:
It's a rather old question, but I post an answer since it's the first hit when googling for "line breaks in rmarkdown".

If compiling to pdf, you can use latex macros. Substitute the ** in the new line with \hfill\break:

# Introduction

The Tufte-\LaTeX\ [^tufte_latex] document**
\hfill\break
classes define a style similar to the style Edward Tufte uses in his books...

ContentLicense: CC BY-SA 4.0


问:
Map path between two points Ionic 2 offline
How to get a path offline between two points using my actual location ?

Is there a way to get it ? i read there is a library called Leaflet which can run offfline.

答:
You might use de geolocalization native plugin and some javascript to paint a line between two points. I don't know about leaflet, but opne layers is a good tool to create offline maps.

https://ionicframework.com/docs/v2/native/geolocation/ .

http://openlayers.org/

I'm too trying to do something with offline map in ionic. Please post whatever you do with this resorcer and I'll do the same :)


答:
Following from @aioobe - Think of the following situation.

In a company, you have a position called Accountant. Now, let's say that hypothetically you have someone that specializes in auditing, and we say his title is Auditor. Now, the company has 100 accountants, but only 4 Auditors. In this case, you would want to instantiate both the Accountant and Auditor classes, even though Accountant is a super-class of Auditor.

Title: In what cases superclass shouldn't be abstract?

Body:
In this thread I found some interesting moment, If class uses only as superclass there isn't rule to make it abstract. Why so?

Thanks


问:
Shell script not working with crontab
I have a script that scans all the directories and subdirectories for those with "RC" in their name and delete all older then 40 days but always leave the last one even if it is older than 40 days.

The problem I am heaving is that if I run the script by hand ./cronJob.sh it works as it should. But when I put it on a crontab list it does not delete directories, but only outputs two lines in log.

```<code>#!/bin/bash

datum=$(date -I)
MOUNTLOG=/var/log/softwareRC/

FIND=/bin/find;

deleteDir(){
    echo "-------- START $parent --------" >> $MOUNTLOG/$datum.log
    dname=$(/usr/bin/dirname $1)
    temp="${dname%\s.*}"
    temp=(${temp[@]})
    parent="${temp[0]}"
    dirNum="$($FIND $parent -maxdepth 1 -name *RC* -type d -print | wc -l)"
    najnovejsi="$($FIND $parent -maxdepth 1 -name *RC* -type d -print | sort | tail -n 1)"
    if [ $dirNum -gt 1 ]; then
            $FIND "$parent" -path "$najnovejsi" -prune -o -name *RC* -mtime +40 -print -exec rm -r "{}" \; >> $MOUNTLOG/$datum.log
    fi;
    echo "-------- END $parent --------" >> $MOUNTLOG/$datum.log
}

declare -i skipDir=1

while true
do
    oldest=$($FIND -type d -name *RC* -mtime +40 -printf '%T+ %p\n' | sort -r | tail -n $skipDir | head -n 1)
#       echo najstarejsi $oldest
    dironly=$(echo $oldest | cut -d' ' -f 2-)
    deleteDir "$dironly"

#       echo $skipDir $dironly
    /bin/sleep 1
    if [ "$dironly" = "$testna" ]; then
            break
    else
            testna=$(echo $oldest | cut -d' ' -f 2-)
            let "skipDir++"
    fi;
#       echo primerjava $testna
done
</code>```

Crontab job

```<code>0 2 * * * /mnt/local/TempDrive/Software_RC/.cleanOld.sh
</code>```

Log output

```<code>[root@SambaServer softwareRC]# cat 2017-03-11.log
-------- START  --------
-------- END  --------
</code>```

答:
Thank you very much for your help and sorry for late reply. I have figured out what was wrong.

The problem was in the below line. I had to enter the whole path to the location where the script is ran from.

Before:

```<code>oldest=$($FIND -type d -name *RC* -mtime +40 -printf '%T+ %p\n' | sort -r | tail -n $skipDir | head -n 1)
</code>```

After:

```<code>oldest=$($FIND /mnt/local/TempDrive/Software_RC -type d -name *RC* -mtime +40 -printf '%T+ %p\n' | sort -r | tail -n $skipDir | head -n 1)
</code>```

This is the working code.

```<code>#!/bin/bash

datum=$(date -I)
MOUNTLOG=/var/log/softwareRC/

exec > $MOUNTLOG/$datum.log 2>&1

FIND=/bin/find;

deleteDir(){
    echo "-------- START $parent --------" >> $MOUNTLOG/$datum.log
    dname=$(/usr/bin/dirname $1)
    temp="${dname%\s.*}"
    temp=(${temp[@]})
    parent="${temp[0]}"
    dirNum="$($FIND $parent -maxdepth 1 -name *RC* -type d -print | wc -l)"
    najnovejsi="$($FIND $parent -maxdepth 1 -name *RC* -type d -print | sort | tail -n 1)"
    if [ $dirNum -gt 1 ]; then
            $FIND "$parent" -path "$najnovejsi" -prune -o -name *RC* -mtime +40 -print -exec rm -r "{}" \; >> $MOUNTLOG/$datum.log
    fi;
    echo "-------- END $parent --------" >> $MOUNTLOG/$datum.log
}

declare -i skipDir=1

while true
do
    oldest=$($FIND /mnt/local/TempDrive/Software_RC -type d -name *RC* -mtime +40 -printf '%T+ %p\n' | sort -r | tail -n $skipDir | head -n 1)
    dironly=$(echo $oldest | cut -d' ' -f 2-)
    deleteDir "$dironly"

    /bin/sleep 1
    if [ "$dironly" = "$testna" ]; then
            break
    else
            testna=$(echo $oldest | cut -d' ' -f 2-)
            let "skipDir++"
    fi;
done
</code>```

Title: Shell script not working with crontab

Body:
I have a script that scans all the directories and subdirectories for those with "RC" in their name and delete all older then 40 days but always leave the last one even if it is older than 40 days.

The problem I am heaving is that if I run the script by hand ./cronJob.sh it works as it should. But when I put it on a crontab list it does not delete directories, but only outputs two lines in log.

#!/bin/bash

datum=$(date -I)
MOUNTLOG=/var/log/softwareRC/

FIND=/bin/find;

deleteDir(){
    echo "-------- START $parent --------" >> $MOUNTLOG/$datum.log
    dname=$(/usr/bin/dirname $1)
    temp="${dname%\s.*}"
    temp=(${temp[@]})
    parent="${temp[0]}"
    dirNum="$($FIND $parent -maxdepth 1 -name *RC* -type d -print | wc -l)"
    najnovejsi="$($FIND $parent -maxdepth 1 -name *RC* -type d -print | sort | tail -n 1)"
    if [ $dirNum -gt 1 ]; then
            $FIND "$parent" -path "$najnovejsi" -prune -o -name *RC* -mtime +40 -print -exec rm -r "{}" \; >> $MOUNTLOG/$datum.log
    fi;
    echo "-------- END $parent --------" >> $MOUNTLOG/$datum.log
}

declare -i skipDir=1

while true
do
    oldest=$($FIND -type d -name *RC* -mtime +40 -printf '%T+ %p\n' | sort -r | tail -n $skipDir | head -n 1)
#       echo najstarejsi $oldest
    dironly=$(echo $oldest | cut -d' ' -f 2-)
    deleteDir "$dironly"

#       echo $skipDir $dironly
    /bin/sleep 1
    if [ "$dironly" = "$testna" ]; then
            break
    else
            testna=$(echo $oldest | cut -d' ' -f 2-)
            let "skipDir++"
    fi;
#       echo primerjava $testna
done

Crontab job

0 2 * * * /mnt/local/TempDrive/Software_RC/.cleanOld.sh

Log output

[root@SambaServer softwareRC]# cat 2017-03-11.log
-------- START  --------
-------- END  --------

Body:
Thank you very much for your help and sorry for late reply. I have figured out what was wrong.

The problem was in the below line. I had to enter the whole path to the location where the script is ran from.

Before:

oldest=$($FIND -type d -name *RC* -mtime +40 -printf '%T+ %p\n' | sort -r | tail -n $skipDir | head -n 1)

After:

oldest=$($FIND /mnt/local/TempDrive/Software_RC -type d -name *RC* -mtime +40 -printf '%T+ %p\n' | sort -r | tail -n $skipDir | head -n 1)

This is the working code.

#!/bin/bash

datum=$(date -I)
MOUNTLOG=/var/log/softwareRC/

exec > $MOUNTLOG/$datum.log 2>&1

FIND=/bin/find;

deleteDir(){
    echo "-------- START $parent --------" >> $MOUNTLOG/$datum.log
    dname=$(/usr/bin/dirname $1)
    temp="${dname%\s.*}"
    temp=(${temp[@]})
    parent="${temp[0]}"
    dirNum="$($FIND $parent -maxdepth 1 -name *RC* -type d -print | wc -l)"
    najnovejsi="$($FIND $parent -maxdepth 1 -name *RC* -type d -print | sort | tail -n 1)"
    if [ $dirNum -gt 1 ]; then
            $FIND "$parent" -path "$najnovejsi" -prune -o -name *RC* -mtime +40 -print -exec rm -r "{}" \; >> $MOUNTLOG/$datum.log
    fi;
    echo "-------- END $parent --------" >> $MOUNTLOG/$datum.log
}

declare -i skipDir=1

while true
do
    oldest=$($FIND /mnt/local/TempDrive/Software_RC -type d -name *RC* -mtime +40 -printf '%T+ %p\n' | sort -r | tail -n $skipDir | head -n 1)
    dironly=$(echo $oldest | cut -d' ' -f 2-)
    deleteDir "$dironly"

    /bin/sleep 1
    if [ "$dironly" = "$testna" ]; then
            break
    else
            testna=$(echo $oldest | cut -d' ' -f 2-)
            let "skipDir++"
    fi;
done


问:
TYPO3 fluid translate view helper: No output when using "%0A%0A" in xlf file
In my fluid Template I am using

{f:translate(key:'LLL:path/to/file/locallang.xlf:Test', arguments: {0: 'Test'})}

Positive test case

Content of locallang.xlf:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xliff version="1.0">
    <file source-language="en" datatype="plaintext" original="messages" date="2016-12-06T14:00:00Z" product-name="">
        <header/>
        <body>
            <trans-unit id="Test" xml:space="preserve">
                <source><![CDATA[mailto:info@example.org?Subject=%1$s&Body=Hello%0A]]></source>
            </trans-unit>
        </body>
    </file>
</xliff>
</code>```

Output:

```<code>mailto:info@example.org?Subject=Test&Body=Hello
</code>```

Negative test case

Content of locallang.xlf:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xliff version="1.0">
    <file source-language="en" datatype="plaintext" original="messages" date="2016-12-06T14:00:00Z" product-name="">
        <header/>
        <body>
            <trans-unit id="Test" xml:space="preserve">
                <source><![CDATA[mailto:info@example.org?Subject=%1$s&Body=Hello%0A%0A]]></source>
            </trans-unit>
        </body>
    </file>
</xliff>
</code>```

Output is an empty string

What is causing the empty output instead of the expected, encoded double line break?

I just found the underlaying PHP error message:

```<code>#1: PHP Warning: vsprintf(): Too few arguments in LocalizationUtility.php line 115
</code>```

答:
The character '%' should be escaped as '%%' as described in the PHP documentation for sprintf

This leads to

```<code> <source><![CDATA[mailto:info@example.org?Subject=%1$s&Body=Hello%%0A%%0A]]></source>
</code>```

instead of

```<code> <source><![CDATA[mailto:info@example.org?Subject=%1$s&Body=Hello%0A%0A]]></source>
</code>```

Body:
In my fluid Template I am using

{f:translate(key:'LLL:path/to/file/locallang.xlf:Test', arguments: {0: 'Test'})}

Positive test case

Content of locallang.xlf:

<?xml version="1.0" encoding="UTF-8"?>
<xliff version="1.0">
    <file source-language="en" datatype="plaintext" original="messages" date="2016-12-06T14:00:00Z" product-name="">

            <trans-unit id="Test" xml:space="preserve">
                <source><![CDATA[mailto:info@example.org?Subject=%1$s&Body=Hello%0A]]></source>
            </trans-unit>

    </file>
</xliff>

Output:

mailto:info@example.org?Subject=Test&Body=Hello

Negative test case

Content of locallang.xlf:

<?xml version="1.0" encoding="UTF-8"?>
<xliff version="1.0">
    <file source-language="en" datatype="plaintext" original="messages" date="2016-12-06T14:00:00Z" product-name="">

            <trans-unit id="Test" xml:space="preserve">
                <source><![CDATA[mailto:info@example.org?Subject=%1$s&Body=Hello%0A%0A]]></source>
            </trans-unit>

    </file>
</xliff>

Output is an empty string

What is causing the empty output instead of the expected, encoded double line break?

I just found the underlaying PHP error message:

#1: PHP Warning: vsprintf(): Too few arguments in LocalizationUtility.php line 115

Body:
The character '%' should be escaped as '%%' as described in the PHP documentation for sprintf

This leads to

 <source><![CDATA[mailto:info@example.org?Subject=%1$s&Body=Hello%%0A%%0A]]></source>

instead of

 <source><![CDATA[mailto:info@example.org?Subject=%1$s&Body=Hello%0A%0A]]></source>


问:
Localizing FirebaseUI Auth
I am a swift newbie so please bear with me. I have successfully integrated FirebaseUI into my app. I now wish to localize the strings for Dutch. My whole project is in Dutch so I do not have any localization in the project since it is all hard coded in the storyboard. The FirebaseUI docs say that you should:

```<code>// Swift
authUI?.customStringsBundle = NSBundle.mainBundle() // Or any custom bundle.
</code>```

But I am not sure where to actually place the strings file in the project (or how) or if I should be using a custom bundle?

I have spent a whole day playing around with bundles but without success. Your help would be appreciated!

答:
Here is how I got it to work eventually:

Add a strings file called FirebaseAuthUI.strings. I copied the content of this file from here

Use the following code when you create the controller to handle sign in:

Code:

```<code>if let bundlePath = Bundle.main.path(forResource: "FirebaseAuthUI", ofType: "strings") {
    let bundle = Bundle(path: bundlePath)
    authUI?.customStringsBundle = bundle;
}
</code>```

Don't forget to translate the strings in step 1.

Good luck

Title: Localizing FirebaseUI Auth

Body:
I am a swift newbie so please bear with me. I have successfully integrated FirebaseUI into my app. I now wish to localize the strings for Dutch. My whole project is in Dutch so I do not have any localization in the project since it is all hard coded in the storyboard. The FirebaseUI docs say that you should:

// Swift
authUI?.customStringsBundle = NSBundle.mainBundle() // Or any custom bundle.

But I am not sure where to actually place the strings file in the project (or how) or if I should be using a custom bundle?

I have spent a whole day playing around with bundles but without success. Your help would be appreciated!

Body:
Here is how I got it to work eventually:

Add a strings file called FirebaseAuthUI.strings. I copied the content of this file from here

Use the following code when you create the controller to handle sign in:

Code:

if let bundlePath = Bundle.main.path(forResource: "FirebaseAuthUI", ofType: "strings") {
    let bundle = Bundle(path: bundlePath)
    authUI?.customStringsBundle = bundle;
}

Don't forget to translate the strings in step 1.

Good luck


问:
is there any way to pass the values betwn the htmls without using any other language
is there any way to pass and get the values betwn the htmls without using any other language like js, jsp, php and others , only html.</p>

答: If you want to use only html the only thing you can do is display another page within your html using an iframe or frames. But I would not recommend those solutions. If you can get away with some javascript you can do way more with it. By you mentioning pass values it seems that you want to do some logic as the previous anwser stated HTML is only for the presentation layer.</p>


问:
Run ASP.NET Core Project from Visual Studio 2017
I have created ASP.NET Core project from command line:

```<code>> dotnet new web
> dotnet restore
> dotnet build
> dotnet run
</code>```

All works fine.

Now I have opened this project in Visual Studio 2017.

Debug - Start without debugging:

Unhandled Exception: System.IO.FileNotFoundException: Could not load
  file or assembly 'System.Runtime, Version=4.1.0.0, Culture=neutral,
  PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The
  system cannot find the file specified.    at
  System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken,
  IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs,
  Int32 methodInstCount, ObjectHandleOnStack type)    at
  System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module,
  Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext,
  RuntimeTypeHandle[] methodInstantiationContext)    at
  System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken,
  Type[] genericTypeArguments, Type[] genericMethodArguments)    at
  System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord
  caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly,
  RuntimeModule decoratedModule, MetadataToken decoratedToken,
  RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[]
  attributes, IList derivedAttributes, RuntimeType& attributeType,
  IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean&
  isVarArg)    at
  System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule
  decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount,
  RuntimeType attributeFilterType, Boolean mustBeInheritable, IList
  derivedAttributes, Boolean isDecoratedTargetSecurityTransparent)    at
  System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeAssembly
  assembly, RuntimeType caType)    at
  System.Attribute.GetCustomAttributes(Assembly element, Type
  attributeType, Boolean inherit)    at
  System.AppDomain.GetTargetFrameworkName()

How can I launcn, debug and develop my project in VS ?

p.s. I know I can create new project in VS and it works fine, but I need to work with project which was created from command line.

Update:

```<code>PS Q:\tsts> dotnet --version
1.0.0

PS Q:\tsts> type .\tsts.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <Folder Include="wwwroot\" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
  </ItemGroup>

</Project>

PS Q:\tsts> dotnet build
Microsoft (R) Build Engine version 15.1.548.43366
Copyright (C) Microsoft Corporation. All rights reserved.

  tsts -> Q:\tsts\bin\Debug\netcoreapp1.1\tsts.dll

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:02.90
</code>```

答:
Opening and running dotnet new project in VS2017 should work.

But sometimes VS goes crazy with strange and inexplicable "not found" dependencies and "not compiled" new files - then just close VS (or unload project), manually remove bin and obj folders and reopen project.

Body:
I have created ASP.NET Core project from command line:

> dotnet new web
> dotnet restore
> dotnet build
> dotnet run

All works fine.

Now I have opened this project in Visual Studio 2017.

Debug - Start without debugging:

Unhandled Exception: System.IO.FileNotFoundException: Could not load
  file or assembly 'System.Runtime, Version=4.1.0.0, Culture=neutral,
  PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The
  system cannot find the file specified.    at
  System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken,
  IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs,
  Int32 methodInstCount, ObjectHandleOnStack type)    at
  System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module,
  Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext,
  RuntimeTypeHandle[] methodInstantiationContext)    at
  System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken,
  Type[] genericTypeArguments, Type[] genericMethodArguments)    at
  System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord
  caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly,
  RuntimeModule decoratedModule, MetadataToken decoratedToken,
  RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[]
  attributes, IList derivedAttributes, RuntimeType& attributeType,
  IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean&
  isVarArg)    at
  System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule
  decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount,
  RuntimeType attributeFilterType, Boolean mustBeInheritable, IList
  derivedAttributes, Boolean isDecoratedTargetSecurityTransparent)    at
  System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeAssembly
  assembly, RuntimeType caType)    at
  System.Attribute.GetCustomAttributes(Assembly element, Type
  attributeType, Boolean inherit)    at
  System.AppDomain.GetTargetFrameworkName()

How can I launcn, debug and develop my project in VS ?

p.s. I know I can create new project in VS and it works fine, but I need to work with project which was created from command line.

Update:

PS Q:\tsts> dotnet --version
1.0.0

PS Q:\tsts> type .\tsts.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <Folder Include="wwwroot\" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
  </ItemGroup>

</Project>

PS Q:\tsts> dotnet build
Microsoft (R) Build Engine version 15.1.548.43366
Copyright (C) Microsoft Corporation. All rights reserved.

  tsts -> Q:\tsts\bin\Debug\netcoreapp1.1\tsts.dll

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:02.90


问:
Count the exact number of children with jQuery
Im trying to find count the exact number of a child and then add a class to another element matching that class, in this example the parent (it wont be the direct parent where I'm trying to achieve this).

$(".test").each(function(index, elem) {
  var countchild = $(this).find(".child");
  if (countchild.length > 4) {
    $(".test").addClass("four")
  } else {}
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
  <div class="child">1</div>
  <div class="child">2</div>
  <div class="child">3</div>
  <div class="child">4</div>
</div></code>```

答:
why dont you try this :

```<code> var countchild = $(".test > .child");
 if (countchild.length > 4) {
    $(".test").addClass("four")
  } else {
  }
</code>```

FYI,

.test > .child will only select child that are direct children to test (that is, there are no other elements in between).

.test  .child will select any child that are inside test, even if there are other elements between them.

Body:
Im trying to find count the exact number of a child and then add a class to another element matching that class, in this example the parent (it wont be the direct parent where I'm trying to achieve this).

$(".test").each(function(index, elem) {
  var countchild = $(this).find(".child");
  if (countchild.length > 4) {
    $(".test").addClass("four")
  } else {}
});

1

2

3

4

Body:
why dont you try this :

 var countchild = $(".test > .child");
 if (countchild.length > 4) {
    $(".test").addClass("four")
  } else {
  }

FYI,

.test > .child will only select child that are direct children to test (that is, there are no other elements in between).

.test  .child will select any child that are inside test, even if there are other elements between them.


问:
Tcl Expect: How can you expect 2 matches in 1 line
How can you expect 2 matches in 1 line</p>

```<code>expect "New password*" | "Retype"
send "something\r
</code>```

答:
The easiest way of doing this is to switch to using the other form of expect:

```<code>expect {
   "New password*" {}
   "Retype" {}
}
send "something\r
</code>```

The {} can be full scripts if you need to respond differently according to what sort of things happen. The exp_continue command is useful if you want to respond to something and keep on waiting:

```<code>expect {
   "New password*" {
       send "$thepassword\r"
       exp_continue
   }
   "Retype" {
       send "$thepassword\r"
       exp_continue
   }
   "thepromptyouexpectafterwards" {}
}
send "something else\r
</code>```

Body:
How can you expect 2 matches in 1 line

expect "New password*" | "Retype"
send "something\r

Body:
The easiest way of doing this is to switch to using the other form of expect:

expect {
   "New password*" {}
   "Retype" {}
}
send "something\r

The {} can be full scripts if you need to respond differently according to what sort of things happen. The exp_continue command is useful if you want to respond to something and keep on waiting:

expect {
   "New password*" {
       send "$thepassword\r"
       exp_continue
   }
   "Retype" {
       send "$thepassword\r"
       exp_continue
   }
   "thepromptyouexpectafterwards" {}
}
send "something else\r


问:
iOS framework to get audio in from dock connector
How would I go abouts playing an 'audio in' through the dock connector in an iOS app? I'm making an app just for myself and have no plans of putting it into the apple store. I have the 30pin breakout board, and on it there are pins for L/R audio in, but I can not find any info on how to use them?

Thanks

答:
Have you looked at the pinouts for the dock connector floating about? It appears that certain resistances connected to pin 21 indicate to the iDevice what is connected.

68kΩ seems to be the magic number for audio in/out.


问:
error writing to -: Invalid argument }
I get this error in qt creator while build project. This error is generated in different files means every time error is change to next .cpp file.

Error appears randomly in last of .cpp file near }(closing braces). I have clean the solution and build many times but error comes again .

答:
Check the *.pro file.
This error can arise because qmake looks for not existing file at the end of the list after a symbol "\".
Remove the last symbol "\".

For example maybe you have in pro-file:

```<code>HEADERS += file1.hpp \
       file2.hpp \
       file3.hpp \
</code>```

You need to change the code as follows :

```<code>HEADERS += file1.hpp \
       file2.hpp \
       file3.hpp
</code>```

Title: error writing to -: Invalid argument }

Body:
Check the *.pro file.
This error can arise because qmake looks for not existing file at the end of the list after a symbol "\".
Remove the last symbol "\".

For example maybe you have in pro-file:

HEADERS += file1.hpp \
       file2.hpp \
       file3.hpp \

You need to change the code as follows :

HEADERS += file1.hpp \
       file2.hpp \
       file3.hpp


问:
Grails Command Object Scope
| Grails Version: 3.0.7
| Groovy Version: 2.4.4
| JVM Version: 1.8.0_60

We have a controller using a command object :

```<code>def search(SearchCommand command) {

}
</code>```

The command object handles the data binding and form validation.  My question is, what would be the recommended approach to retain the data in the command object between non consecutive calls.

The command object in question holds a good number of parameters used in a complex search and the reason to retain the data is to repopulate the search form each time the user returns to the search form (which may be any number of subsequent requests later).

Any recommendations greatly appreciated.

答:
Either

put your command object into the session:

or some ConcurrentHashMap-like cache

or persist it in your DB

Title: Grails Command Object Scope

Body:
| Grails Version: 3.0.7
| Groovy Version: 2.4.4
| JVM Version: 1.8.0_60

We have a controller using a command object :

def search(SearchCommand command) {

}

The command object handles the data binding and form validation.  My question is, what would be the recommended approach to retain the data in the command object between non consecutive calls.

The command object in question holds a good number of parameters used in a complex search and the reason to retain the data is to repopulate the search form each time the user returns to the search form (which may be any number of subsequent requests later).

Any recommendations greatly appreciated.


问:
ArrayAdapter requires the resource ID to be a TextView in Custom Adapter
I build custom arrayAdapter to show a progress bar into spinner, my xml for row be like this

```<code><ProgressBar
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/progressBar"
 style="?android:attr/progressBarStyle"
 android:layout_width="match_parent"
 android:layout_height="wrap_content" />
</code>```

and my custom adapter

```<code>public class CustomAdapter extends ArrayAdapter
{

    private Context mContext;

    public CustomAdapter(@NonNull Context context, int resource,int textViewResourceId) {
        super(context, resource,textViewResourceId);
        mContext = context;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View row = inflater.inflate(R.layout.default_spinner_progress,parent,false);
        return row;
    }

    @Override
    public int getCount() {
        return 1;
    }
}
</code>```

I initialize it

```<code>transferSpinner.setAdapter(new CustomAdapter(getContext(),R.layout.default_spinner_progress,R.id.progressBar));
</code>```

I got this error in stack trace

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
   Process: com..debug, PID: 9537
   java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
</code>```

答:
use a BaseAdapter instead

```<code>public class CustomAdapter extends BaseAdapter {

    private Context mContext;

    public CustomAdapter(@NonNull Context context) {
        this.mContext = context;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            LayoutInflater inflater = LayoutInflater.from(mContext);
            view = inflater.inflate(R.layout.default_spinner_progress, parent, false);
        }
        return view;
    }

    @Override
    public int getCount() {
        return 1;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }
}
</code>```

call it using: transferSpinner.setAdapter(new CustomAdapter(this));

Body:
I build custom arrayAdapter to show a progress bar into spinner, my xml for row be like this

<ProgressBar
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/progressBar"
 style="?android:attr/progressBarStyle"
 android:layout_width="match_parent"
 android:layout_height="wrap_content" />

and my custom adapter

public class CustomAdapter extends ArrayAdapter
{

    private Context mContext;

    public CustomAdapter(@NonNull Context context, int resource,int textViewResourceId) {
        super(context, resource,textViewResourceId);
        mContext = context;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View row = inflater.inflate(R.layout.default_spinner_progress,parent,false);
        return row;
    }

    @Override
    public int getCount() {
        return 1;
    }
}

I initialize it

transferSpinner.setAdapter(new CustomAdapter(getContext(),R.layout.default_spinner_progress,R.id.progressBar));

I got this error in stack trace

E/AndroidRuntime: FATAL EXCEPTION: main
   Process: com..debug, PID: 9537
   java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView

Body:
use a BaseAdapter instead

public class CustomAdapter extends BaseAdapter {

    private Context mContext;

    public CustomAdapter(@NonNull Context context) {
        this.mContext = context;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            LayoutInflater inflater = LayoutInflater.from(mContext);
            view = inflater.inflate(R.layout.default_spinner_progress, parent, false);
        }
        return view;
    }

    @Override
    public int getCount() {
        return 1;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }
}

call it using: transferSpinner.setAdapter(new CustomAdapter(this));


问:
why is 'create table' in sql script executing 3 times when only using 1 create statement?
I have an SQL script in which I want to automate the creation of a table.
However, when I exec it, it seems as though it's trying to create the table 3 times.
The first time, it creates the table. The next 2 times, it complains it already exists by throwing an

```<code>"ORA-00955: name is already used by an existing object"
</code>```

Here my sql script(@/vagrant/scripts/db_tables_stubs.sql):

```<code>CREATE TABLE IDA_RADIUS_USER(
  CHECK_STRING    VARCHAR2(30),
  REPLY_STRING    VARCHAR2(300),
  RADIUS_USERNAME VARCHAR2(30),
  ACCOUNT_STATUS  VARCHAR2(30)
);
/
show errors;
</code>```

And this is what I get:

```<code>SQL> select * from IDA_RADIUS_USER;

no rows selected

SQL> drop table IDA_RADIUS_USER;

Table dropped.

SQL> @/vagrant/scripts/db_tables_stubs.sql

Table created.

CREATE TABLE IDA_RADIUS_USER(
             *
ERROR at line 1:
ORA-00955: name is already used by an existing object

No errors.
CREATE TABLE IDA_RADIUS_USER(
             *
ERROR at line 1:
ORA-00955: name is already used by an existing object

No errors.

Commit complete.
</code>```

All I want is to automate the process of creating that table.

Please help me.
I can't figure out why that's happening. It's annoying!

答:
You've said you have commented out code. It is those comments that are causing the problem.

```<code>SQL> create table t42(id number(38));

Table created.

SQL> /*insert into t42(id) values (1);*/
create table t42(id number(38))
             *
ERROR at line 1:
ORA-00955: name is already used by an existing object

SQL> /*exec dbms_stats.gather_schema_stats(user);*/
create table t42(id number(38))
             *
ERROR at line 1:
ORA-00955: name is already used by an existing object

SQL> show errors
No errors.
SQL>
</code>```

The slash (/) at the start of the comments is resubmitting the command in the buffer.

The SQL*Plus documentation also says:

Enter the SQL comment delimiters, /*...*/, on separate lines in your script, on the same line as a SQL command, or on a line in a PL/SQL block.

You must enter a space after the slash-asterisk (/*) beginning a comment.

So if you change your comments to have a space between the /* and the commented-out code that won't happen, and those will be ignored:

```<code>SQL> create table t42(id number(38));

Table created.

SQL> /* insert into t42(id) values (1); */
SQL> /* exec dbms_stats.gather_schema_stats(user); */
SQL> show errors
No errors.
SQL>
</code>```

Body:
I have an SQL script in which I want to automate the creation of a table.
However, when I exec it, it seems as though it's trying to create the table 3 times.
The first time, it creates the table. The next 2 times, it complains it already exists by throwing an

"ORA-00955: name is already used by an existing object"

Here my sql script(@/vagrant/scripts/db_tables_stubs.sql):

CREATE TABLE IDA_RADIUS_USER(
  CHECK_STRING    VARCHAR2(30),
  REPLY_STRING    VARCHAR2(300),
  RADIUS_USERNAME VARCHAR2(30),
  ACCOUNT_STATUS  VARCHAR2(30)
);
/
show errors;

And this is what I get:

SQL> select * from IDA_RADIUS_USER;

no rows selected

SQL> drop table IDA_RADIUS_USER;

Table dropped.

SQL> @/vagrant/scripts/db_tables_stubs.sql

Table created.

CREATE TABLE IDA_RADIUS_USER(
             *
ERROR at line 1:
ORA-00955: name is already used by an existing object

No errors.
CREATE TABLE IDA_RADIUS_USER(
             *
ERROR at line 1:
ORA-00955: name is already used by an existing object

No errors.

Commit complete.

All I want is to automate the process of creating that table.

Please help me.
I can't figure out why that's happening. It's annoying!

Body:
You've said you have commented out code. It is those comments that are causing the problem.

SQL> create table t42(id number(38));

Table created.

SQL> /*insert into t42(id) values (1);*/
create table t42(id number(38))
             *
ERROR at line 1:
ORA-00955: name is already used by an existing object

SQL> /*exec dbms_stats.gather_schema_stats(user);*/
create table t42(id number(38))
             *
ERROR at line 1:
ORA-00955: name is already used by an existing object

SQL> show errors
No errors.
SQL>

The slash (/) at the start of the comments is resubmitting the command in the buffer.

The SQL*Plus documentation also says:

Enter the SQL comment delimiters, /*...*/, on separate lines in your script, on the same line as a SQL command, or on a line in a PL/SQL block.

You must enter a space after the slash-asterisk (/*) beginning a comment.

So if you change your comments to have a space between the /* and the commented-out code that won't happen, and those will be ignored:

SQL> create table t42(id number(38));

Table created.

SQL> /* insert into t42(id) values (1); */
SQL> /* exec dbms_stats.gather_schema_stats(user); */
SQL> show errors
No errors.
SQL>


问:
how to run any program when connecting any device through ActivSync
how to run any program when connecting any device through ActivSync ?

thank's in advance

答:
Use registry based notification events, see MSDN

Registry-based notification is based on two predefined events, AutoStartOnConnect and AutoStartOnDisconnect, each of which has its own registry key. When either event occurs, a command associated with the corresponding key is executed.
  HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows CE Services\AutoStartOnConnect
  HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows CE Services\AutoStartOnDisconnect

To associate an application with an event

Construct a value that uniquely identifies the application. The value should include a company and product name — MicrosoftActiveSync, for example.

Enter the identifier value under one or both AutoStartOn registry keys.

The data for the identifier should be the command line for the application to be executed, including arguments. The command line must be enclosed in quotation marks if arguments are used.

The following registry editor (.reg) file shows how to register a command line for both AutoStartOnConnect and AutoStartOnDisconnect. When the Windows CE-based device is connected, Notepad is started with a command-line argument of C:\Config.sys. When the Windows CE-based device is disconnected, Notepad is started with a command-line argument of C:\Autoexec.bat.

```<code>REGEDIT4
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows CE Services\AutoStartOnConnect]
    "MicrosoftActiveSync"="\"notepad"\ c:\\config.sys"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows CE Services\AutoStartOnDisconnect]
    "MicrosoftActiveSync"="\"notepad"\ c:\\autoexec.bat"
</code>```

Body:
Use registry based notification events, see MSDN

Registry-based notification is based on two predefined events, AutoStartOnConnect and AutoStartOnDisconnect, each of which has its own registry key. When either event occurs, a command associated with the corresponding key is executed.
  HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows CE Services\AutoStartOnConnect
  HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows CE Services\AutoStartOnDisconnect

To associate an application with an event

Construct a value that uniquely identifies the application. The value should include a company and product name — MicrosoftActiveSync, for example.

Enter the identifier value under one or both AutoStartOn registry keys.

The data for the identifier should be the command line for the application to be executed, including arguments. The command line must be enclosed in quotation marks if arguments are used.

The following registry editor (.reg) file shows how to register a command line for both AutoStartOnConnect and AutoStartOnDisconnect. When the Windows CE-based device is connected, Notepad is started with a command-line argument of C:\Config.sys. When the Windows CE-based device is disconnected, Notepad is started with a command-line argument of C:\Autoexec.bat.

REGEDIT4
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows CE Services\AutoStartOnConnect]
    "MicrosoftActiveSync"="\"notepad"\ c:\\config.sys"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows CE Services\AutoStartOnDisconnect]
    "MicrosoftActiveSync"="\"notepad"\ c:\\autoexec.bat"