问:
Reading a file in Python in Ubuntu
I'm trying to access a .txt file in my root account to open and read in python. My code looks like this:

```<code>>>> path = 'root/unpackedFiles/enrollment_fact.txt'
>>> read = open(path,'r')
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    read = open(path,'r')
FileNotFoundError: [Errno 2] No such file or directory: 'root/unpackedFiles/enrollment_fact.txt'
</code>```

I've also tried several variations of this with no such luck. Including:

path = 'unpackedFiles/enrollment_fact.txt' and path = 'enrollment_fact.txt'

答:
Your path is incorrect. Absolute paths need to start with a slash for the root directory. Your path should look like this:</p>

```<code>path = '/root/unpackedFiles/enrollment_fact.txt'
</code>```

Title: Reading a file in Python in Ubuntu

Body:
I'm trying to access a .txt file in my root account to open and read in python. My code looks like this:

>>> path = 'root/unpackedFiles/enrollment_fact.txt'
>>> read = open(path,'r')
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    read = open(path,'r')
FileNotFoundError: [Errno 2] No such file or directory: 'root/unpackedFiles/enrollment_fact.txt'

I've also tried several variations of this with no such luck. Including:

path = 'unpackedFiles/enrollment_fact.txt' and path = 'enrollment_fact.txt'

Body:
Your path is incorrect. Absolute paths need to start with a slash for the root directory. Your path should look like this:

path = '/root/unpackedFiles/enrollment_fact.txt'


来源: stackexchange

问:
Excel Browsing a folder and Automating Data Entry into a default template
I been reading up codes available on the net from various sources and have debug with self-taught programming to make it work but I'm having difficulty proceeding on.

As you can see, it comes from a source. Browsing a folder & reading the files works fine with the code, I need to copy values from this folder & paste it into the default template as assigned in the code & save the file with with a default format and alongside values from a cell(O1) & (O11) assign in the code.

As you can see, is not saved as xlsx and neither is it saving with the values from cell specified.

Next, automating data entry to assigned field. Only first 3 files are able to copy exactly what I want. The rest inputs wrong data, as shown in the image below. Additionally, I also need to copy values from cell N15:O83 read from files in  folder, into template Column AA & AB starting from row 6 respectively.

Thanks in advance for any assistance provided.

Sample Source File

Correct Automation

Wrong Automation

Macro 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
Dim InstID As String
Dim InstDate As Date
Dim InstBR As String

'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 = "Select A Target Folder"
  .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

'Input Code Here

  InstID = Range("O1")
  InstDate = Range("O11")
  InstBR = "Base Reading"

  wb.Worksheets(1).Range("B15:E83").Copy
  Workbooks.Add template:="C:\Users\PC1\Desktop\Daily data file\Inc\TestTemplate.xlsx"
  Sheets(ActiveSheet.Index + 1).Activate
  If Err.Number <> 0 Then Sheets(1).Activate
  Range("M6").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

    Range("E6:F76") = InstID
    Range("K6:K76") = InstDate
    Range("J6") = InstBR

ChDir ("C:\Users\PC\Desktop\Daily data file\Inc\INC22001 - Copy\Test Save") ' Directory you need to save the file as xlsm
Filename = ("Test_Data_ ") & Range("O1").Value & ";" &     Range("O11").Value
ActiveWorkbook.SaveAs Filename:=Filename, FileFormat:=xlOpenXMLWorkbook

'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>```

答:
Hi Please correct me if I'm wrong. Okay here's the thing that I understand based on your explanation.

First you have a Template (wbTemplate), and then a set of other workbooks that you need to open and pre-format it based on the template given then save it on your target path.

You need to practice in setting all your objects dynamically.

I put comments on every line so you may understand how this works.

{

```<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 wbTemplate As Workbook, wbSourceFile As Workbook
 Dim wsTemplate As Worksheet, wsSourceFile As Worksheet
 Dim SourceFileEndRow As Long, TemplateEndRow As Long
 Dim myPath As String, myFile As String 'This is where the Source File      located
 Dim myExtension As String
 Dim FldrPicker As FileDialog
 Dim InstID As String
 Dim InstDate As Date
 Dim InstBR As String
 Dim targetPath As String 'Set this to where you want to save all the output files

 Set wbTemplate = ThisWorkbook
 Set wsTemplate = ThisWorkbook.Sheets(1) ' Input the Index no. of your      Template, or much better to rename it based on the Name of the Template Tab
 targetPath = "C:\Users\Enrerol\Desktop\Tester\TargetPath\" 'Set where you want to save your Output File
 '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 = "Select A Target Folder"
   .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 wbSourceFile = Workbooks.Open(Filename:=myPath & myFile) ' Set our      SourceFile
   Set wsSourceFile = wbSourceFile.Worksheets(1) 'Set the Worksheet that we      are copying
 'Ensure Workbook has opened before moving on to next line of code
   DoEvents

 'Input Code Here

   InstID = wsSourceFile.Range("O1")
   InstDate = wsSourceFile.Range("O11")
   InstBR = "Base Reading"
 SourceFileEndRow = wsSourceFile.Range("B" & Rows.Count).End(xlUp).Row '      This to  make sure that you have a dynamic range; it will get the last row used      of the Source File
   wsSourceFile.Range("B15:E" & SourceFileEndRow).Copy      Destination:=wsTemplate.Range("M6")
 TemplateEndRow = wsTemplate.Range("M" & Rows.Count).End(xlUp).Row 'We will      get the last used row of our Destination Column
   wsTemplate.Range("E6:F" & TemplateEndRow) = InstID
   wsTemplate.Range("K6:K" & TemplateEndRow) = InstDate
   wsTemplate.Range("J6") = InstBR

 Filename = ("Test_Data_") & InstID & "_" & Format(InstDate, "m_d_yyyy") '      You need to change this, because there will be an error on your existing format.      Specially the instdate is Formated as "dd/mm/yyyy"
 Application.DisplayAlerts = False 'We will need to stop the prompting of      the excel application
 wbTemplate.SaveAs Filename:=targetPath & Filename,      FileFormat:=xlOpenXMLWorkbook
 Application.DisplayAlerts = True 'Reset application Values
 'Save and Close Workbook

 wbSourceFile.Close SaveChanges:=True
 wsTemplate.UsedRange.Delete
 '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>```

ContentLicense: CC BY-SA 3.0

Body:
I been reading up codes available on the net from various sources and have debug with self-taught programming to make it work but I'm having difficulty proceeding on.

As you can see, it comes from a source. Browsing a folder & reading the files works fine with the code, I need to copy values from this folder & paste it into the default template as assigned in the code & save the file with with a default format and alongside values from a cell(O1) & (O11) assign in the code.

As you can see, is not saved as xlsx and neither is it saving with the values from cell specified.

Next, automating data entry to assigned field. Only first 3 files are able to copy exactly what I want. The rest inputs wrong data, as shown in the image below. Additionally, I also need to copy values from cell N15:O83 read from files in  folder, into template Column AA & AB starting from row 6 respectively.

Thanks in advance for any assistance provided.

Sample Source File

Correct Automation

Wrong Automation

Macro 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 InstID As String
Dim InstDate As Date
Dim InstBR As String

'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 = "Select A Target Folder"
  .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

'Input Code Here

  InstID = Range("O1")
  InstDate = Range("O11")
  InstBR = "Base Reading"

  wb.Worksheets(1).Range("B15:E83").Copy
  Workbooks.Add template:="C:\Users\PC1\Desktop\Daily data file\Inc\TestTemplate.xlsx"
  Sheets(ActiveSheet.Index + 1).Activate
  If Err.Number <> 0 Then Sheets(1).Activate
  Range("M6").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

    Range("E6:F76") = InstID
    Range("K6:K76") = InstDate
    Range("J6") = InstBR

ChDir ("C:\Users\PC\Desktop\Daily data file\Inc\INC22001 - Copy\Test Save") ' Directory you need to save the file as xlsm
Filename = ("Test_Data_ ") & Range("O1").Value & ";" &     Range("O11").Value
ActiveWorkbook.SaveAs Filename:=Filename, FileFormat:=xlOpenXMLWorkbook

'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

Body:
Hi Please correct me if I'm wrong. Okay here's the thing that I understand based on your explanation.

First you have a Template (wbTemplate), and then a set of other workbooks that you need to open and pre-format it based on the template given then save it on your target path.

You need to practice in setting all your objects dynamically.

I put comments on every line so you may understand how this works.

{

 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 wbTemplate As Workbook, wbSourceFile As Workbook
 Dim wsTemplate As Worksheet, wsSourceFile As Worksheet
 Dim SourceFileEndRow As Long, TemplateEndRow As Long
 Dim myPath As String, myFile As String 'This is where the Source File      located
 Dim myExtension As String
 Dim FldrPicker As FileDialog
 Dim InstID As String
 Dim InstDate As Date
 Dim InstBR As String
 Dim targetPath As String 'Set this to where you want to save all the output files

 Set wbTemplate = ThisWorkbook
 Set wsTemplate = ThisWorkbook.Sheets(1) ' Input the Index no. of your      Template, or much better to rename it based on the Name of the Template Tab
 targetPath = "C:\Users\Enrerol\Desktop\Tester\TargetPath\" 'Set where you want to save your Output File
 '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 = "Select A Target Folder"
   .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 wbSourceFile = Workbooks.Open(Filename:=myPath & myFile) ' Set our      SourceFile
   Set wsSourceFile = wbSourceFile.Worksheets(1) 'Set the Worksheet that we      are copying
 'Ensure Workbook has opened before moving on to next line of code
   DoEvents

 'Input Code Here

   InstID = wsSourceFile.Range("O1")
   InstDate = wsSourceFile.Range("O11")
   InstBR = "Base Reading"
 SourceFileEndRow = wsSourceFile.Range("B" & Rows.Count).End(xlUp).Row '      This to  make sure that you have a dynamic range; it will get the last row used      of the Source File
   wsSourceFile.Range("B15:E" & SourceFileEndRow).Copy      Destination:=wsTemplate.Range("M6")
 TemplateEndRow = wsTemplate.Range("M" & Rows.Count).End(xlUp).Row 'We will      get the last used row of our Destination Column
   wsTemplate.Range("E6:F" & TemplateEndRow) = InstID
   wsTemplate.Range("K6:K" & TemplateEndRow) = InstDate
   wsTemplate.Range("J6") = InstBR

 Filename = ("Test_Data_") & InstID & "_" & Format(InstDate, "m_d_yyyy") '      You need to change this, because there will be an error on your existing format.      Specially the instdate is Formated as "dd/mm/yyyy"
 Application.DisplayAlerts = False 'We will need to stop the prompting of      the excel application
 wbTemplate.SaveAs Filename:=targetPath & Filename,      FileFormat:=xlOpenXMLWorkbook
 Application.DisplayAlerts = True 'Reset application Values
 'Save and Close Workbook

 wbSourceFile.Close SaveChanges:=True
 wsTemplate.UsedRange.Delete
 '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


问:
Angular get in-between indexes after orderBy
As you know after orderBy table loses its ordering and the $index value is from the sorted array, not from the original array. So if you pass an items array ['orange', 'banana','potato','apple'] to your ng-repeat, after an orderBy on the UI you will see them like this:

```<code>- apple   $index = 0
- banana  $index = 1
- orange  $index = 2
- potato  $index = 3
</code>```

And if you now want to multi select items between apple($index = 0) and orange($index = 2) you might think that this will work:

```<code>for(index = 0; index <= 2; index++)
  console.log(items[index])
</code>```

which is wrong, it will print : [orange, banana, potato]; not [apple, banana, orange].

I am looking a way to get the interval indexes of the displayed array after an orderBy, any ideas?

EDIT: To clarify, assume that on UI you have sorted items and then you select apple and then select orange:

```<code>✓ apple
  banana
✓ orange
  potato
</code>```

I want a way to know the items in between those two selected, so that I can select all in between, in our case banana.

答:
Angular allows you to specify an alias for the data after filters have been applied. You could pass that alias into whatever method selected the items out of it along with the item or the $index which is the item's index within the ordered items.

```<code> <div ng-repeat="item in items | orderBy: '+' as orderedItems">
    <a ng-click="itemSelected(orderedItems, $index)">{{item}}</a>
 </div>
</code>```

Body:
As you know after orderBy table loses its ordering and the $index value is from the sorted array, not from the original array. So if you pass an items array ['orange', 'banana','potato','apple'] to your ng-repeat, after an orderBy on the UI you will see them like this:

- apple   $index = 0
- banana  $index = 1
- orange  $index = 2
- potato  $index = 3

And if you now want to multi select items between apple($index = 0) and orange($index = 2) you might think that this will work:

for(index = 0; index <= 2; index++)
  console.log(items[index])

which is wrong, it will print : [orange, banana, potato]; not [apple, banana, orange].

I am looking a way to get the interval indexes of the displayed array after an orderBy, any ideas?

EDIT: To clarify, assume that on UI you have sorted items and then you select apple and then select orange:

✓ apple
  banana
✓ orange
  potato

I want a way to know the items in between those two selected, so that I can select all in between, in our case banana.

Body:
Angular allows you to specify an alias for the data after filters have been applied. You could pass that alias into whatever method selected the items out of it along with the item or the $index which is the item's index within the ordered items.

 <div ng-repeat="item in items | orderBy: '+' as orderedItems">
    <a ng-click="itemSelected(orderedItems, $index)">{{item}}</a>
 </div>


问:
Explicitly setting active member in union in C++
The following code is the classical, infamous type-punning union. Similar code is legal in C99/C11 but illegal in C++, because one has to read from the inactive member.

To activate the inactive member one has to write to it (that is not appropriate here) or to construct it via placement-new.

The code below does exactly this: it initializes member a and then activates member b by placement-new. In case of an array of primitive types, the construction is actually a noop, and the bitvalues remain the same.

I never saw this solution in the numerous other questions / answers to this topix, so I wonder if the code below in fact circumvents UB really.

```<code>#include <cstdint>
#include <cstddef>
#include <utility>
#include <array>
#include <tuple>
#include <cassert>

union ByteUnion32 {
public:
    explicit ByteUnion32(uint32_t v) : a{v}{
        new (&b) std::byte[sizeof(uint32_t)]; // set b active, but prevents constexpr, actually a noop
    }
    std::byte operator[](uint8_t i) const {
            return b[i];
    }
private:
    uint32_t a;
    std::byte b[sizeof(uint32_t)];
};
int main(){
    ByteUnion32 u10{0x01020304}; // initialise and activate byte-memebers
    auto v10 = std::to_integer<uint8_t>(u10[0]);
    assert(v10 == 4);

}
</code>```

答:
From [dcl.init]/12:

If no initializer is specified for an object, the object is default-initialized. When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced ([expr.ass]). [...] If an indeterminate value is produced by an evaluation, the behavior is undefined except in the following cases: [...]

In this code:

```<code>assert(v10 == 4);
</code>```

Either the initialization of v10 itself is undefined behavior due to not fitting any of the bullet points (I'm not entirely sure about this), or the initialization of v10 is fine and it just is considered to have indeterminate value, at which point the ultimate comparison to 4 is undefined behavior.

Either way, this is undefined behavior.

Body:
The following code is the classical, infamous type-punning union. Similar code is legal in C99/C11 but illegal in C++, because one has to read from the inactive member.

To activate the inactive member one has to write to it (that is not appropriate here) or to construct it via placement-new.

The code below does exactly this: it initializes member a and then activates member b by placement-new. In case of an array of primitive types, the construction is actually a noop, and the bitvalues remain the same.

I never saw this solution in the numerous other questions / answers to this topix, so I wonder if the code below in fact circumvents UB really.

#include <cstdint>
#include <cstddef>
#include <utility>
#include <array>
#include <tuple>
#include <cassert>

union ByteUnion32 {
public:
    explicit ByteUnion32(uint32_t v) : a{v}{
        new (&b) std::byte[sizeof(uint32_t)]; // set b active, but prevents constexpr, actually a noop
    }
    std::byte operator[](uint8_t i) const {
            return b[i];
    }
private:
    uint32_t a;
    std::byte b[sizeof(uint32_t)];
};
int main(){
    ByteUnion32 u10{0x01020304}; // initialise and activate byte-memebers
    auto v10 = std::to_integer<uint8_t>(u10[0]);
    assert(v10 == 4);

}

Body:
From [dcl.init]/12:

If no initializer is specified for an object, the object is default-initialized. When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced ([expr.ass]). [...] If an indeterminate value is produced by an evaluation, the behavior is undefined except in the following cases: [...]

In this code:

assert(v10 == 4);

Either the initialization of v10 itself is undefined behavior due to not fitting any of the bullet points (I'm not entirely sure about this), or the initialization of v10 is fine and it just is considered to have indeterminate value, at which point the ultimate comparison to 4 is undefined behavior.

Either way, this is undefined behavior.


问:
Is it possible to force deselection of all object onclick?
My problem is that when I go to print a fabricjs canvas sometimes I'll forget to deselect an object and it leaves the controls on it when it goes to the print dialogue. Is there a way to clear any selected objects onclick?

Currently to print I'm using the following:

```<code>// Print
function printCanvas() {
var dataUrl = document.getElementById('c').toDataURL(); //attempt to save base64 string to server using this var
  var windowContent = '<!DOCTYPE html>';
  windowContent += '<html>'
  windowContent += '<head><title>Print canvas</title></head>';
  windowContent += '<body>'
  windowContent += '<img src="' + dataUrl + '" onload=window.print();window.close();>';
  windowContent += '</body>';
  windowContent += '</html>';
  var printWin = window.open('', '', 'width=340,height=260');
  printWin.document.open();
  printWin.document.write(windowContent);
}
</code>```

```<code><button onclick="printCanvas()">Print</button>
</code>```

From the print dialogue:

Thanks for any help in advance!

答:
you can use

```<code>canvas.discardActiveObject();
canvas.renderAll();
</code>```

(function() {
    var canvas = this.__canvas = new fabric.Canvas('canvas');

    // create a rectangle with a fill and a different color stroke
    var rect = new fabric.Rect({
       left: 50,
       top: 50,
       width: 50,
       height: 50,
       fill: 'rgba(255,127,39,1)',
       stroke: 'rgba(34,177,76,1)',
       strokeWidth: 5
    });
    canvas.add(rect);
    canvas.renderAll();
    $('#deselect').click(function(){
      canvas.discardActiveObject();
      canvas.renderAll();
    });
})();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="canvas" width="150" height="150"></canvas>
<button id="deselect">deselect</button>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script></code>```

Body:
My problem is that when I go to print a fabricjs canvas sometimes I'll forget to deselect an object and it leaves the controls on it when it goes to the print dialogue. Is there a way to clear any selected objects onclick?

Currently to print I'm using the following:

// Print
function printCanvas() {
var dataUrl = document.getElementById('c').toDataURL(); //attempt to save base64 string to server using this var
  var windowContent = '<!DOCTYPE html>';
  windowContent += ''
  windowContent += '<title>Print canvas</title>';
  windowContent += ''
  windowContent += '';
  windowContent += '';
  windowContent += '';
  var printWin = window.open('', '', 'width=340,height=260');
  printWin.document.open();
  printWin.document.write(windowContent);
}

<button onclick="printCanvas()">Print</button>

From the print dialogue:

Thanks for any help in advance!

Body:
you can use

canvas.discardActiveObject();
canvas.renderAll();

(function() {
    var canvas = this.__canvas = new fabric.Canvas('canvas');

    // create a rectangle with a fill and a different color stroke
    var rect = new fabric.Rect({
       left: 50,
       top: 50,
       width: 50,
       height: 50,
       fill: 'rgba(255,127,39,1)',
       stroke: 'rgba(34,177,76,1)',
       strokeWidth: 5
    });
    canvas.add(rect);
    canvas.renderAll();
    $('#deselect').click(function(){
      canvas.discardActiveObject();
      canvas.renderAll();
    });
})();

<canvas id="canvas" width="150" height="150"></canvas>
<button id="deselect">deselect</button>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>


问:
How to get triangle upper matrix without the diagonal using numpy
Lets say I have the following matrix:

```<code>A = np.array([
     [1,2,3],
     [4,5,6],
     [7,8,9]])
</code>```

How can I extract the upper triangle matrix without the diagonal efficiently?
The output would be the following array:

```<code>B = np.array([2,3,6])
</code>```

答:
One approach with masking -

```<code>def upper_tri_masking(A):
    m = A.shape[0]
    r = np.arange(m)
    mask = r[:,None] < r
    return A[mask]
</code>```

Another with np.triu_indices -

```<code>def upper_tri_indexing(A):
    m = A.shape[0]
    r,c = np.triu_indices(m,1)
    return A[r,c]
</code>```

Sample run -

```<code>In [403]: A
Out[403]:
array([[79, 17, 79, 58, 14],
       [87, 63, 89, 26, 31],
       [69, 34, 90, 24, 96],
       [59, 60, 80, 52, 46],
       [75, 80, 11, 61, 47]])

In [404]: upper_tri_masking(A)
Out[404]: array([17, 79, 58, 14, 89, 26, 31, 24, 96, 46])
</code>```

Runtime test -

```<code>In [415]: A = np.random.randint(0,9,(5000,5000))

In [416]: %timeit upper_tri_masking(A)
10 loops, best of 3: 64.2 ms per loop

In [417]: %timeit upper_tri_indexing(A)
1 loop, best of 3: 252 ms per loop
</code>```

Body:
Lets say I have the following matrix:

A = np.array([
     [1,2,3],
     [4,5,6],
     [7,8,9]])

How can I extract the upper triangle matrix without the diagonal efficiently?
The output would be the following array:

B = np.array([2,3,6])

Body:
One approach with masking -

def upper_tri_masking(A):
    m = A.shape[0]
    r = np.arange(m)
    mask = r[:,None] < r
    return A[mask]

Another with np.triu_indices -

def upper_tri_indexing(A):
    m = A.shape[0]
    r,c = np.triu_indices(m,1)
    return A[r,c]

Sample run -

In [403]: A
Out[403]:
array([[79, 17, 79, 58, 14],
       [87, 63, 89, 26, 31],
       [69, 34, 90, 24, 96],
       [59, 60, 80, 52, 46],
       [75, 80, 11, 61, 47]])

In [404]: upper_tri_masking(A)
Out[404]: array([17, 79, 58, 14, 89, 26, 31, 24, 96, 46])

Runtime test -

In [415]: A = np.random.randint(0,9,(5000,5000))

In [416]: %timeit upper_tri_masking(A)
10 loops, best of 3: 64.2 ms per loop

In [417]: %timeit upper_tri_indexing(A)
1 loop, best of 3: 252 ms per loop


问:
VBA Select specific cell in PowerPoint table
How do you select a specific cell in a PowerPoint table ?

I need to paste into a PowerPoint table, including my Excel formatting, to a specific cell.

Code is situated in Excel!

Specifically, this is how you select a specific cell!

```<code>    PPSlide.Shapes("Table 4").Table.Rows(2).Cells.Item(1).Select
</code>```

This is an informational post, I couldn't figure out how to do it for a while, so I thought I'd add.t

```<code>Dim PPApp As PowerPoint.Application
Dim PPPres As PowerPoint.Presentation
Dim PPSlide As PowerPoint.Slide

Set PPApp = GetObject(, "Powerpoint.Application")
Set PPPres = PPApp.ActivePresentation
Dim sht as Worksheet
Set sht = ThisWorkbook.Sheets("Local Channels National View")

   ''''''''COPY TEMPLATE SLIDE''''''''
    ''duplicate template slide, move to end of presentation
    Set slideR = PPPres.Slides(3).Duplicate
    slideR.MoveTo (PPPres.Slides.Count)
    Set PPSlide = PPPres.Slides(PPPres.Slides.Count)

    sht.Range("B10:F14").Copy

    ''''select rows 2, column 1 cell
    PPSlide.Shapes("Table 4").Table.Rows(2).Cells.Item(1).Select

    '''paste
    PPApp.CommandBars.ExecuteMso ("Paste")
</code>```

Resources:
CellRange object - collection of cells, row or column
https://msdn.microsoft.com/en-us/VBA/PowerPoint-VBA/articles/cellrange-object-powerpoint

Cell Object
https://msdn.microsoft.com/en-us/vba/powerpoint-vba/articles/cell-object-powerpoint

答:
This is how you select a specific cell:

PPSlide.Shapes("Table 4").Table.Rows(2).Cells.Item(1).Select

Body:
How do you select a specific cell in a PowerPoint table ?

I need to paste into a PowerPoint table, including my Excel formatting, to a specific cell.

Code is situated in Excel!

Specifically, this is how you select a specific cell!

    PPSlide.Shapes("Table 4").Table.Rows(2).Cells.Item(1).Select

This is an informational post, I couldn't figure out how to do it for a while, so I thought I'd add.t

Dim PPApp As PowerPoint.Application
Dim PPPres As PowerPoint.Presentation
Dim PPSlide As PowerPoint.Slide

Set PPApp = GetObject(, "Powerpoint.Application")
Set PPPres = PPApp.ActivePresentation
Dim sht as Worksheet
Set sht = ThisWorkbook.Sheets("Local Channels National View")

   ''''''''COPY TEMPLATE SLIDE''''''''
    ''duplicate template slide, move to end of presentation
    Set slideR = PPPres.Slides(3).Duplicate
    slideR.MoveTo (PPPres.Slides.Count)
    Set PPSlide = PPPres.Slides(PPPres.Slides.Count)

    sht.Range("B10:F14").Copy

    ''''select rows 2, column 1 cell
    PPSlide.Shapes("Table 4").Table.Rows(2).Cells.Item(1).Select

    '''paste
    PPApp.CommandBars.ExecuteMso ("Paste")

Resources:
CellRange object - collection of cells, row or column
https://msdn.microsoft.com/en-us/VBA/PowerPoint-VBA/articles/cellrange-object-powerpoint

Cell Object
https://msdn.microsoft.com/en-us/vba/powerpoint-vba/articles/cell-object-powerpoint


问:
TypeScript type for all JS objects that can be passed to Object.keys(o)
I am trying to determine what the parameter type is for Object.keys(), here is the official declaration (lib.es6.d.ts):

```<code>interface ObjectConstructor {
    new(value?: any): Object;
    (): any;
    (value: any): any;

    ...

    /**
      * Returns the names of the enumerable properties and methods of an object.
      * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
      */
    keys(o: any): string[];
}
</code>```

So I have a function like so:

```<code> v.registerMap = function (o: NotSureWhatTypeToUse): Promise<Array<any>> {

        let keys: Array<string>;

        try {
          keys = Object.keys(o);  // perhaps this will never throw
        }
        catch (err) {
          _suman.log.error('Could not call Object.keys(o), where o is:', util.inspect(o));
          throw err;
        }

        return Promise.all(keys.map(function (k) {

          try {
            return valuesMap[k] = o.get(k)
          }
          catch (err) {
            return valuesMap[k] = o[k];
          }

        }));
      };
</code>```

as you can see above, I am trying to handle the case where the original parameter is a Map or a plain object.

The async library uses Dictionary<{}> for its TypeScript type for a similar type of parameter. Is that the one I am looking for?

In the async library, this type looks like:

```<code>export interface Dictionary<T> { [key: string]: T; }
</code>```

Perhaps the one I am looking for.

答:
I think the best thing to do, is just to limit the input to plain objects, something like this:

```<code>type PlainObj = {}

v.registerMap = function (o: PlainObj): Promise<Array<any>> {...};
</code>```

one thing I am confused about, however, is how generics work in the async library. The async lib use Dictionary, like so:

```<code>export interface Dictionary<T> { [key: string]: T; }
</code>```

I don't know how Dictionary<any> is different from PlainObj.

Body:
I am trying to determine what the parameter type is for Object.keys(), here is the official declaration (lib.es6.d.ts):

interface ObjectConstructor {
    new(value?: any): Object;
    (): any;
    (value: any): any;

    ...

    /**
      * Returns the names of the enumerable properties and methods of an object.
      * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
      */
    keys(o: any): string[];
}

So I have a function like so:

 v.registerMap = function (o: NotSureWhatTypeToUse): Promise<Array<any>> {

        let keys: Array<string>;

        try {
          keys = Object.keys(o);  // perhaps this will never throw
        }
        catch (err) {
          _suman.log.error('Could not call Object.keys(o), where o is:', util.inspect(o));
          throw err;
        }

        return Promise.all(keys.map(function (k) {

          try {
            return valuesMap[k] = o.get(k)
          }
          catch (err) {
            return valuesMap[k] = o[k];
          }

        }));
      };

as you can see above, I am trying to handle the case where the original parameter is a Map or a plain object.

The async library uses Dictionary<{}> for its TypeScript type for a similar type of parameter. Is that the one I am looking for?

In the async library, this type looks like:

export interface Dictionary<T> { [key: string]: T; }

Perhaps the one I am looking for.

Body:
I think the best thing to do, is just to limit the input to plain objects, something like this:

type PlainObj = {}

v.registerMap = function (o: PlainObj): Promise<Array<any>> {...};

one thing I am confused about, however, is how generics work in the async library. The async lib use Dictionary, like so:

export interface Dictionary<T> { [key: string]: T; }

I don't know how Dictionary<any> is different from PlainObj.


问:
INDEX-MATCH and SUMPRODUCT
I have a list of users and the security groups they're associated with, generated from Active Directory.  It looks like this:

```<code>Username  Security Group
Chris     Group A
Chris     Group B
Chris     Group C
Dave      Group D
Dave      Group A
Dave      Group E
</code>```

I have another list of usernames that I need to cross-reference to determine if a user is a part of one or more specific security groups.  The list of security  groups is dynamic and will change based on some other criteria so I'd like to just reference a named range in my check.

The equation I'm using right now looks like this:

```<code>=IF(INDEX('Users in Security Groups'!C:C, MATCH('Cross-Reference'!A2, 'Users in Security Groups'!B:B, 0))=Rng_SecGrp, "YES", "NO")
</code>```

Because INDEX-MATCH stops on the first value I am getting "NO" for username that I know actually belong to these security groups I'm concerned with.  I imagine the answer lies with array formulas and/or SUMPRODUCT but both are a bit outside my comfort zone and I've failed to nail down the right formula to this point.

Any help is appreciated!  Thanks!

答:
Use COUNTIFS() not INDEX(,MATCH()):

```<code>=IF(SUM(COUNTIFS('Users in Security Groups'!C:C,Rng_SecGrp,'Users in Security Groups'!B:B,'Cross-Reference'!A2)),"YES","NO")
</code>```

This may need to be array entered with Ctrl-Shift-Enter.

Title: INDEX-MATCH and SUMPRODUCT

Body:
I have a list of users and the security groups they're associated with, generated from Active Directory.  It looks like this:

Username  Security Group
Chris     Group A
Chris     Group B
Chris     Group C
Dave      Group D
Dave      Group A
Dave      Group E

I have another list of usernames that I need to cross-reference to determine if a user is a part of one or more specific security groups.  The list of security  groups is dynamic and will change based on some other criteria so I'd like to just reference a named range in my check.

The equation I'm using right now looks like this:

=IF(INDEX('Users in Security Groups'!C:C, MATCH('Cross-Reference'!A2, 'Users in Security Groups'!B:B, 0))=Rng_SecGrp, "YES", "NO")

Because INDEX-MATCH stops on the first value I am getting "NO" for username that I know actually belong to these security groups I'm concerned with.  I imagine the answer lies with array formulas and/or SUMPRODUCT but both are a bit outside my comfort zone and I've failed to nail down the right formula to this point.

Any help is appreciated!  Thanks!

Body:
Use COUNTIFS() not INDEX(,MATCH()):

=IF(SUM(COUNTIFS('Users in Security Groups'!C:C,Rng_SecGrp,'Users in Security Groups'!B:B,'Cross-Reference'!A2)),"YES","NO")

This may need to be array entered with Ctrl-Shift-Enter.


问:
Why is my if statement not working (bash - zenity)?
I am using an if statement to run a different response for each option selected in a yad GUI zenity fork.

For some reason the if statement works with some options and not with others!?

NOTE : I'm substituting '^' for ' in the example

```<code>opt=^yad --list --column="Option"  --column="Description" \
     1 "option 1" \
     2 "option 2
        <i> subtext </i>" \
     | cut -c 1^
echo $opt
if [[ $opt == 1 ]]
then
    echo 1
elif [[ $opt == 2 ]]
then
    echo 2
else
    echo error
</code>```

option one gives: 1 1

option 2 gives: 2 error.

The variable is being recorded right as is evident by the echo $opt output. I know it has something to do with the subtext, if I erase it the problem goes away, but as to why I have no idea.

Can anyone help me with a fix, or suggest a workaround?

Thanks for all of your help! This problem is really stumping me.

答:
Thanks to abhishek phukan for the answer!

By using == the shell wanted to treat the variables as a string, -eq is normally used for integer operations and works better in this case. Why the subtext effected the answer i don't know.

Body:
I am using an if statement to run a different response for each option selected in a yad GUI zenity fork.

For some reason the if statement works with some options and not with others!?

NOTE : I'm substituting '^' for ' in the example

opt=^yad --list --column="Option"  --column="Description" \
     1 "option 1" \
     2 "option 2
         subtext " \
     | cut -c 1^
echo $opt
if [[ $opt == 1 ]]
then
    echo 1
elif [[ $opt == 2 ]]
then
    echo 2
else
    echo error

option one gives: 1 1

option 2 gives: 2 error.

The variable is being recorded right as is evident by the echo $opt output. I know it has something to do with the subtext, if I erase it the problem goes away, but as to why I have no idea.

Can anyone help me with a fix, or suggest a workaround?

Thanks for all of your help! This problem is really stumping me.


问:
Give CSS property to parent td using CSS
I have referred to many options but still I am not able to apply CSS to my parent container. My table structure is like:

```<code><td>
  <div id="div1">
      <div id="div2" class="colorMe"></div>
  </div>
</td>
</code>```

Now according to above structure if div2 has class colorMe then I want to color the entire td background in yellow.

I have used CSS like this but not working:

```<code>td > div> div.colorMe {
background-color:yellow;
}
</code>```

Can you please tell me how I can color my td using css?

答:
You can kind of emulate the behavior you need with the following trick:

td {
  position: relative; /* make the cell a container for positioned children */
}

.colorMe::before { /* cover this container with colored pseudo element */
  content: '';
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
  background-color:yellow;
  z-index: -1;
}

table { /* just to make the example prettier :) */
  width: 100%;
  height: 100px;
  table-layout: fixed;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td>
      Just a TD
    </td>
    <td>
      <div id="div1">
          <div id="div2" class="colorMe"></div>
      </div>
    </td>
    <td>
      Just a TD again
    </td>
  </tr>
</table></code>```

It won't work, however, if you need to position something absolutely from the .colorMe element itself.

Body:
I have referred to many options but still I am not able to apply CSS to my parent container. My table structure is like:

Now according to above structure if div2 has class colorMe then I want to color the entire td background in yellow.

I have used CSS like this but not working:

td > div> div.colorMe {
background-color:yellow;
}

Can you please tell me how I can color my td using css?

Body:
You can kind of emulate the behavior you need with the following trick:

td {
  position: relative; /* make the cell a container for positioned children */
}

.colorMe::before { /* cover this container with colored pseudo element */
  content: '';
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
  background-color:yellow;
  z-index: -1;
}

table { /* just to make the example prettier :) */
  width: 100%;
  height: 100px;
  table-layout: fixed;
}

<table>
  <tr>
    <td>
      Just a TD
    </td>
    <td>
      <div id="div1">
          <div id="div2" class="colorMe"></div>
      </div>
    </td>
    <td>
      Just a TD again
    </td>
  </tr>
</table>

It won't work, however, if you need to position something absolutely from the .colorMe element itself.


问:
How to use Substring to find a character and update date format?
I have a field in one table named SourceID.  All records have a bunch of '|' characters, and after the last pipe is a date, in four different format.  I am trying to update this date to be in one single format.  The data looks like this.

```<code>SourceID
ARS|1C47|13.2|2017-09-29
mm|M8|160|030|ZX7|Sep 29 2017 12:00AM
TMP_Schedule | Int | MG100 | 20370429
TS|01|0|USD|I|S|ZDER|10/31/2017
</code>```

I tried to come up with code to update another field (SourceID_Revised), in the same table, with all data from SourceID and one standardized date format, such as DD/MM/YYYY.  I tried some different ideas, and came up with this, which is think is close, but of course it doesn't work.

```<code>UPDATE    TBL_HIST
SET       SourceID_Revised = SourceID
WHERE     (SELECT CONVERT(VARCHAR(8), SUBSTRING([SourceID],select dbo.LastIndexOf('|', [SourceID]),99)) AS [DD/MM/YYYY]
FROM [dbo].[TBL_HIST]
</code>```

Using this to find the last pipe.

```<code>FUNCTION [dbo].[LastIndexOf] (@stringToFind varchar(max), @stringToSearch varchar(max))
RETURNS INT
AS
BEGIN
    RETURN (LEN(@stringToSearch) - CHARINDEX(@stringToFind,REVERSE(@stringToSearch))) + 1
END
</code>```

I'm on SQL Server 2008.

UPDATE:

John, I think this could work!  It runs for about 5 seconds and then konks out.  I get this message.

Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.

I'm guessing, that because some records in that field have nothing at all like a date.  So I have things like this:

```<code>40285
3467868
</code>```

I think that is causing an error.  How can I skip those, or just do some  kind of On Error Resume Next?

One more thing that I noticed is that several hundred records have this format.

```<code>101.002.112020-06-30
102.0012.102019-09-30
125.02.022022-06-30
</code>```

For these, I want to find the last dot, move to to the right, and get

```<code>MM/DD/YYYY:
06/30/2020
09/30/2019
06/30/2022
</code>```

NOT DD/MM/YY!

答:
Since you are not on 2012+, you can't use try_convert()

The following works with the sample provided,  but I have concerns of conversion failures (i.e. bogus dates)

Note, the following can be converted to inline if you can't use or want the Parse UDF.

Example

```<code>Declare @YourTable Table ([SourceID] varchar(50))
Insert Into @YourTable Values
('RS|1C47|13.2|2017-09-29'),
('mm|M8|160|030|ZX7|Sep 29 2017 12:00AM'),
('TMP_Schedule | Int | MG100 | 20370429'),
('TS|01|0|USD|I|S|ZDER|10/31/2017')

Update @YourTable Set SourceID=Replace(SourceID,RetVal,AsDate)
  From @YourTable A
  Cross Apply (
                Select Top 1 *,AsDate = convert(varchar(10),convert(Date,RetVal),101)
                 From  [dbo].[tvf-Str-Parse]([SourceID],'|')
                 Order By RetSeq Desc
               ) B

Select * From  @YourTable
</code>```

Returns Updated Table

```<code>SourceID
RS|1C47|13.2|09/29/2017
mm|M8|160|030|ZX7|09/29/2017
TMP_Schedule | Int | MG100 | 04/29/2037
TS|01|0|USD|I|S|ZDER|10/31/2017
</code>```

The UDF if Interested

```<code>CREATE FUNCTION [dbo].[tvf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table
As
Return (
    Select RetSeq = Row_Number() over (Order By (Select null))
          ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
    From  (Select x = Cast('<x>' + replace((Select replace(@String,@Delimiter,'§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
    Cross Apply x.nodes('x') AS B(i)
);
--Thanks Shnugo for making this XML safe
--Select * from [dbo].[tvf-Str-Parse]('Dog,Cat,House,Car',',')
--Select * from [dbo].[tvf-Str-Parse]('John Cappelletti was here',' ')
--Select * from [dbo].[tvf-Str-Parse]('this,is,<test>,for,< & >',',')
</code>```

Body:
I have a field in one table named SourceID.  All records have a bunch of '|' characters, and after the last pipe is a date, in four different format.  I am trying to update this date to be in one single format.  The data looks like this.

SourceID
ARS|1C47|13.2|2017-09-29
mm|M8|160|030|ZX7|Sep 29 2017 12:00AM
TMP_Schedule | Int | MG100 | 20370429
TS|01|0|USD|I|S|ZDER|10/31/2017

I tried to come up with code to update another field (SourceID_Revised), in the same table, with all data from SourceID and one standardized date format, such as DD/MM/YYYY.  I tried some different ideas, and came up with this, which is think is close, but of course it doesn't work.

UPDATE    TBL_HIST
SET       SourceID_Revised = SourceID
WHERE     (SELECT CONVERT(VARCHAR(8), SUBSTRING([SourceID],select dbo.LastIndexOf('|', [SourceID]),99)) AS [DD/MM/YYYY]
FROM [dbo].[TBL_HIST]

Using this to find the last pipe.

FUNCTION [dbo].[LastIndexOf] (@stringToFind varchar(max), @stringToSearch varchar(max))
RETURNS INT
AS
BEGIN
    RETURN (LEN(@stringToSearch) - CHARINDEX(@stringToFind,REVERSE(@stringToSearch))) + 1
END

I'm on SQL Server 2008.

UPDATE:

John, I think this could work!  It runs for about 5 seconds and then konks out.  I get this message.

Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.

I'm guessing, that because some records in that field have nothing at all like a date.  So I have things like this:

40285
3467868

I think that is causing an error.  How can I skip those, or just do some  kind of On Error Resume Next?

One more thing that I noticed is that several hundred records have this format.

101.002.112020-06-30
102.0012.102019-09-30
125.02.022022-06-30

For these, I want to find the last dot, move to to the right, and get

MM/DD/YYYY:
06/30/2020
09/30/2019
06/30/2022

NOT DD/MM/YY!

Body:
Since you are not on 2012+, you can't use try_convert()

The following works with the sample provided,  but I have concerns of conversion failures (i.e. bogus dates)

Note, the following can be converted to inline if you can't use or want the Parse UDF.

Example

Declare @YourTable Table ([SourceID] varchar(50))
Insert Into @YourTable Values
('RS|1C47|13.2|2017-09-29'),
('mm|M8|160|030|ZX7|Sep 29 2017 12:00AM'),
('TMP_Schedule | Int | MG100 | 20370429'),
('TS|01|0|USD|I|S|ZDER|10/31/2017')

Update @YourTable Set SourceID=Replace(SourceID,RetVal,AsDate)
  From @YourTable A
  Cross Apply (
                Select Top 1 *,AsDate = convert(varchar(10),convert(Date,RetVal),101)
                 From  [dbo].[tvf-Str-Parse]([SourceID],'|')
                 Order By RetSeq Desc
               ) B

Select * From  @YourTable

Returns Updated Table

SourceID
RS|1C47|13.2|09/29/2017
mm|M8|160|030|ZX7|09/29/2017
TMP_Schedule | Int | MG100 | 04/29/2037
TS|01|0|USD|I|S|ZDER|10/31/2017

The UDF if Interested

CREATE FUNCTION [dbo].[tvf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table
As
Return (
    Select RetSeq = Row_Number() over (Order By (Select null))
          ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
    From  (Select x = Cast('<x>' + replace((Select replace(@String,@Delimiter,'§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
    Cross Apply x.nodes('x') AS B(i)
);
--Thanks Shnugo for making this XML safe
--Select * from [dbo].[tvf-Str-Parse]('Dog,Cat,House,Car',',')
--Select * from [dbo].[tvf-Str-Parse]('John Cappelletti was here',' ')
--Select * from [dbo].[tvf-Str-Parse]('this,is,<test>,for,< & >',',')


问:
Enabling SSH compression in Sourcetree Windows for a mercurial repository
I am on  Windows 7 - Sourcetree 1.4.1.0 - Embedded Mercurial 2.6.1

Target is a private mercurial repo hosted on bitbucket.

How do I enable SSH compression so that my transactions are faster?

答:
In my case, I'm using TortoiseHg, but the concept should be the same.

Here is my original c:\somerepo\.hg\hgrc file:

```<code>[paths]
default = ssh://hg@bitbucket.org/someuser/somerepo
</code>```

So what's happening with ssh?  Let's debug a pull statement, hg pull --debug on the command-line.  I noticed it is running C:\Program Files\TortoiseHg\lib\TortoisePlink.exe instead of ssh to make the call:

```<code>PS C:\somerepo> hg pull --debug
pulling from ssh://hg@bitbucket.org/someuser/somerepo
running "C:\Program Files\TortoiseHg\lib\TortoisePlink.exe" -ssh -2 hg@bitbucket.org "hg -R someuser/somerepo serve --stdio"
sending hello command
sending between command
abort: no suitable response from remote hg!
</code>```

So let's just reuse the call, add compression (yay!), non-interactive (batch) and our key:

```<code>[paths]
default = ssh://hg@bitbucket.org/someuser/somerepo

[ui]
ssh = "C:\Program Files\TortoiseHg\lib\TortoisePlink.exe" -ssh -2 -C -batch -i "c:\keys\somekey.ppk"
</code>```

Body:
In my case, I'm using TortoiseHg, but the concept should be the same.

Here is my original c:\somerepo\.hg\hgrc file:

[paths]
default = ssh://hg@bitbucket.org/someuser/somerepo

So what's happening with ssh?  Let's debug a pull statement, hg pull --debug on the command-line.  I noticed it is running C:\Program Files\TortoiseHg\lib\TortoisePlink.exe instead of ssh to make the call:

PS C:\somerepo> hg pull --debug
pulling from ssh://hg@bitbucket.org/someuser/somerepo
running "C:\Program Files\TortoiseHg\lib\TortoisePlink.exe" -ssh -2 hg@bitbucket.org "hg -R someuser/somerepo serve --stdio"
sending hello command
sending between command
abort: no suitable response from remote hg!

So let's just reuse the call, add compression (yay!), non-interactive (batch) and our key:

[paths]
default = ssh://hg@bitbucket.org/someuser/somerepo

[ui]
ssh = "C:\Program Files\TortoiseHg\lib\TortoisePlink.exe" -ssh -2 -C -batch -i "c:\keys\somekey.ppk"


问:
Send ArrayList<Float> between Activities
I have to draw a graph from the values stored in an ArrayList named "subZ" (It has 252 elements). In my main activity I store the values and then in the next activity I have to draw.

So I send it like this:

```<code>Intent change_screen = new Intent(MeasureScreenActivity.this, ResultScreenActivity.class);
//Send variables to another activity
change_screen.putExtra("standard_measurement",standard_measurement);
change_screen.putExtra("current_measurement",current_measurement);
change_screen.putExtra("subZ", subZ);
startActivity(change_screen);
//Effect of transition
overridePendingTransition(R.anim.fade_in,R.anim.fade_out);
finish();
</code>```

And in the other activity I recieve it like this:

```<code>//Store the data passed from MeasureScreenActivity
Intent intent = getIntent();
Bundle bundle = intent.getExtras();

//Make sure that bundle is not null
if(bundle != null) {
    standard_measurement = (String) bundle.get("standard_measurement");
    current_measurement = (int) bundle.get("current_measurement");
    subZ = (ArrayList<Float>) bundle.get("subZ");
}
</code>```

My question is: Is well done in this way? Because the metod putExtra(String, ArrayList) does not exist really.

I know about other way that is cast the ArrayList to array:

```<code>Float aux[] = subZ.toArray();
</code>```

And use the method putExtra(String, Float[]) to send in the same way than before.

I do not know which on in the best way to do this because I do not want to saturate the main thread.

Other way that I am thinking is to draw in the main activity and then send the draw to the next activity to show it. But I do not know if it is possible.

Which one of this three options will saturate less the main thread?

答:
Did you try using Serializable?

```<code>ArrayList<Float> list = new ArrayList<>();
Intent i = new Intent(MeasureScreenActivity.this, ResultScreenActivity.class);
i.putExtra("arg_key", list);
</code>```

Get Extra

```<code>ArrayList<Float> list = ( ArrayList<Float>) getIntent().getSerializableExtra("arg_key");
</code>```

Body:
I have to draw a graph from the values stored in an ArrayList named "subZ" (It has 252 elements). In my main activity I store the values and then in the next activity I have to draw.

So I send it like this:

Intent change_screen = new Intent(MeasureScreenActivity.this, ResultScreenActivity.class);
//Send variables to another activity
change_screen.putExtra("standard_measurement",standard_measurement);
change_screen.putExtra("current_measurement",current_measurement);
change_screen.putExtra("subZ", subZ);
startActivity(change_screen);
//Effect of transition
overridePendingTransition(R.anim.fade_in,R.anim.fade_out);
finish();

And in the other activity I recieve it like this:

//Store the data passed from MeasureScreenActivity
Intent intent = getIntent();
Bundle bundle = intent.getExtras();

//Make sure that bundle is not null
if(bundle != null) {
    standard_measurement = (String) bundle.get("standard_measurement");
    current_measurement = (int) bundle.get("current_measurement");
    subZ = (ArrayList<Float>) bundle.get("subZ");
}

My question is: Is well done in this way? Because the metod putExtra(String, ArrayList) does not exist really.

I know about other way that is cast the ArrayList to array:

Float aux[] = subZ.toArray();

And use the method putExtra(String, Float[]) to send in the same way than before.

I do not know which on in the best way to do this because I do not want to saturate the main thread.

Other way that I am thinking is to draw in the main activity and then send the draw to the next activity to show it. But I do not know if it is possible.

Which one of this three options will saturate less the main thread?

Body:
Did you try using Serializable?

ArrayList<Float> list = new ArrayList<>();
Intent i = new Intent(MeasureScreenActivity.this, ResultScreenActivity.class);
i.putExtra("arg_key", list);

Get Extra

ArrayList<Float> list = ( ArrayList<Float>) getIntent().getSerializableExtra("arg_key");


问:
Wrap img in div on click
I would like to wrap an image in a div element when the image is clicked. Once this is done, I would like to add a class attribute on the div. I'm looking for a utility in jQuery that could help achieve the first task.

```<code>$(img).on('click', function() {
   // wrap this image in div
})
</code>```

While a jQuery implementation is preferable, vanilla dom scripting is ok as well.

答:
You can do this with the following code:</p>

```<code>$(img).on('click', function() {
   $(this).wrap('<div></div>')
});
</code>```

Title: Wrap img in div on click

Body:
I would like to wrap an image in a div element when the image is clicked. Once this is done, I would like to add a class attribute on the div. I'm looking for a utility in jQuery that could help achieve the first task.

$(img).on('click', function() {
   // wrap this image in div
})

While a jQuery implementation is preferable, vanilla dom scripting is ok as well.

Body:
You can do this with the following code:

$(img).on('click', function() {
   $(this).wrap('<div></div>')
});


问:
PDFBox TextToPdf keep font
I am currently converting a text document to pdf and rendering it to the browser and cannot seem to keep the font. The font is courier but gets converted to something else when it is converted to a pdf. Is there a easy way to just make it keep the default font? Or at least be able to set it after converting? here is the code.

```<code>public void downloadFile(HttpServletResponse response, List<Report> reports) throws IOException{
    OutputStream outputStream = response.getOutputStream();
    PDFMergerUtility pdfMergerUtility = new PDFMergerUtility();
    PDDocument documentToPrint = new PDDocument();
    for(Report report : reports){
        PDDocument pdDocument = new TextToPDF().createPDFFromText(new InputStreamReader(
                new FileInputStream(fileDirectory + File.separator + report.getFileLocation()), "UTF8")
        );
        pdfMergerUtility.appendDocument(documentToPrint, pdDocument);
    }
    pdfMergerUtility.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());

    response.setContentType("application/pdf");
    response.addHeader("Content-Disposition", "inline; filename=" + "download.pdf");
    documentToPrint.save(outputStream);
    documentToPrint.close();
}
</code>```

I have also tried setting it like the following before appending the document.

```<code>    PDDocumentCatalog documentCatalog = pdDocument.getDocumentCatalog();
    PDResources pdResources = documentCatalog.getPages().get(i).getResources();
    pdResources.add(PDType1Font.COURIER);
    documentCatalog.getPages().get(i++).setResources(pdResources);
</code>```

But that does not seem to work either

答:
Because I have a the font in the text document as courier.

No you don't, editors usually display it with Courier. So you have to set it because the default is Helvetica.

Change this:

```<code>PDDocument pdDocument = new TextToPDF().createPDFFromText(new InputStreamReader(....
</code>```

to this:

```<code>TextToPDF textToPDF = new TextToPDF();
textToPDF.setFont(PDType1Font.COURIER);
textToPDF.createPDFFromText(new InputStreamReader(....
</code>```

Title: PDFBox TextToPdf keep font

Body:
I am currently converting a text document to pdf and rendering it to the browser and cannot seem to keep the font. The font is courier but gets converted to something else when it is converted to a pdf. Is there a easy way to just make it keep the default font? Or at least be able to set it after converting? here is the code.

public void downloadFile(HttpServletResponse response, List<Report> reports) throws IOException{
    OutputStream outputStream = response.getOutputStream();
    PDFMergerUtility pdfMergerUtility = new PDFMergerUtility();
    PDDocument documentToPrint = new PDDocument();
    for(Report report : reports){
        PDDocument pdDocument = new TextToPDF().createPDFFromText(new InputStreamReader(
                new FileInputStream(fileDirectory + File.separator + report.getFileLocation()), "UTF8")
        );
        pdfMergerUtility.appendDocument(documentToPrint, pdDocument);
    }
    pdfMergerUtility.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());

    response.setContentType("application/pdf");
    response.addHeader("Content-Disposition", "inline; filename=" + "download.pdf");
    documentToPrint.save(outputStream);
    documentToPrint.close();
}

I have also tried setting it like the following before appending the document.

    PDDocumentCatalog documentCatalog = pdDocument.getDocumentCatalog();
    PDResources pdResources = documentCatalog.getPages().get(i).getResources();
    pdResources.add(PDType1Font.COURIER);
    documentCatalog.getPages().get(i++).setResources(pdResources);

But that does not seem to work either

Body:
Because I have a the font in the text document as courier.

No you don't, editors usually display it with Courier. So you have to set it because the default is Helvetica.

Change this:

PDDocument pdDocument = new TextToPDF().createPDFFromText(new InputStreamReader(....

to this:

TextToPDF textToPDF = new TextToPDF();
textToPDF.setFont(PDType1Font.COURIER);
textToPDF.createPDFFromText(new InputStreamReader(....


问:
Defining the same phrase for both `Given` and `Then` steps
I'm looking for suggestions or best practices here.

Sometimes I would like to give the same regex/phrase for 2 different steps using different prepositions. The case I see often is a phrase that makes sense in both Given and in Then steps.

Given being used for a step that performs and action (to setup the test state).
And Then being used for a step that verifies the state, but doesn't perform an action. Quite often I find the same phrasing works right for both. An example such phrase is "I am logged in"

Here is a contrived scenario

```<code>Scenario: Login is saved between sessions.
    Given I am logged in
    When I exit the application
    And I start the application
    Then I am logged in
</code>```

Of course this doesn't work in the step definitions because cucumber doesn't differentiate between step predicates.

I've toyed with adding 'verify' to all colliding Then steps, or adding a 'that' to all duplicated Given steps. But nothing sits right.

```<code>Given that I am logged in.
...
Then verify I am logged in.
</code>```

It works of course, but I feel I'm missing something that doesn't require having the same "extended predicate" for most of my steps.

答:
I've had the same question, this is the answer I got:

Step Definitions have to be unique for Cucumber to know what to execute. In addition, the Given/When/Then keywords are technically interchangeable. They're for the readability of the feature file, but not linked to the implementation. So if both steps (Given and Then) do the same thing, there is technically no problem; you should be able to use the same step definition from your feature file, preceded by either 'Given' or 'Then' keyword. That said, you might want to consider rewriting your step definitions to describe the intended behavior instead of the implementation, e.g. "Given an element with id xxx"

Body:
I'm looking for suggestions or best practices here.

Sometimes I would like to give the same regex/phrase for 2 different steps using different prepositions. The case I see often is a phrase that makes sense in both Given and in Then steps.

Given being used for a step that performs and action (to setup the test state).
And Then being used for a step that verifies the state, but doesn't perform an action. Quite often I find the same phrasing works right for both. An example such phrase is "I am logged in"

Here is a contrived scenario

Scenario: Login is saved between sessions.
    Given I am logged in
    When I exit the application
    And I start the application
    Then I am logged in

Of course this doesn't work in the step definitions because cucumber doesn't differentiate between step predicates.

I've toyed with adding 'verify' to all colliding Then steps, or adding a 'that' to all duplicated Given steps. But nothing sits right.

Given that I am logged in.
...
Then verify I am logged in.

It works of course, but I feel I'm missing something that doesn't require having the same "extended predicate" for most of my steps.


问:
Mongoose query altering object order
I have a query that is generated in my Node backend - if I log it out and run it in Mongo shell then all is fine, however, if I use mongoose to do Model.find(query), then some strange property re-ordering takes place and the query breaks.

The query in question is:

```<code>{
    "attributes": {
        "$all": [
            {
                "attribute": "an id",
                "value": "a value",
                "deletedOn": null
            },
            {
                "attribute": "an id again",
                "value": "a value",
                "deletedOn": null
            }
        ]
    }
}
</code>```

However, the output from mongoose debug is:

```<code>users.find({
    attributes: {
        '$all': [
            {
                deletedOn: null,
                attribute: 'an id',
                value: 'a value'
            },
            {
                deletedOn: null,
                attribute: 'an id again',
                value: 'a value'
            }
        ]
    }
},
    { fields: {} }
)
</code>```

The only change is the shifting of the deletedOn field from last position to first position in the object.  This means the query returns no results.

Are there any solutions to this issue?

答:
Adding on the previous answer, if order is important to you, you should use array instead of objects.

for example:

```<code>"$all": [
    [
        {"attribute": "an id"},
        {"value": "a value"},
        {"deletedOn": null},
    ],
    ...etc.
]
</code>```

Title: Mongoose query altering object order

Body:
I have a query that is generated in my Node backend - if I log it out and run it in Mongo shell then all is fine, however, if I use mongoose to do Model.find(query), then some strange property re-ordering takes place and the query breaks.

The query in question is:

{
    "attributes": {
        "$all": [
            {
                "attribute": "an id",
                "value": "a value",
                "deletedOn": null
            },
            {
                "attribute": "an id again",
                "value": "a value",
                "deletedOn": null
            }
        ]
    }
}

However, the output from mongoose debug is:

users.find({
    attributes: {
        '$all': [
            {
                deletedOn: null,
                attribute: 'an id',
                value: 'a value'
            },
            {
                deletedOn: null,
                attribute: 'an id again',
                value: 'a value'
            }
        ]
    }
},
    { fields: {} }
)

The only change is the shifting of the deletedOn field from last position to first position in the object.  This means the query returns no results.

Are there any solutions to this issue?

Body:
Adding on the previous answer, if order is important to you, you should use array instead of objects.

for example:

"$all": [
    [
        {"attribute": "an id"},
        {"value": "a value"},
        {"deletedOn": null},
    ],
    ...etc.
]


问:
2d array with parameter
I am trying to create a 2d array but I don't seem to be able to pass a value in the constructor.

For example

```<code>public class MyObj
{
    public string State {get; private set;}
    public MyObj(string s)
    {
         this.State = s;
    }
}
</code>```

And in another class

```<code>private MyObj[,] Obj;
private void Setup()
{
    this.Obj = new MyObj[5,5];
}
</code>```

When I review this.Obj the value of State is always null. I understand why but without looping over each item in the array (after it's created) and setting the State property (removing the private set) I'm not sure if I have other options?

Whilst I know the syntax is wrong, something like

```<code>this.Obj = new MyObj("default text for each item in array")[5,5,]
</code>```

答:
When creating an array, you are only allocating space for the potential objects.  You are not actually assigning any objects to those spaces.  Defining the array as new MyObj[5,5] results in a 5x5 array consisting of all nulls.  You would still need to initialize each member of the array.  It's during this initialization that you can assign the default values.

Alternatively, you could use the inline initialization syntax.

var a = new MyObj[,]{ {new MyObj('default'), new MyObj('default2') ...}, {...} ...}

Title: 2d array with parameter

Body:
I am trying to create a 2d array but I don't seem to be able to pass a value in the constructor.

For example

public class MyObj
{
    public string State {get; private set;}
    public MyObj(string s)
    {
         this.State = s;
    }
}

And in another class

private MyObj[,] Obj;
private void Setup()
{
    this.Obj = new MyObj[5,5];
}

When I review this.Obj the value of State is always null. I understand why but without looping over each item in the array (after it's created) and setting the State property (removing the private set) I'm not sure if I have other options?

Whilst I know the syntax is wrong, something like

this.Obj = new MyObj("default text for each item in array")[5,5,]


问:
Binary diff and patch utility for a virtual machine image
I need to release some software quite frequently, and the software is contained as a VMWare disk file, i.e., .vmdk file.
What I want is some kind of binary diff and patch utility to make the delta generated as small as possible.

答:
Let me start off with tried-and-true approaches, then point out some more recent approaches.

approaches that I have seen work with binary files

A long time ago, people expanded the old and the new versions of a binary file into temporary "text" files (every byte expanded to 3 bytes: 2 hex digits and a newline).
Then run these two "text" files through an old version of "diff" (that definitely couldn't handle binary files) to make a patch file.
Then we transmitted that "text" patch file over communication lines that were not yet 8-bit-clean.
On the receive end, one expanded the old binary file into a temporary text version, then patched that old text file, and then compressed the new text file back into a binary file (compressing each pair of hex digits into one byte, and throwing away the newlines and any carriage returns that might have crept in).

More recently, I have been using rsync (or some utility built on top of it such as Unison).
It handles arbitrary binary files just fine.
I generally do a live update, with Unison running on my local machine and rsync running on the file server, talking back and forth to each other.

No matter how a patch file is generated, you can use any data compression utility to compress that file.

approaches that, as far as I know, ought to work with binary files

StackOverflow: "how to crate a PATCH file for the binary difference output file"
suggests using bsdiff.

Another StackOverflow question implies that "vimdiff" seems to handle arbitrary bytes adequately.

StackOverflow: "Useful Binary Diff Tool" mentions a few other binary difference tools.

I hear that some tools based on rsync -- "rdiff" and "rdiff-backup" and "duplicity" -- allow you create a patch file.
Then a person who receives that patch file can use it to update their old binary file to a new binary file.

The Wikipedia claims that recent versions of the standard "diff" and "patch" utilities support binary files.
Have you tried that?

cutting-edge research in executable file compression

If you are interested in cutting-edge research on making the delta file as small as possible when updating executable files, you'll want to check out
"How Courgette works"
by Stephen Adams 2009 at The Chromium Projects.

Among other things, the computer that receives the patch "disassembles" the old application, converting all absolute addresses and offsets into symbols; then patches the disassembled code; then "reassembles" the patched code into the new version of the application.

ContentLicense: CC BY-SA 2.5


问:
Laravel view content showing twice for routes with parameters
I am working with Laravel 5.5, I have two get routes with parameters like this

Route::get( 'route/{parameter}', 'Controller@action' )->name( 'controller.action' );

My controller action is simply loading the view:

```<code>public function action( $slug ) {
    return view( 'view', [
        'post' => Post::whereSlug( $slug )->first()
    ] );
}
</code>```

My base app.blade.php view content is:

```<code><!-- ==========================
  PAGE WRAPPER
=========================== -->
<div class="page-wrapper">

    <!-- ==========================
          HEADER
        =========================== -->
    <header class="header" id="header">

        <!-- Hamburger -->
        <div class="h-hamburger" id="hamburger">
            <svg class="h-hamburger__icon">
                <use xlink:href="#icon-hamburger"></use>
            </svg>
        </div>

        <!-- Logo -->
        <div class="h-logo">
            <a href="{{route('dashboard')}}" title="{{config('app.name','Sensei U')}}">
                <img class="h-logo__img" src="{{URL::to('/')}}/images/logo-black.svg"
                     alt="{{ config('app.name', 'Sensei U') }}">
            </a>
        </div>

    @if (Auth::user())

        <!-- Welcome -->
            <div class="h-welcome">

                <!-- Title -->
                <div class="h-welcome__title">Welcome Back, {{Auth::user()->name}}</div>

                <!-- Date -->
                <div class="h-welcome__date">{{date('F j')}}</div>

                <!-- Time -->
                <div class="h-welcome__time">{{date('g:i a')}}</div>

            </div>
            <!-- Profile -->
            <div class="h-profile">

                <!-- Avatar -->
                <img class="h-profile__avatar"
                     src="{{Auth::user()->image ? SenseiU::getImagePathBySize(Storage::url(Auth::user()->image), 58, 58) : ''}}"
                     srcset="{{Auth::user()->image ? SenseiU::getImagePathBySize(Storage::url(Auth::user()->image), 116, 116) : ''}} 2x"
                     alt="{{Auth::user()->name}}">
            @if(($notifications = SenseiU::generateNotificationMessages( Auth::user() )) )
                <!-- Notifications -->
                    <button class="h-profile__notifications" data-uid="{{Auth::user()->id}}"
                            data-url="{{route('member.nr', [Auth::user()])}}">
                        {{count($notifications)}}
                    </button>
                @endif

            </div>

        @if($notifications)

            <!-- Notifications Dropdown -->
                <ul class="noti-dropdown">
                    @foreach($notifications as $notification)
                        <li class="noti-dropdown__item">
                            <a class="noti-dropdown__link" href="{{$notification['link']}}">
                                {{$notification['msg']}}
                            </a>
                        </li>
                    @endforeach
                </ul>
            @endif
        @endif

    </header>
    <!-- ==========================
      CONTENT WRAPPER
    =========================== -->
    <div class="wrapper">
        <!-- ==========================
          SIDEBAR
        =========================== -->
        <aside class="sidebar" id="sidebar">
            <!-- Menu -->
            <nav class="sidebar-menu">
                @if(Auth::user())
                    <a class="sidebar-menu__item {{Route::currentRouteName() == 'dashboard' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('dashboard')}}">
                        <span class="sidebar-menu__title">Home</span>
                    </a>

                    @permission('daily-mastery')
                    <a class="sidebar-menu__item  {{Route::currentRouteName() == 'member.daily-mastery' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('member.daily-mastery')}}">
                        <span class="sidebar-menu__title">Daily Mastery</span>

                        @if(SenseiU::getPageNotificationsCount( Auth::user(), [
                        'App\Notifications\TipPublishedNotification',
                        'App\Notifications\ExerciseSchedulePublishedNotification'] ))

                            <span class="sidebar-menu__notifications">{{SenseiU::getPageNotificationsCount( Auth::user(), [
                        'App\Notifications\TipPublishedNotification',
                        'App\Notifications\ExerciseSchedulePublishedNotification'] )}}</span>
                        @endif
                    </a>
                    @endpermission

                    <a class="sidebar-menu__item {{Route::currentRouteName() == 'member.macros' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('member.macros')}}">
                        <span class="sidebar-menu__title">Macros Calculator</span>
                    </a>

                    <a class="sidebar-menu__item {{Route::currentRouteName() == 'member.instructional-videos' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('member.instructional-videos')}}">
                        <span class="sidebar-menu__title">Instructional Videos</span>
                        @if(SenseiU::getPageNotificationsCount( Auth::user(), [
                        'App\Notifications\VideoPublishedNotification'] ))
                            <span class="sidebar-menu__notifications">{{SenseiU::getPageNotificationsCount( Auth::user(), [
                        'App\Notifications\VideoPublishedNotification'] )}}</span>
                        @endif
                    </a>

                    @permission('health-articles')
                    <a class="sidebar-menu__item {{Route::currentRouteName() == 'member.nutrition' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('member.nutrition')}}">
                        <span class="sidebar-menu__title">Nutrition</span>
                        @if(SenseiU::getArticleSectionNotificationsCount( Auth::user(), 2 ))
                            <span class="sidebar-menu__notifications">{{SenseiU::getArticleSectionNotificationsCount( Auth::user(), 2 )}}</span>
                        @endif
                    </a>

                    <a class="sidebar-menu__item {{Route::currentRouteName() == 'member.sports-injuries' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('member.sports-injuries')}}">
                        <span class="sidebar-menu__title">Sports Injuries</span>
                        @if(SenseiU::getArticleSectionNotificationsCount( Auth::user(), 3 ))
                            <span class="sidebar-menu__notifications">{{SenseiU::getArticleSectionNotificationsCount( Auth::user(), 3 )}}</span>
                        @endif
                    </a>

                    <a class="sidebar-menu__item {{Route::currentRouteName() == 'member.mobility-stretching' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('member.mobility-stretching')}}">
                        <span class="sidebar-menu__title">Mobility & Stretching</span>
                        @if(SenseiU::getArticleSectionNotificationsCount( Auth::user(), 4 ))
                            <span class="sidebar-menu__notifications">{{SenseiU::getArticleSectionNotificationsCount( Auth::user(), 4 )}}</span>
                        @endif
                    </a>

                    <a class="sidebar-menu__item {{Route::currentRouteName() == 'member.functional-training' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('member.functional-training')}}">
                        <span class="sidebar-menu__title">Functional Training</span>
                        @if(SenseiU::getArticleSectionNotificationsCount( Auth::user(), 5 ))
                            <span class="sidebar-menu__notifications">{{SenseiU::getArticleSectionNotificationsCount( Auth::user(), 5 )}}</span>
                        @endif
                    </a>

                    <a class="sidebar-menu__item {{Route::currentRouteName() == 'member.articles' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('member.articles')}}">
                        <span class="sidebar-menu__title">Articles</span>
                        @if(SenseiU::getArticleSectionNotificationsCount( Auth::user(), 1 ))
                            <span class="sidebar-menu__notifications">{{SenseiU::getArticleSectionNotificationsCount( Auth::user(), 1 )}}</span>
                        @endif
                    </a>
                    @endpermission

                    <a class="sidebar-menu__item {{Route::currentRouteName() == 'member.faqs' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('member.faqs')}}">
                        <span class="sidebar-menu__title">FAQs</span>
                    </a>

                    <a class="sidebar-menu__item" href="#">
                        <span class="sidebar-menu__title">Ultimate Personal Trainer</span>
                    </a>
                    <a class="sidebar-menu__item {{Route::currentRouteName() == 'member.profile.edit' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('member.profile.edit')}}">
                        <span class="sidebar-menu__title">Edit Profile</span>
                    </a>
                    <a class="sidebar-menu__item" href="{{URL::to('logout')}}">
                        <span class="sidebar-menu__title">Logout</span>
                    </a>
                @else
                    <a class="sidebar-menu__item {{Route::currentRouteName() == 'login' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('login')}}">
                        <span class="sidebar-menu__title">Login</span>
                    </a>

                    <a class="sidebar-menu__item {{Route::currentRouteName() == 'register' ? 'sidebar-menu__item--active' : ''}}"
                       href="{{route('register')}}">
                        <span class="sidebar-menu__title">Register</span>
                    </a>
                @endif
            </nav>

        </aside>

        <!-- ==========================
              CONTENT
            =========================== -->
        <main class="content @yield('main-class')">
            <!-- Container -->
            <div class="@yield('container-class')">
                @if(session('msg'))
                    <div class="msg msg-{{session('status')}}">
                        {{session('msg')}}
                    </div>
                @endif
                @yield('content')
            </div>
        </main>
    </div>
</div>
</code>```

My view content is like this:

```<code>@extends('layouts.app')

@section('title', $title)
@section('container-class', 'container')

@section('content')
    @if($post)
        <div class="cover" style="background-image:url('{{Storage::url($post->file)}}');"></div>
        <article class="article__container">
            <h1>{{$post->title}}</h1>
            <div>{!!$post->text!!}</div>
        </article>
    @endif
@stop
</code>```

The problem is that my view content is showing duplicated, one 404 on top of the actual view content like this:

答:
I figured it out and I will leave an answer for future reference, the problem wasn't with Laravel, it was a javascript issue, I had this code on the head:

```<code>    <script>
    var ajax = new XMLHttpRequest();

    ajax.open('GET', '/images/sprites.svg', true);

    ajax.send();

    ajax.onload = function (e) {

        var div = document.createElement('div');

        div.innerHTML = ajax.responseText;

        document.body.insertBefore(div, document.body.childNodes[0]);

    };
</script>
</code>```

which loads an svg sprite and insert it into the page to be used, the ajax url was returning a 404 on routes with parameters, so a 404 page was showing above the views, I fixed it by using an absolute url like this:

```<code>ajax.open('GET', '{{URL::to('/')}}/images/sprites.svg', true);
</code>```

Thank you all for your help.

Body:
I am working with Laravel 5.5, I have two get routes with parameters like this

Route::get( 'route/{parameter}', 'Controller@action' )->name( 'controller.action' );

My controller action is simply loading the view:

public function action( $slug ) {
    return view( 'view', [
        'post' => Post::whereSlug( $slug )->first()
    ] );
}

My base app.blade.php view content is:

            <svg class="h-hamburger__icon">
                <use xlink:href="#icon-hamburger"></use>
            </svg>

    @if (Auth::user())

Welcome Back, {{Auth::user()->name}}

{{date('F j')}}

{{date('g:i a')}}

                image ? SenseiU::getImagePathBySize(Storage::url(Auth::user()->image), 58, 58) : ''}}"
                     srcset="{{Auth::user()->image ? SenseiU::getImagePathBySize(Storage::url(Auth::user()->image), 116, 116) : ''}} 2x"
                     alt="{{Auth::user()->name}}">
            @if(($notifications = SenseiU::generateNotificationMessages( Auth::user() )) )

                    <button class="h-profile__notifications" data-uid="{{Auth::user()->id}}"
                            data-url="{{route('member.nr', [Auth::user()])}}">
                        {{count($notifications)}}
                    </button>
                @endif

        @if($notifications)

                    @foreach($notifications as $notification)

                                {{$notification['msg']}}

                    @endforeach

            @endif
        @endif

                @if(Auth::user())

                        Home

                    @permission('daily-mastery')

                        Daily Mastery

                        @if(SenseiU::getPageNotificationsCount( Auth::user(), [
                        'App\Notifications\TipPublishedNotification',
                        'App\Notifications\ExerciseSchedulePublishedNotification'] ))

                            {{SenseiU::getPageNotificationsCount( Auth::user(), [
                        'App\Notifications\TipPublishedNotification',
                        'App\Notifications\ExerciseSchedulePublishedNotification'] )}}
                        @endif

                    @endpermission

                        Macros Calculator

                        Instructional Videos
                        @if(SenseiU::getPageNotificationsCount( Auth::user(), [
                        'App\Notifications\VideoPublishedNotification'] ))
                            {{SenseiU::getPageNotificationsCount( Auth::user(), [
                        'App\Notifications\VideoPublishedNotification'] )}}
                        @endif

                    @permission('health-articles')

                        Nutrition
                        @if(SenseiU::getArticleSectionNotificationsCount( Auth::user(), 2 ))
                            {{SenseiU::getArticleSectionNotificationsCount( Auth::user(), 2 )}}
                        @endif

                        Sports Injuries
                        @if(SenseiU::getArticleSectionNotificationsCount( Auth::user(), 3 ))
                            {{SenseiU::getArticleSectionNotificationsCount( Auth::user(), 3 )}}
                        @endif

                        Mobility & Stretching
                        @if(SenseiU::getArticleSectionNotificationsCount( Auth::user(), 4 ))
                            {{SenseiU::getArticleSectionNotificationsCount( Auth::user(), 4 )}}
                        @endif

                        Functional Training
                        @if(SenseiU::getArticleSectionNotificationsCount( Auth::user(), 5 ))
                            {{SenseiU::getArticleSectionNotificationsCount( Auth::user(), 5 )}}
                        @endif

                        Articles
                        @if(SenseiU::getArticleSectionNotificationsCount( Auth::user(), 1 ))
                            {{SenseiU::getArticleSectionNotificationsCount( Auth::user(), 1 )}}
                        @endif

                    @endpermission

                        FAQs

                        Ultimate Personal Trainer

                        Edit Profile

                        Logout

                @else

                        Login

                        Register

                @endif

                @if(session('msg'))

                        {{session('msg')}}

                @endif
                @yield('content')

My view content is like this:

@extends('layouts.app')

@section('title', $title)
@section('container-class', 'container')

@section('content')
    @if($post)

file)}}');">

{{$post->title}}

{!!$post->text!!}

    @endif
@stop

The problem is that my view content is showing duplicated, one 404 on top of the actual view content like this:

Body:
I figured it out and I will leave an answer for future reference, the problem wasn't with Laravel, it was a javascript issue, I had this code on the head:

    <script>
    var ajax = new XMLHttpRequest();

    ajax.open('GET', '/images/sprites.svg', true);

    ajax.send();

    ajax.onload = function (e) {

        var div = document.createElement('div');

        div.innerHTML = ajax.responseText;

        document.body.insertBefore(div, document.body.childNodes[0]);

    };
</script>

which loads an svg sprite and insert it into the page to be used, the ajax url was returning a 404 on routes with parameters, so a 404 page was showing above the views, I fixed it by using an absolute url like this:

ajax.open('GET', '{{URL::to('/')}}/images/sprites.svg', true);

Thank you all for your help.


问:
How to compare values using Id from $scope value in html
I want to compare values as new value and old value on the basis of id. I just want to get a condition to put the correct value at the right place

Here is the Html :

```<code><div ng-repeat = "values in aAndaData track by $index"> {{aAndaData}}
                                        <li ng-if="old  != null || new !=null" >
                                            <strong>Account Executive : </strong><span ng-if="data.id==data.id" class="past-data">{{old.fullName}}</span> <i class=" fa fa-angle-double-right"></i> <span ng-if="data.id!=data.id">{{new.fullName}}<!-- {{quotation.accountExecutive.lastName}}--></span>
                                        </li>
                                        </div>
</code>```

PS : How to check the condition
Thanks in advance

答:
You need to make sure you save the changed value in different variable, or else you are technically overwriting.

```<code>$scope.data.id = oldvalue;
$scope.datacc.id = angular.copy(oldValue);

function(somechange) {
    $scope.datacc.id = newValue;
}
</code>```

that way... ng-if= "data.id == datacc.id"> {{oldvalue}} else newValue. So here if the datacc.id will be in same state as oldvalue initially, but if the value changed then that original value will be overwritten.

Hope that helps.

Body:
I want to compare values as new value and old value on the basis of id. I just want to get a condition to put the correct value at the right place

Here is the Html :

 {{aAndaData}}

                                            Account Executive : {{old.fullName}}  {{new.fullName}}

PS : How to check the condition
Thanks in advance

Body:
You need to make sure you save the changed value in different variable, or else you are technically overwriting.

$scope.data.id = oldvalue;
$scope.datacc.id = angular.copy(oldValue);

function(somechange) {
    $scope.datacc.id = newValue;
}

that way... ng-if= "data.id == datacc.id"> {{oldvalue}} else newValue. So here if the datacc.id will be in same state as oldvalue initially, but if the value changed then that original value will be overwritten.

Hope that helps.


问:
Passing merchant key and salt in website
I have integrated payu in my website for transaction. I have a doubt, in their dev guide they pass merchant key, salt, hash etc. to form parameters. Now, if anybody does an inspect element in my website then he/she can see those parameters.I want to know the best way people use payu apis and how do they make sure that mechant id, salt remains on server only. My backend is in django and front end in angular js</p>

答:
Afaik, that hash is calculated in the backend based on a secret word known only by PayU and the merchant (you should keep that stored in the environment), therefore no security issues if someone inspects the form and see's those elements, paypal, cybersource, etc are also doing the same. No need to doubt, go ahead and finalise the integration.

To be able to use their API and integrate server2server method your employer should be PCI Compliance, which is not actually a small thing.


问:
Reading a file in Python in Ubuntu
I'm trying to access a .txt file in my root account to open and read in python. My code looks like this:

```<code>>>> path = 'root/unpackedFiles/enrollment_fact.txt'
>>> read = open(path,'r')
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    read = open(path,'r')
FileNotFoundError: [Errno 2] No such file or directory: 'root/unpackedFiles/enrollment_fact.txt'
</code>```

I've also tried several variations of this with no such luck. Including:

path = 'unpackedFiles/enrollment_fact.txt' and path = 'enrollment_fact.txt'

答:
```<code>>>> path = 'ports.txt'
>>> read = open ( path, 'r')
>>> print(read)
<_io.TextIOWrapper name='ports.txt' mode='r' encoding='cp1252'>
>>> exit()
</code>```

You have to give either relative path or absolute path.And your code you are missing / before root and so interpreter unable to find the file at given path.

Relative path:

```<code>$ ls ports.txt
ports.txt
</code>```

Absolute path:

```<code>$ readlink -f ports.txt
/c/Users/rgenupula/ports.txt
</code>```

ContentLicense: CC BY-SA 4.0

Title: Reading a file in Python in Ubuntu

Body:
I'm trying to access a .txt file in my root account to open and read in python. My code looks like this:

>>> path = 'root/unpackedFiles/enrollment_fact.txt'
>>> read = open(path,'r')
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    read = open(path,'r')
FileNotFoundError: [Errno 2] No such file or directory: 'root/unpackedFiles/enrollment_fact.txt'

I've also tried several variations of this with no such luck. Including:

path = 'unpackedFiles/enrollment_fact.txt' and path = 'enrollment_fact.txt'

Body:
>>> path = 'ports.txt'
>>> read = open ( path, 'r')
>>> print(read)
<_io.TextIOWrapper name='ports.txt' mode='r' encoding='cp1252'>
>>> exit()

You have to give either relative path or absolute path.And your code you are missing / before root and so interpreter unable to find the file at given path.

Relative path:

$ ls ports.txt
ports.txt

Absolute path:

$ readlink -f ports.txt
/c/Users/rgenupula/ports.txt


问:
Powershell Code for a birthday cake
My son is a computer science major, and his birthday is coming up. I want to create a code themed cake for him. I have studied PowerShell code and created what I think is something correct and fun. However, I'm unsure and was turned on to this site to get help with it. This is what I have ... JularJ is my son's display name for his video games.</p>

```<code>$day=11/21/2017
$today=Get-Date
if (Today=$day)
{
    echo"Happy 18th Birthday [Jular]"}
else
{
    echo"Eat Cake Anyway"
}
</code>```

答:
Here's mine, a shorter version without variables:

```<code>if ([datetime]::Now.ToString("MM/dd/yyyy") -eq "11/21/2017")
{
    "Happy 18th Birthday [Jular]"
}
else
{
    "Eat Cake Anyway"
}
</code>```

Happy Birthday :)

Title: Powershell Code for a birthday cake

Body:
My son is a computer science major, and his birthday is coming up. I want to create a code themed cake for him. I have studied PowerShell code and created what I think is something correct and fun. However, I'm unsure and was turned on to this site to get help with it. This is what I have ... JularJ is my son's display name for his video games.

$day=11/21/2017
$today=Get-Date
if (Today=$day)
{
    echo"Happy 18th Birthday [Jular]"}
else
{
    echo"Eat Cake Anyway"
}

Body:
Here's mine, a shorter version without variables:

if ([datetime]::Now.ToString("MM/dd/yyyy") -eq "11/21/2017")
{
    "Happy 18th Birthday [Jular]"
}
else
{
    "Eat Cake Anyway"
}

Happy Birthday :)