问:
TListview FMX onclick event along with Toggle Design

The implementation is the following:

```<code>ds.first;
  while not(ds.Eof) do
    begin
      L := LV1.Items.Add;
      L.Data['Part_No']   := ds.FieldByName('Part_no').AsString;
      L.Data['Part_Name'] := ds.FieldByName('Part_name').AsString;
      L.Data['LocNo']     := ds.FieldByName('Loc_No').AsString;
      L.Data['Qty']       := ds.FieldByName('BAL').AsFloat;
      ds.Next;
    end;
</code>```

I add items dynamically using code

How can OnItemClick event fire to detect which element has been clicked. Very frustrating to find out just simple thing.

Any help appreciated.

答:
A bit thrown together, however it should have you started:

```<code>function GetClickedDrawable(const AItem: TListViewItem; APoint: TPointF): TListItemDrawable;
var
  I: Integer;
begin
  Result := nil;
  // Fudge for statusbar height if using iOS. Should be done properly
  APoint := PointF(APoint.X, APoint.Y - 20);
  for I := 0 to AItem.Objects.ViewList.Count - 1 do
  begin
    if AItem.Objects.ViewList[I].InLocalRect(APoint) then
    begin
      Result := AItem.Objects.ViewList[I];
      Break;
    end;
  end;
end;

procedure TForm1.ListViewItemClick(const Sender: TObject; const AItem: TListViewItem);
var
  LDrawable: TListItemDrawable;
begin
  LDrawable := GetClickedDrawable(AItem, ListView.AbsoluteToLocal(Screen.MousePos));
  if LDrawable <> nil then
    ShowMessage(LDrawable.Name);
end;
</code>```

You'll need to adjust GetClickedDrawable to suit whatever platform you're on. PS: Thanks for asking; I'm going to need to do something very much like this, eventually :-)

EDIT:

I've left my original answer in place in case the following is not available in earlier versions of Delphi:

Use the OnItemClickEx event. The parameters of the event make it pretty self explanatory

Don't know why I didn't see that earlier :-)

Body:
The implementation is the following:

ds.first;
  while not(ds.Eof) do
    begin
      L := LV1.Items.Add;
      L.Data['Part_No']   := ds.FieldByName('Part_no').AsString;
      L.Data['Part_Name'] := ds.FieldByName('Part_name').AsString;
      L.Data['LocNo']     := ds.FieldByName('Loc_No').AsString;
      L.Data['Qty']       := ds.FieldByName('BAL').AsFloat;
      ds.Next;
    end;

I add items dynamically using code

How can OnItemClick event fire to detect which element has been clicked. Very frustrating to find out just simple thing.

Any help appreciated.

Body:
A bit thrown together, however it should have you started:

function GetClickedDrawable(const AItem: TListViewItem; APoint: TPointF): TListItemDrawable;
var
  I: Integer;
begin
  Result := nil;
  // Fudge for statusbar height if using iOS. Should be done properly
  APoint := PointF(APoint.X, APoint.Y - 20);
  for I := 0 to AItem.Objects.ViewList.Count - 1 do
  begin
    if AItem.Objects.ViewList[I].InLocalRect(APoint) then
    begin
      Result := AItem.Objects.ViewList[I];
      Break;
    end;
  end;
end;

procedure TForm1.ListViewItemClick(const Sender: TObject; const AItem: TListViewItem);
var
  LDrawable: TListItemDrawable;
begin
  LDrawable := GetClickedDrawable(AItem, ListView.AbsoluteToLocal(Screen.MousePos));
  if LDrawable <> nil then
    ShowMessage(LDrawable.Name);
end;

You'll need to adjust GetClickedDrawable to suit whatever platform you're on. PS: Thanks for asking; I'm going to need to do something very much like this, eventually :-)

EDIT:

I've left my original answer in place in case the following is not available in earlier versions of Delphi:

Use the OnItemClickEx event. The parameters of the event make it pretty self explanatory

Don't know why I didn't see that earlier :-)


来源: stackexchange

问:
Automated string insertion on windows
Normally I'm a mac person, but at my new job I'm finding myself using a PC. I often have to open html files and for every href link insert a target blank argument. Rather then do this manually I was wondering if there was a script that I could use to automate the process. Say:

search for href

find the second double quotation after the href string

insert the string "target = _blank"

Mind you I have never used a shell script on a PC in my life, so much explanation might be needed here.

Thanks,

答: Just get a copy of sed for win32 (perhaps form here) and do it the usual sed way.</p>

ContentLicense: CC BY-SA 2.5

Title: Automated string insertion on windows


问:
Error extending Shape class
Im getting an error in my C# code and I cant figure out why

```<code>namespace Memory
{
    class Meme : Shape
    {
        public int used { get; set; }
        public string name { get; set; }

        protected override Geometry DefiningGeometry => throw new NotImplementedException();
    }
}
</code>```

The error im getting is:

System.NotImplementedException: 'The method or operation is not implemented.'

code creating the instance:

```<code>options.Add(new Meme()
    {
     name  =  option,
            used = 0,
            Width = 50,
            Height = 50,
            Fill = Brushes.Red
        });
</code>```

答:
Your custom Shape class is supposed to actually return a Geometry of some kind. This will at least compile:

```<code>class Meme : Shape
{
    public int used { get; set; }
    public string name { get; set; }

    protected override Geometry DefiningGeometry
    {
        get
        {
            return new EllipseGeometry(new Point(50, 50), 45, 20);
        }
    }
}
</code>```

But if you don't know what geometry to return from the DefiningGeometry property, you might ask yourself whether you really want to create a custom Shape class in the first place...

ContentLicense: CC BY-SA 3.0

Title: Error extending Shape class

Body:
Im getting an error in my C# code and I cant figure out why

namespace Memory
{
    class Meme : Shape
    {
        public int used { get; set; }
        public string name { get; set; }

        protected override Geometry DefiningGeometry => throw new NotImplementedException();
    }
}

The error im getting is:

System.NotImplementedException: 'The method or operation is not implemented.'

code creating the instance:

options.Add(new Meme()
    {
     name  =  option,
            used = 0,
            Width = 50,
            Height = 50,
            Fill = Brushes.Red
        });

Body:
Your custom Shape class is supposed to actually return a Geometry of some kind. This will at least compile:

class Meme : Shape
{
    public int used { get; set; }
    public string name { get; set; }

    protected override Geometry DefiningGeometry
    {
        get
        {
            return new EllipseGeometry(new Point(50, 50), 45, 20);
        }
    }
}

But if you don't know what geometry to return from the DefiningGeometry property, you might ask yourself whether you really want to create a custom Shape class in the first place...


问:
UIImage to another UIImage
In my project, I have two UIViewControllers. On my first ViewController, I have a UIImageView and there is an image from an url. On the second ViewController, I have an empty UIImageView.

When the user clicks on the image in the UIImageView on the first ViewController, the image in the second ViewController (which was empty before) should be the same like the clicked one on the first ViewController.

Is something like that possible? The image is from a url (like I wrote before), so i think it should work, but I have no idea how I can do that.

答:
Create a static property of UIImage in firstVC

```<code>static var imageFromUrl = UIImage()
</code>```

Get image from url & assign it into imageFromUrl.

Now you can use in all ViewControllers simply calling by

```<code>FirstVC.imageFromUrl
</code>```

Title: UIImage to another UIImage

Body:
Create a static property of UIImage in firstVC

static var imageFromUrl = UIImage()

Get image from url & assign it into imageFromUrl.

Now you can use in all ViewControllers simply calling by

FirstVC.imageFromUrl


问:
Angularjs loading screen on ajax request
Using Angularjs , I need to show a loading screen (a simple spinner) until ajax request is complete. Please suggest any idea with a code snippet.</p>

答:
You could add a condition and then change it via the rootscope. Before your ajax request, you simply call $rootScope.$emit('stopLoader');

```<code>angular.module('directive.loading', [])
        .directive('loading',   ['$http', '$rootScope',function ($http, $rootScope)
        {
            return {
                restrict: 'A',
                link: function (scope, elm, attrs)
                {
                    scope.isNoLoadingForced = false;
                    scope.isLoading = function () {
                        return $http.pendingRequests.length > 0 && scope.isNoLoadingForced;
                    };

                    $rootScope.$on('stopLoader', function(){
                        scope.isNoLoadingForced = true;
                    })

                    scope.$watch(scope.isLoading, function (v)
                    {
                        if(v){
                            elm.show();
                        }else{
                            elm.hide();
                        }
                    });
                }
            };

        }]);
</code>```

This is definatly not the best solution but it would still works.

Body:
You could add a condition and then change it via the rootscope. Before your ajax request, you simply call $rootScope.$emit('stopLoader');

angular.module('directive.loading', [])
        .directive('loading',   ['$http', '$rootScope',function ($http, $rootScope)
        {
            return {
                restrict: 'A',
                link: function (scope, elm, attrs)
                {
                    scope.isNoLoadingForced = false;
                    scope.isLoading = function () {
                        return $http.pendingRequests.length > 0 && scope.isNoLoadingForced;
                    };

                    $rootScope.$on('stopLoader', function(){
                        scope.isNoLoadingForced = true;
                    })

                    scope.$watch(scope.isLoading, function (v)
                    {
                        if(v){
                            elm.show();
                        }else{
                            elm.hide();
                        }
                    });
                }
            };

        }]);

This is definatly not the best solution but it would still works.


问:
Prevent resizing of a view controller presented as a sheet?
Is there a way to prevent a view from being resized if the view controller is presented as a sheet using the method presentViewControllerAsSheet or using a segue of style "sheet"?

Note that modal/show segues can be implanted to a window controller which can be set as non resizable from the storyboard itself. Segues of type popover are non-resizable by default.

答:
None of the other solutions worked for me, so I ended up using an NSWindow as the sheet controller (rather than a NSViewController on its own).

Declare an NSWindowController object in your header file:

```<code>NSWindowController *detailWindow;
</code>```

To open the window in the form of a sheet, use the following code:

```<code>NSStoryboard *storyFile = [NSStoryboard storyboardWithName:@"Main" bundle:nil];
detailWindow = [storyFile instantiateInitialController];
[self.view.window beginSheet:detailWindow.window completionHandler:nil];
</code>```

To close the window:

```<code>[self.view.window endSheet:detailWindow.window];
</code>```

In order to stop the window sheet from being resized, simply set the NSWindow minimum/maximum size in interface builder:

That's it, super easy! (Don't forget to set the window controller, as the initial controller).

ContentLicense: CC BY-SA 4.0

Body:
None of the other solutions worked for me, so I ended up using an NSWindow as the sheet controller (rather than a NSViewController on its own).

Declare an NSWindowController object in your header file:

NSWindowController *detailWindow;

To open the window in the form of a sheet, use the following code:

NSStoryboard *storyFile = [NSStoryboard storyboardWithName:@"Main" bundle:nil];
detailWindow = [storyFile instantiateInitialController];
[self.view.window beginSheet:detailWindow.window completionHandler:nil];

To close the window:

[self.view.window endSheet:detailWindow.window];

In order to stop the window sheet from being resized, simply set the NSWindow minimum/maximum size in interface builder:

That's it, super easy! (Don't forget to set the window controller, as the initial controller).


问:
Paste special method of Range class failed - error 104
Hopefully this should be straight forward but I can't see what I have missed. I am getting the runtime error on the Paste Special line just after clearing the contents of Column A on the "original" sheet. Can someone please help me?</p>

```<code> Sub BACSConversion2()

 Dim MyNewBook As String
 Dim MySaveFile As String
 Dim fileToOpen As Variant
 Dim fileName As String
 Dim sheetName As String

 'Turn off display alerts
 Application.DisplayAlerts = False
 'Turn off screen updates
 Application.ScreenUpdating = False

 'This calls the routine to get the text file data
 'Call CopyTxtFile

 'Opens the folder to location to select txt file
 fileToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt")
 If fileToOpen <> False Then

    Workbooks.OpenText fileName:=fileToOpen, _
    DataType:=xlDelimited, Tab:=True
 End If
 'Creates the file name based on txt file name
 fileName = Mid(fileToOpen, InStrRev(fileToOpen, "\") + 1)
 'Creates the sheet name based on the active txt file
 sheetName = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4)

 'Save active file as...
 ActiveWorkbook.SaveAs ("S:\Accounts (New)\Management Information
 (Analysis)\Phil Hanmore - Analysis\Neil Test\Test Destination Folder\" &
 fileName & ".CSV")

 'Selects all data in column A and copies to clipboard
 Range("A1", Range("A1").End(xlDown)).Select
 Selection.Copy
 'Closes the workbook
 'ActiveWorkbook.Close

 'Open the original document where the BACS file is located
 Workbooks.Open "S:\Accounts (New)\Management Information (Analysis)\Phil
  Hanmore - Analysis\Neil Test\copy of bacs conversation calc.xlsx"
 'Selects the worksheet called "Original"
 Sheets("Original").Select

 Range("A:A").ClearContents

 'Paste selected values from previous sheet
 Selection.PasteSpecial Paste:=xlPasteValues

 'Selects appropriate worksheet - Non-MyPayFINAL
 Sheets("Non-MyPay FINAL").Select

 'Selects all data in column A and copies to clipboard
 Range("A1", Range("A1").End(xlDown)).Select
  Selection.Copy

 'Add a new workbook
 Workbooks.Add
 'Paste selected values from previous sheet
 Selection.PasteSpecial Paste:=xlPasteValues

 'Build SaveAs file name
    MySaveFile = Format(Now(), "DDMMYYYY") & "NonMyPayFINAL" & ".CSV"
    'Save template file as...
    ActiveWorkbook.SaveAs ("S:\Accounts (New)\Management Information
  (Analysis)\Phil Hanmore - Analysis\Neil Test\" & MySaveFile)
    'Close the new saved file
    ActiveWorkbook.Close

 'Selects appropriate worksheet - MyPayFINAL
 Sheets("MyPay FINAL").Select

 'Selects all data in column A and copies to clipboard
 Range("A1", Range("A1").End(xlDown)).Select
 Selection.Copy

 'Add a new workbook
 Workbooks.Add
 'Paste selected values from previous sheet
 Selection.PasteSpecial Paste:=xlPasteValues

 'Build SaveAs file name
    MySaveFile = Format(Now(), "DDMMYYYY") & "MyPayFINAL" & ".CSV"
    'Save template file as...
    ActiveWorkbook.SaveAs ("S:\Accounts (New)\Management Information
  (Analysis)\Phil Hanmore - Analysis\Neil Test\" & MySaveFile)
    'Close the new saved file
    ActiveWorkbook.Close
 'Close original source workbook
  Workbooks("bacs conversation calc").Close

 'Turn on display alerts
 Application.DisplayAlerts = True
 'Turn on screen updates
 Application.ScreenUpdating = True

 End Sub
</code>```

答:
This code actually assigns the copy range to a variable and uses that. Because you are using various workbooks and sheets it would be good practice to assign variables to them and refer to them directly so that there is no doubt about which file you are referencing. I'm not 100% sure what you are doing so have not done that.</p>

```<code>Sub BACSConversion2()

Dim MyNewBook As String
Dim MySaveFile As String
Dim fileToOpen As Variant
Dim fileName As String
Dim sheetName As String
Dim rCopy As Range

'Turn off display alerts
Application.DisplayAlerts = False
'Turn off screen updates
Application.ScreenUpdating = False

'This calls the routine to get the text file data
'Call CopyTxtFile

'Opens the folder to location to select txt file
fileToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt")
If fileToOpen <> False Then
    Workbooks.OpenText fileName:=fileToOpen, _
    DataType:=xlDelimited, Tab:=True
End If
'Creates the file name based on txt file name
fileName = Mid(fileToOpen, InStrRev(fileToOpen, "\") + 1)
'Creates the sheet name based on the active txt file
sheetName = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4)

'Save active file as...
ActiveWorkbook.SaveAs ("S:\Accounts (New)\Management Information (Analysis)\Phil Hanmore - Analysis\Neil Test\Test Destination Folder\" & _
fileName & ".CSV")

'Selects all data in column A and copies to clipboard
Set rCopy = Range("A1", Range("A1").End(xlDown))
'Closes the workbook
'ActiveWorkbook.Close

'Open the original document where the BACS file is located
Workbooks.Open "S:\Accounts (New)\Management Information (Analysis)\Phil Hanmore - Analysis\Neil Test\copy of bacs conversation calc.xlsx"
'Selects the worksheet called "Original"
Sheets("Original").Range("A:A").ClearContents

'Paste selected values from previous sheet
rCopy.Copy
Sheets("Original").Range("A1").PasteSpecial Paste:=xlPasteValues

'Selects appropriate worksheet - Non-MyPayFINAL
Sheets("Non-MyPay FINAL").Select

'Selects all data in column A and copies to clipboard
Range("A1", Range("A1").End(xlDown)).Select
Selection.Copy

'Add a new workbook
Workbooks.Add
'Paste selected values from previous sheet
Selection.PasteSpecial Paste:=xlPasteValues

'Build SaveAs file name
MySaveFile = Format(Now(), "DDMMYYYY") & "NonMyPayFINAL" & ".CSV"
'Save template file as...
ActiveWorkbook.SaveAs ("S:\Accounts (New)\Management Information (Analysis)\Phil Hanmore - Analysis\Neil Test\" & MySaveFile)
'Close the new saved file
ActiveWorkbook.Close

'Selects appropriate worksheet - MyPayFINAL
Sheets("MyPay FINAL").Select

'Selects all data in column A and copies to clipboard
Range("A1", Range("A1").End(xlDown)).Select
Selection.Copy

'Add a new workbook
Workbooks.Add
'Paste selected values from previous sheet
Selection.PasteSpecial Paste:=xlPasteValues

'Build SaveAs file name
MySaveFile = Format(Now(), "DDMMYYYY") & "MyPayFINAL" & ".CSV"
'Save template file as...
ActiveWorkbook.SaveAs ("S:\Accounts (New)\Management Information (Analysis)\Phil Hanmore - Analysis\Neil Test\" & MySaveFile)
'Close the new saved file
ActiveWorkbook.Close
'Close original source workbook
Workbooks("bacs conversation calc").Close

'Turn on display alerts
Application.DisplayAlerts = True
'Turn on screen updates
Application.ScreenUpdating = True

End Sub
</code>```

Body:
Hopefully this should be straight forward but I can't see what I have missed. I am getting the runtime error on the Paste Special line just after clearing the contents of Column A on the "original" sheet. Can someone please help me?

 Sub BACSConversion2()

 Dim MyNewBook As String
 Dim MySaveFile As String
 Dim fileToOpen As Variant
 Dim fileName As String
 Dim sheetName As String

 'Turn off display alerts
 Application.DisplayAlerts = False
 'Turn off screen updates
 Application.ScreenUpdating = False

 'This calls the routine to get the text file data
 'Call CopyTxtFile

 'Opens the folder to location to select txt file
 fileToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt")
 If fileToOpen <> False Then

    Workbooks.OpenText fileName:=fileToOpen, _
    DataType:=xlDelimited, Tab:=True
 End If
 'Creates the file name based on txt file name
 fileName = Mid(fileToOpen, InStrRev(fileToOpen, "\") + 1)
 'Creates the sheet name based on the active txt file
 sheetName = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4)

 'Save active file as...
 ActiveWorkbook.SaveAs ("S:\Accounts (New)\Management Information
 (Analysis)\Phil Hanmore - Analysis\Neil Test\Test Destination Folder\" &
 fileName & ".CSV")

 'Selects all data in column A and copies to clipboard
 Range("A1", Range("A1").End(xlDown)).Select
 Selection.Copy
 'Closes the workbook
 'ActiveWorkbook.Close

 'Open the original document where the BACS file is located
 Workbooks.Open "S:\Accounts (New)\Management Information (Analysis)\Phil
  Hanmore - Analysis\Neil Test\copy of bacs conversation calc.xlsx"
 'Selects the worksheet called "Original"
 Sheets("Original").Select

 Range("A:A").ClearContents

 'Paste selected values from previous sheet
 Selection.PasteSpecial Paste:=xlPasteValues

 'Selects appropriate worksheet - Non-MyPayFINAL
 Sheets("Non-MyPay FINAL").Select

 'Selects all data in column A and copies to clipboard
 Range("A1", Range("A1").End(xlDown)).Select
  Selection.Copy

 'Add a new workbook
 Workbooks.Add
 'Paste selected values from previous sheet
 Selection.PasteSpecial Paste:=xlPasteValues

 'Build SaveAs file name
    MySaveFile = Format(Now(), "DDMMYYYY") & "NonMyPayFINAL" & ".CSV"
    'Save template file as...
    ActiveWorkbook.SaveAs ("S:\Accounts (New)\Management Information
  (Analysis)\Phil Hanmore - Analysis\Neil Test\" & MySaveFile)
    'Close the new saved file
    ActiveWorkbook.Close

 'Selects appropriate worksheet - MyPayFINAL
 Sheets("MyPay FINAL").Select

 'Selects all data in column A and copies to clipboard
 Range("A1", Range("A1").End(xlDown)).Select
 Selection.Copy

 'Add a new workbook
 Workbooks.Add
 'Paste selected values from previous sheet
 Selection.PasteSpecial Paste:=xlPasteValues

 'Build SaveAs file name
    MySaveFile = Format(Now(), "DDMMYYYY") & "MyPayFINAL" & ".CSV"
    'Save template file as...
    ActiveWorkbook.SaveAs ("S:\Accounts (New)\Management Information
  (Analysis)\Phil Hanmore - Analysis\Neil Test\" & MySaveFile)
    'Close the new saved file
    ActiveWorkbook.Close
 'Close original source workbook
  Workbooks("bacs conversation calc").Close

 'Turn on display alerts
 Application.DisplayAlerts = True
 'Turn on screen updates
 Application.ScreenUpdating = True

 End Sub

Body:
This code actually assigns the copy range to a variable and uses that. Because you are using various workbooks and sheets it would be good practice to assign variables to them and refer to them directly so that there is no doubt about which file you are referencing. I'm not 100% sure what you are doing so have not done that.

Sub BACSConversion2()

Dim MyNewBook As String
Dim MySaveFile As String
Dim fileToOpen As Variant
Dim fileName As String
Dim sheetName As String
Dim rCopy As Range

'Turn off display alerts
Application.DisplayAlerts = False
'Turn off screen updates
Application.ScreenUpdating = False

'This calls the routine to get the text file data
'Call CopyTxtFile

'Opens the folder to location to select txt file
fileToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt")
If fileToOpen <> False Then
    Workbooks.OpenText fileName:=fileToOpen, _
    DataType:=xlDelimited, Tab:=True
End If
'Creates the file name based on txt file name
fileName = Mid(fileToOpen, InStrRev(fileToOpen, "\") + 1)
'Creates the sheet name based on the active txt file
sheetName = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4)

'Save active file as...
ActiveWorkbook.SaveAs ("S:\Accounts (New)\Management Information (Analysis)\Phil Hanmore - Analysis\Neil Test\Test Destination Folder\" & _
fileName & ".CSV")

'Selects all data in column A and copies to clipboard
Set rCopy = Range("A1", Range("A1").End(xlDown))
'Closes the workbook
'ActiveWorkbook.Close

'Open the original document where the BACS file is located
Workbooks.Open "S:\Accounts (New)\Management Information (Analysis)\Phil Hanmore - Analysis\Neil Test\copy of bacs conversation calc.xlsx"
'Selects the worksheet called "Original"
Sheets("Original").Range("A:A").ClearContents

'Paste selected values from previous sheet
rCopy.Copy
Sheets("Original").Range("A1").PasteSpecial Paste:=xlPasteValues

'Selects appropriate worksheet - Non-MyPayFINAL
Sheets("Non-MyPay FINAL").Select

'Selects all data in column A and copies to clipboard
Range("A1", Range("A1").End(xlDown)).Select
Selection.Copy

'Add a new workbook
Workbooks.Add
'Paste selected values from previous sheet
Selection.PasteSpecial Paste:=xlPasteValues

'Build SaveAs file name
MySaveFile = Format(Now(), "DDMMYYYY") & "NonMyPayFINAL" & ".CSV"
'Save template file as...
ActiveWorkbook.SaveAs ("S:\Accounts (New)\Management Information (Analysis)\Phil Hanmore - Analysis\Neil Test\" & MySaveFile)
'Close the new saved file
ActiveWorkbook.Close

'Selects appropriate worksheet - MyPayFINAL
Sheets("MyPay FINAL").Select

'Selects all data in column A and copies to clipboard
Range("A1", Range("A1").End(xlDown)).Select
Selection.Copy

'Add a new workbook
Workbooks.Add
'Paste selected values from previous sheet
Selection.PasteSpecial Paste:=xlPasteValues

'Build SaveAs file name
MySaveFile = Format(Now(), "DDMMYYYY") & "MyPayFINAL" & ".CSV"
'Save template file as...
ActiveWorkbook.SaveAs ("S:\Accounts (New)\Management Information (Analysis)\Phil Hanmore - Analysis\Neil Test\" & MySaveFile)
'Close the new saved file
ActiveWorkbook.Close
'Close original source workbook
Workbooks("bacs conversation calc").Close

'Turn on display alerts
Application.DisplayAlerts = True
'Turn on screen updates
Application.ScreenUpdating = True

End Sub


问:
Sylius - How to assign a Channel to a Product programmatically?
I am trying to assign a Channel to my products created programmatically, so they will be displayed on shop. Unfortunately, there is no documentation for this use case.

Here is how I create my products:

```<code>$productFactory = $this->container->get('sylius.factory.product');
$productManager = $this->container->get('sylius.manager.product');
$productRepository = $this->get('sylius.repository.product');
$productVariantFactory = $this->get('sylius.factory.product_variant');
$productVariantRepository = $this->get('sylius.repository.product_variant');
$channelPricingFactory = $this->get('sylius.factory.channel_pricing');
$channelPricingRepository = $this->get('sylius.repository.channel_pricing');

//CREATE PRODUCT

$product = $factory->createNew();
$product->setName('TEST 2 - '.$title);
$product->setCode($this->generateRandomString());
$product->setSlug($this->generateRandomString());
$productRepository->add($product);

//CREATE VARIANT & ATTACH IT TO PRODUCT

$variant = $productVariantFactory->createNew();
$variant->setName('TEST 2 - '.$title);
$variant->setCode($this->generateRandomString());
$variant->setProduct($product);
$productVariantRepository->add($variant);

//CREATE PRICE & ATTACH IT TO VARIANT

$channelPricing = $channelPricingFactory->createNew();
$channelPricing->setPrice(999);
$channelPricing->setOriginalPrice(999);
$channelPricing->setChannelCode('US_WEB');
$channelPricing->setProductVariant($variant);
$channelPricingRepository->add($channelPricing);
</code>```

Unfortunately, the products are not linked to a Channel:

答:
The answer to your question:

You have one product variant, but Product variant implements ProductVariantInterface which extends TranslatableInterface. So we need one translation to make it appear and work. To add the translation:

```<code>$productVariant->setCurrentLocale('fr_FR');
$productVariantTranslation = $productVariant->getTranslation();
</code>```

or

```<code>$productVariantTranslation = $productVariant->getTranslation($locale);
</code>```

after you can add a name or not:

```<code>$productVariantTranslation->setName('What a product variant!');
</code>```

after:

```<code>$product->addVariant($productVariant);
$this->entityManager->persist($product);
</code>```

You will have your product variant on line.

Another thing is that:

```<code>$channelPricingRepository = $this->get('sylius.repository.channel_pricing');
$channelPricingRepository->add($entity);
</code>```

it's going to flush directly data to DB in each call. In the example you are going to flush 3 times instead only one. In bigger proccess with many "add" this can be a lack of performance. You can simply;

```<code>$this->entityManager->persist($entity); //Many times
$this->entityManager->flush();
</code>```

Body:
I am trying to assign a Channel to my products created programmatically, so they will be displayed on shop. Unfortunately, there is no documentation for this use case.

Here is how I create my products:

$productFactory = $this->container->get('sylius.factory.product');
$productManager = $this->container->get('sylius.manager.product');
$productRepository = $this->get('sylius.repository.product');
$productVariantFactory = $this->get('sylius.factory.product_variant');
$productVariantRepository = $this->get('sylius.repository.product_variant');
$channelPricingFactory = $this->get('sylius.factory.channel_pricing');
$channelPricingRepository = $this->get('sylius.repository.channel_pricing');

//CREATE PRODUCT

$product = $factory->createNew();
$product->setName('TEST 2 - '.$title);
$product->setCode($this->generateRandomString());
$product->setSlug($this->generateRandomString());
$productRepository->add($product);

//CREATE VARIANT & ATTACH IT TO PRODUCT

$variant = $productVariantFactory->createNew();
$variant->setName('TEST 2 - '.$title);
$variant->setCode($this->generateRandomString());
$variant->setProduct($product);
$productVariantRepository->add($variant);

//CREATE PRICE & ATTACH IT TO VARIANT

$channelPricing = $channelPricingFactory->createNew();
$channelPricing->setPrice(999);
$channelPricing->setOriginalPrice(999);
$channelPricing->setChannelCode('US_WEB');
$channelPricing->setProductVariant($variant);
$channelPricingRepository->add($channelPricing);

Unfortunately, the products are not linked to a Channel:

Body:
The answer to your question:

You have one product variant, but Product variant implements ProductVariantInterface which extends TranslatableInterface. So we need one translation to make it appear and work. To add the translation:

$productVariant->setCurrentLocale('fr_FR');
$productVariantTranslation = $productVariant->getTranslation();

or

$productVariantTranslation = $productVariant->getTranslation($locale);

after you can add a name or not:

$productVariantTranslation->setName('What a product variant!');

after:

$product->addVariant($productVariant);
$this->entityManager->persist($product);

You will have your product variant on line.

Another thing is that:

$channelPricingRepository = $this->get('sylius.repository.channel_pricing');
$channelPricingRepository->add($entity);

it's going to flush directly data to DB in each call. In the example you are going to flush 3 times instead only one. In bigger proccess with many "add" this can be a lack of performance. You can simply;

$this->entityManager->persist($entity); //Many times
$this->entityManager->flush();


问:
GWT + Ajax Crawling
I am trying to incorporate Ajax Crawling (http://code.google.com/web/ajaxcrawling/docs/getting-started.html) with my GWT apps.
The app is a single HTML Page with all content rendered using GWT.
I am using GWT-RPC to communicate with the server and the data is exchanged in the form of serializable POJOs. As such, there are no links in my application pointing to any "servlets".

In such a scenario, how would I go about making my app crawlable?

答:
GWT relies on the MVP (Model-View-Presenter) pattern and not MVC. Hence, it is perfectly fine (and expected) if you have just a single HTML page where all the views get rendered.

The way to make your GWT app crawlable is to have distinct URLs for each of your views that you wish to get indexed.

One can go about doing this by using the History mechanism in GWT (click here for docs). ie, For every view, you ought to assign a 'history token' using the hash-bang notation.

GWT 2.1 also introduces the concept of Activities and Places which you can utilize to compartmentalize your ajax app into logically distinct views, each of which would have their own 'history token' and hence a unique crawable URL.

Hope this helps.

Title: GWT + Ajax Crawling


问:
Rails 5.1 minitest flattens array of arrays in params
After upgrading from Rails 4.2 to 5.1 it seems that only for the tests, when I provide something like:

```<code>post :create, params: {
  model: {
    prices: [[2000, "EUR"], [2113.56, "USD"]],
    estimates: [[50, 2500, "EUR"], [505, 2600, "USD"]]
  }
}
</code>```

It is then parsed within the params of the controller as:

```<code>prices: [["2000"], ["EUR"], ["2113.56"], ["USD"]]
estimates: [["50"], ["2500"], ["EUR"], ["505"], ["2600"], ["USD"]]
</code>```

Fortunately, actual calls to the controller are parsed correctly.
I need the tests fixed though obviously, so any help would be really appreciated!

答:
Found the answer after so much time..

We thought that by having only:

@request.headers['Accept'] = 'application/json'

in setup was ok.

But we also had to include:

@request.headers['Content-Type'] = 'application/json'

in order for the params to be parsed correctly!

Body:
After upgrading from Rails 4.2 to 5.1 it seems that only for the tests, when I provide something like:

post :create, params: {
  model: {
    prices: [[2000, "EUR"], [2113.56, "USD"]],
    estimates: [[50, 2500, "EUR"], [505, 2600, "USD"]]
  }
}

It is then parsed within the params of the controller as:

prices: [["2000"], ["EUR"], ["2113.56"], ["USD"]]
estimates: [["50"], ["2500"], ["EUR"], ["505"], ["2600"], ["USD"]]

Fortunately, actual calls to the controller are parsed correctly.
I need the tests fixed though obviously, so any help would be really appreciated!


问:
How can I make setInterval increase each time when user clicks?
This is from JavaScript for kids, and I am stuck. How can I make setInterval increase each time the user clicks on the header? I have tried several solutions such as setInterval(moveheading,counter) or creating multiple setIntervals but it always seems to choose the fastest one and then proceeds to lose the second slowest (creating the opposite desired effect).

I have read that maybe setTimeOut would be a better solution to this, but I am having a hard time figuring out how. The book 'JavaScript for kids' can be found online as a PDF if you need further reference. The page where this challenge is at is 166.

```<code><!DOCTYPE html>
<html>

<head>
    <title>MouseMove</title>
</head>

<body>
    <h1 id='heading'> Try and click me 10 times.</h1>

    <script src='https://code.jquery.com/jquery-2.1.0.js'></script>

    <script>
        var leftOffset = 0;
        var topOffset = (200, 0);
        var rightOffset = 200;
        var toTheTop = (0, 200);
        var counter = 10;
        var congrats = "Congrats you Win!"

        var moveHeading = function() {

            $('#heading').offset({
                top:0,
                left: leftOffset
            });
            leftOffset++;

            if (leftOffset > 200) {

                $('#heading').offset({
                   top: topOffset,
                    left: 200

                });
                topOffset++;

            }
            if (topOffset > 200) {
                 $('#heading').offset({
                     left:rightOffset,
                     top: 200

            });
           rightOffset--

            };
             if (rightOffset < 0) {
                $('#heading').offset({
                 left:(200,0),
                    top:toTheTop

                });
                toTheTop--;
             }

           <p> ijfsdkfjnlskdjfklsdjfs</P>

        if (toTheTop < 0){
      leftOffset = 0,
        topOffset = (200, 0),
         rightOffset = 200,
          toTheTop= (200);

            }

        };

   var ghost = function () {
       $("#heading").text(counter)
       counter--;
   }

     var chill =function ()  {

  if (counter < 7 )
        clearInterval(nuts);}

    var nuts = setTimeout(moveHeading,1000)

  $("#heading").click(moveHeading)
         $("#heading").click(ghost)

        $("#heading").click(chill);
    </script>

</body>
</html>
</code>```

答: To set different (dynamic) duration, we need to stop the current timer, using clearInterval(), then re-run the timer with the new counter.

Body:
This is from JavaScript for kids, and I am stuck. How can I make setInterval increase each time the user clicks on the header? I have tried several solutions such as setInterval(moveheading,counter) or creating multiple setIntervals but it always seems to choose the fastest one and then proceeds to lose the second slowest (creating the opposite desired effect).

I have read that maybe setTimeOut would be a better solution to this, but I am having a hard time figuring out how. The book 'JavaScript for kids' can be found online as a PDF if you need further reference. The page where this challenge is at is 166.

<!DOCTYPE html>

    <title>MouseMove</title>

 Try and click me 10 times.


问:
Passport-twitter: failed to find request token in session
just yesterday on Heroku I started to have this error on twitter login in express

```<code>Error: failed to find request token in session
    at Strategy.<anonymous> (/app/node_modules/passport-twitter/node_modules/passport-oauth/lib/passport-oauth/strategies/oauth.js:120:54)
    at Strategy.authenticate (/app/node_modules/passport-twitter/lib/passport-twitter/strategy.js:82:40)
    at Passport.authenticate (/app/node_modules/passport/lib/passport/middleware/authenticate.js:153:14)
    at callbacks (/app/node_modules/express/lib/router/index.js:272:11)
    at param (/app/node_modules/express/lib/router/index.js:246:11)
    at pass (/app/node_modules/express/lib/router/index.js:253:5)
    at Router._dispatch (/app/node_modules/express/lib/router/index.js:280:4)
    at Object.handle (/app/node_modules/express/lib/router/index.js:45:10)
    at Context.next (/app/node_modules/express/node_modules/connect/lib/http.js:204:15)
    at Context.<anonymous> (/app/node_modules/passport/lib/passport/context/http/actions.js:64:8)
</code>```

any suggestion?

答:
I used passport-flickr and fixed the same problem by changing 127.0.0.1 to localhost

```<code>passport.use(new FlickrStrategy({
    ...
    callbackURL: "http://localhost:3000/auth/flickr/callback"
  },
</code>```

Body:
just yesterday on Heroku I started to have this error on twitter login in express

Error: failed to find request token in session
    at Strategy.<anonymous> (/app/node_modules/passport-twitter/node_modules/passport-oauth/lib/passport-oauth/strategies/oauth.js:120:54)
    at Strategy.authenticate (/app/node_modules/passport-twitter/lib/passport-twitter/strategy.js:82:40)
    at Passport.authenticate (/app/node_modules/passport/lib/passport/middleware/authenticate.js:153:14)
    at callbacks (/app/node_modules/express/lib/router/index.js:272:11)
    at param (/app/node_modules/express/lib/router/index.js:246:11)
    at pass (/app/node_modules/express/lib/router/index.js:253:5)
    at Router._dispatch (/app/node_modules/express/lib/router/index.js:280:4)
    at Object.handle (/app/node_modules/express/lib/router/index.js:45:10)
    at Context.next (/app/node_modules/express/node_modules/connect/lib/http.js:204:15)
    at Context.<anonymous> (/app/node_modules/passport/lib/passport/context/http/actions.js:64:8)

any suggestion?

Body:
I used passport-flickr and fixed the same problem by changing 127.0.0.1 to localhost

passport.use(new FlickrStrategy({
    ...
    callbackURL: "http://localhost:3000/auth/flickr/callback"
  },


问:
c# uwp pointer position
In UWP I am trying to get position of pointer.

I have managed to do it with next Event:

```<code>    private void Grid_PointerMoved(object sender, PointerRoutedEventArgs e)
    {
        PointerPoint point = e.GetCurrentPoint(mainGrid);
        var x = point.Position.X;
        var y = point.Position.Y;
    }
</code>```

And with this way it will be fired all the time. So, I needed some property to get that position. I have found this:

```<code>var pointerPosition = Windows.UI.Core.CoreWindow.GetForCurrentThread().PointerPosition;
</code>```

But it doesn't always return correct position.

Any other property to get current mouse location?

答:
Add PointerMoved event handlers through code

```<code>mainGrid.PointerMoved += mainGrid_PointerMoved;
</code>```

Remove PointerMoved event handlers in the event handler

```<code>mainGrid.PointerMoved -= mainGrid_PointerMoved;
</code>```

Then Get the pointer data in PointerMoved event handlers

```<code>var x = e.GetCurrentPoint(mainGrid).Position.X;
var y = e.GetCurrentPoint(mainGrid).Position.Y;
</code>```

Here is the entire code

```<code>void GetPointerPosition()
{
    mainGrid.PointerMoved += mainGrid_PointerMoved;
}

void MainStack_PointerMoved(object sender, PointerRoutedEventArgs e)
{
    mainGrid.PointerMoved -= mainGrid_PointerMoved;
    var x = e.GetCurrentPoint(mainGrid).Position.X;
    var y = e.GetCurrentPoint(mainGrid).Position.Y;
}
</code>```

Learn more about Adding event handlers in code from here

Title: c# uwp pointer position

Body:
In UWP I am trying to get position of pointer.

I have managed to do it with next Event:

    private void Grid_PointerMoved(object sender, PointerRoutedEventArgs e)
    {
        PointerPoint point = e.GetCurrentPoint(mainGrid);
        var x = point.Position.X;
        var y = point.Position.Y;
    }

And with this way it will be fired all the time. So, I needed some property to get that position. I have found this:

var pointerPosition = Windows.UI.Core.CoreWindow.GetForCurrentThread().PointerPosition;

But it doesn't always return correct position.

Any other property to get current mouse location?

Body:
Add PointerMoved event handlers through code

mainGrid.PointerMoved += mainGrid_PointerMoved;

Remove PointerMoved event handlers in the event handler

mainGrid.PointerMoved -= mainGrid_PointerMoved;

Then Get the pointer data in PointerMoved event handlers

var x = e.GetCurrentPoint(mainGrid).Position.X;
var y = e.GetCurrentPoint(mainGrid).Position.Y;

Here is the entire code

void GetPointerPosition()
{
    mainGrid.PointerMoved += mainGrid_PointerMoved;
}

void MainStack_PointerMoved(object sender, PointerRoutedEventArgs e)
{
    mainGrid.PointerMoved -= mainGrid_PointerMoved;
    var x = e.GetCurrentPoint(mainGrid).Position.X;
    var y = e.GetCurrentPoint(mainGrid).Position.Y;
}

Learn more about Adding event handlers in code from here


问:
model name don't want to override if a same model name using in different fields
I have model and I am binding for two sides. First side is inside of the html p tag.
second side is textarea.
when i change the textarea, inside of the p changes too.
How can i change only textarea?</p>

```<code><div class="title-content">
  <p>{{currentNew.Title}}</p>
</div>
<textarea class="title-textarea" ng-model="currentNew.Title" maxlength="70" style="display:none"></textarea>
</code>```

答:
use the one way binding :: in the paragraph

```<code><div class="title-content">
  <p>{{::currentNew.Title}}</p>
</div>
<textarea class="title-textarea" ng-model="currentNew.Title" maxlength="70" style="display:none"></textarea>
</code>```

Body:
I have model and I am binding for two sides. First side is inside of the html p tag.
second side is textarea.
when i change the textarea, inside of the p changes too.
How can i change only textarea?

{{currentNew.Title}}

<textarea class="title-textarea" ng-model="currentNew.Title" maxlength="70" style="display:none"></textarea>

Body:
use the one way binding :: in the paragraph

<div class="title-content">
  <p>{{::currentNew.Title}}</p>
</div>
<textarea class="title-textarea" ng-model="currentNew.Title" maxlength="70" style="display:none"></textarea>


问:
select query with multiple conditions on same column
i am having 2 master tables with id

```<code>ingredients master
------
id int
name varchar(50)

product master
-----
id int
pname varchar(50)

product ingredients
----
inId int (fk - ingredients master)
prId int (fk - product master)
</code>```

now scenario is that a product is having below data

ingredients master
  ----- (id , name) {[1 , floor], [2 , salt], [3 , sugar], [4 , oil], [5 , pepper]}

product master
   ----- (id , pname) {[1 , chapati], [2 , pizza bun], [3 , chappati type 2], [4 , pizza bun type 2]}

product ingredients
   ----- (inId , prId) {[1, 1], [2, 1], [3, 1], [1, 2], [2, 2], [3, 2], [4, 2], [1, 3], [2, 3], [3, 3], [1, 4], [2, 4], [3, 4], [4, 4]}

now i want to fire a select query where i could get chapati type 2 as an alternative to chapati or pizza bun type 2 as an alternative to pizza bun

i have tried google and much but cannot come up with a feasible solution.

i just want that which is the exact alternate item of the given item. like chapati and chapati type 2 are completely identical in matter of ingredients. and pizza bun and pizza bun type 2 are completely identical but when i am trying queries it gives all items. as there are some items like floor are common in all.

答:
If I understand your question, you can use this query to obtain the ingredients for chapati and pizza bun type 2 (in common):

```<code>select ingredients.id
from ingredients master join product master join product ingredients (complete it)
where product.name in ('chapati', 'pizza bun type 2')
group by ingredients.id
having count(*)>1
</code>```

and then you can find product with similar ingredients

```<code>select product.name
from ingredients master join product master join product ingredients (complete it)
where ingredients.id in (first query)
</code>```

Body:
i am having 2 master tables with id

ingredients master
------
id int
name varchar(50)

product master
-----
id int
pname varchar(50)

product ingredients
----
inId int (fk - ingredients master)
prId int (fk - product master)

now scenario is that a product is having below data

ingredients master
  ----- (id , name) {[1 , floor], [2 , salt], [3 , sugar], [4 , oil], [5 , pepper]}

product master
   ----- (id , pname) {[1 , chapati], [2 , pizza bun], [3 , chappati type 2], [4 , pizza bun type 2]}

product ingredients
   ----- (inId , prId) {[1, 1], [2, 1], [3, 1], [1, 2], [2, 2], [3, 2], [4, 2], [1, 3], [2, 3], [3, 3], [1, 4], [2, 4], [3, 4], [4, 4]}

now i want to fire a select query where i could get chapati type 2 as an alternative to chapati or pizza bun type 2 as an alternative to pizza bun

i have tried google and much but cannot come up with a feasible solution.

i just want that which is the exact alternate item of the given item. like chapati and chapati type 2 are completely identical in matter of ingredients. and pizza bun and pizza bun type 2 are completely identical but when i am trying queries it gives all items. as there are some items like floor are common in all.

Body:
If I understand your question, you can use this query to obtain the ingredients for chapati and pizza bun type 2 (in common):

select ingredients.id
from ingredients master join product master join product ingredients (complete it)
where product.name in ('chapati', 'pizza bun type 2')
group by ingredients.id
having count(*)>1

and then you can find product with similar ingredients

select product.name
from ingredients master join product master join product ingredients (complete it)
where ingredients.id in (first query)


问:
Erasing a container element using iterators
My current homework assignment has me creating an iterator class for a list. I'm stuck at creating a good erase(iterator where) function.

Current code (reduced to fit question):

```<code>class List
{
    class _Iter
    {
        friend class List;
    public:
        _Iter(ListElem *pCurr, List *pList);

        /* *, ->, ++, --, == and != operators overloaded */

    private:
        ListElem *pCurr_; List *pList_;
    };

    typedef _Iter iterator;

    iterator erase(iterator where);
};
</code>```

with the erase being implemented like so:

```<code>// Precondition: List has been checked for size > 0.
List::iterator List::erase(List::iterator& where)
{
    // Erasing only element in list.
    if(where == end() && where == begin())
    {
        pop_back(); // or pop_front();
        return iterator(0, this);
    }

    // Elem at end
    if(where == end())
    {
        pop_back();
        return end();
    }
    else
    {
        // Elem at beginning
        if(where == begin())
        {
            pop_front();
            return ++begin();
        }
    }

    // Elem somewhere between beginning and end.
    iterator temp(where);
    // The node next to pCurr_ should point to the one before pCurr_
    where.pCurr_->next->prev = where.pCurr_->prev;
    // The node before pCurr_ should point to the one after pCurr_
    where.pCurr_->prev->next = where.pCurr_->next;
    // Return the node after pCurr_
    ++temp;
    delete where.pCurr_;
    --size_;
    return temp;
}
</code>```

The first three cases- only element, element at end and element at beginning- are all okay. Coded fine and need absolutely no knowledge and private access to _Iters members. However, if the element is not in those positions, then I have (seemingly) no choice but to violate the encapsulation and change pCurr_ (element of the list) directly.

Is there any way to avoid this? I looked inside the STL list, but they used some other functions _Next_Node_(/* stuff */) and _Prev_Node_(/* stuff */) that weren't very useful to me. Google searches give me helpful results on how to use the erase function, not how to write it myself.

Question:  Is there a way in which I can erase the element pointed to by my iterator without having to grab it's pCurr_ member?

答:
This is not really violating encapsulation. It is pretty much inevitable that a container and its iterators are tightly coupled. The two of them together hide the implementation details from the user. If they weren't friends to each other, more implementation details would have to be leaked to the user. The friend keyword can enhance encapsulation if the classes in question have valid reasons to know about each others internals.

Note that begin() == end() representing a list with one element is not the standard library convention where it means that the container is empty. end() should return an iterator to "one-past-the-end" of the container.

Body:
My current homework assignment has me creating an iterator class for a list. I'm stuck at creating a good erase(iterator where) function.

Current code (reduced to fit question):

class List
{
    class _Iter
    {
        friend class List;
    public:
        _Iter(ListElem *pCurr, List *pList);

        /* *, ->, ++, --, == and != operators overloaded */

    private:
        ListElem *pCurr_; List *pList_;
    };

    typedef _Iter iterator;

    iterator erase(iterator where);
};

with the erase being implemented like so:

// Precondition: List has been checked for size > 0.
List::iterator List::erase(List::iterator& where)
{
    // Erasing only element in list.
    if(where == end() && where == begin())
    {
        pop_back(); // or pop_front();
        return iterator(0, this);
    }

    // Elem at end
    if(where == end())
    {
        pop_back();
        return end();
    }
    else
    {
        // Elem at beginning
        if(where == begin())
        {
            pop_front();
            return ++begin();
        }
    }

    // Elem somewhere between beginning and end.
    iterator temp(where);
    // The node next to pCurr_ should point to the one before pCurr_
    where.pCurr_->next->prev = where.pCurr_->prev;
    // The node before pCurr_ should point to the one after pCurr_
    where.pCurr_->prev->next = where.pCurr_->next;
    // Return the node after pCurr_
    ++temp;
    delete where.pCurr_;
    --size_;
    return temp;
}

The first three cases- only element, element at end and element at beginning- are all okay. Coded fine and need absolutely no knowledge and private access to _Iters members. However, if the element is not in those positions, then I have (seemingly) no choice but to violate the encapsulation and change pCurr_ (element of the list) directly.

Is there any way to avoid this? I looked inside the STL list, but they used some other functions _Next_Node_(/* stuff */) and _Prev_Node_(/* stuff */) that weren't very useful to me. Google searches give me helpful results on how to use the erase function, not how to write it myself.

Question:  Is there a way in which I can erase the element pointed to by my iterator without having to grab it's pCurr_ member?


问:
get name from a button click React
Just some context with respect to the code. I currently have an array of objects which populates the label,icon, and id of a button accordingly in a loop. The trouble I am having is targeting the selected button upon click. Everytime I do click a button, i get the following the error:

TypeError: _this2.props.bind is not a function

My code is as follows:

```<code>import React, {Component} from 'react'
import propTypes from 'prop-types'
import Button from 'components/button'
import './segmentedButtons.scss'

class segmentedButtons extends Component {
  onChange = (displayLabels) => {
    console.log(displayLabels)
    //this.props.onChange({ label: displayLabels.label, icon: displayLabels.icon, id: displayLabels.id })
  }

  render() {
    const {displayLabels} = this.props.labels
    const classPrefix = this.props.view
    var renderLabels = [];
    for (var i = 0; i< this.props.labels.length; i++){
        renderLabels.push(<Button
        label={this.props.labels[i].title}
        icon={this.props.labels[i].icon}
        id={this.props.labels[i].id}
        onClick={() => this.onChange(this.props.bind(this,i))}
      />)
    }

    return (
      <div className={classPrefix+"-buttons "+ "segmentedButtons-buttons"}>
          {renderLabels}
      </div>
    )
  }
}

segmentedButtons.propTypes = {
  displayLabels: propTypes.arrayOf(propTypes.shape({
    label: propTypes.string,
    icon: propTypes.string,
    id: propTypes.number,
    onClick: propTypes.func
  })),
}

export default segmentedButtons
</code>```

答:
Like Andrew mentioned, the best way is probably us use an arrow function:
onClick={() => this.onChange(i)}.

If you want to use bind, this is the way to do it: onClick={this.onChange.bind(this, i)}.

Title: get name from a button click React

Body:
Just some context with respect to the code. I currently have an array of objects which populates the label,icon, and id of a button accordingly in a loop. The trouble I am having is targeting the selected button upon click. Everytime I do click a button, i get the following the error:

TypeError: _this2.props.bind is not a function

My code is as follows:

import React, {Component} from 'react'
import propTypes from 'prop-types'
import Button from 'components/button'
import './segmentedButtons.scss'

class segmentedButtons extends Component {
  onChange = (displayLabels) => {
    console.log(displayLabels)
    //this.props.onChange({ label: displayLabels.label, icon: displayLabels.icon, id: displayLabels.id })
  }

  render() {
    const {displayLabels} = this.props.labels
    const classPrefix = this.props.view
    var renderLabels = [];
    for (var i = 0; i< this.props.labels.length; i++){
        renderLabels.push(<Button
        label={this.props.labels[i].title}
        icon={this.props.labels[i].icon}
        id={this.props.labels[i].id}
        onClick={() => this.onChange(this.props.bind(this,i))}
      />)
    }

    return (

          {renderLabels}

    )
  }
}

segmentedButtons.propTypes = {
  displayLabels: propTypes.arrayOf(propTypes.shape({
    label: propTypes.string,
    icon: propTypes.string,
    id: propTypes.number,
    onClick: propTypes.func
  })),
}

export default segmentedButtons


问:
What is a state of an object after it was moved-from via a reference to its base class?
Assume, there is a hierarchy of two classes:

```<code>class Base {};
class Foo: public Base {};
</code>```

Which are used like this:

```<code>Foo foo;
Base &base = foo;
Base moved = std::move(base);
</code>```

In what state is foo after such move? Does the Standard impose any requirements on limitations on such code?

答:
In your particular case, nothing happens, since both Base and Foo are empty classes.

For the more interesting situation that both Base and Foo have some movable members (or bases), since Base has no user-defined move constructor, the default move constructor will be used. This will move the Base part of foo to moved, but leave the rest intact. For example, after

```<code>struct Base      { std::unique_ptr<int> X; };
struct Foo: Base { std::unique_ptr<int> Y; };

Foo foo;
foo.X.reset(new int);
foo.Y.reset(new int);
Base &base = foo;
Base moved = std::move(base);
</code>```

foo.X is empty (nullptr) with the original value moved to moved, but still foo.Y still holds the initial value.

This demonstrates that when moving from a reference you potentially change the state of the referred to object, which can create all sorts of unwanted effects and is best avoided.

Body:
Assume, there is a hierarchy of two classes:

class Base {};
class Foo: public Base {};

Which are used like this:

Foo foo;
Base &base = foo;
Base moved = std::move(base);

In what state is foo after such move? Does the Standard impose any requirements on limitations on such code?

Body:
In your particular case, nothing happens, since both Base and Foo are empty classes.

For the more interesting situation that both Base and Foo have some movable members (or bases), since Base has no user-defined move constructor, the default move constructor will be used. This will move the Base part of foo to moved, but leave the rest intact. For example, after

struct Base      { std::unique_ptr<int> X; };
struct Foo: Base { std::unique_ptr<int> Y; };

Foo foo;
foo.X.reset(new int);
foo.Y.reset(new int);
Base &base = foo;
Base moved = std::move(base);

foo.X is empty (nullptr) with the original value moved to moved, but still foo.Y still holds the initial value.

This demonstrates that when moving from a reference you potentially change the state of the referred to object, which can create all sorts of unwanted effects and is best avoided.


问:
How do I get a textarea to span two columns of a table
So I'm learning some php and found my html skills more then a little rusty. I'm trying to get my textarea to span two table columns. W3schools says I can do a colspan for a  tag but didn't see if it was supported for . I thought about splitting it between two tables same form. Seems like there would be an easier way to do this. I did try td colspan"2" but it didnt do anything

```<code>   echo '<form action="' . $_SERVER['PHP_SELF'] . '" method="post" id="crud_form">';
   echo '<table id="table_articles">';
   echo '<tr><td>Article Title:</td><td> <input type="text" name="art_title" /></td></tr>';
   echo '<tr><td>Author:</td><td> <input type="text" name="author" /></td></tr>';
   echo '<tr><td>Date Posted:</td><td> <input type="text" name="d_posted" /></td></tr>';
   echo '<tr><td>Article Text:</td></tr>';
   echo '<tr><td><textarea rows="10" columns="60" name="art_text" ></textarea></td></tr>';
   echo '<tr><td><input type="submit" name="submit_art" value="Submit" /></td></tr>';
   echo '</table>';
   echo '</form>';
</code>```

The CSS

```<code>   #crud_form
   {
   color:red;
   position:absolute;
   left:300px;
   top:200px;
   border-style:outset;
   border-width:5px;
   border-color:red;
   background-color:#cccccc;
   }

   #table_articles
   {
   color:red;
   width:450px;
   height:300px;
   }
</code>```

Thoughts? Thanks for the help.

答:
You need to use CSS to make the text area occupy all the width allotted to the td tag, for example:</p>

```<code><tr><td colspan="2"><textarea style="width: 100%;" /></td> </tr>
</code>```

Body:
So I'm learning some php and found my html skills more then a little rusty. I'm trying to get my textarea to span two table columns. W3schools says I can do a colspan for a  tag but didn't see if it was supported for . I thought about splitting it between two tables same form. Seems like there would be an easier way to do this. I did try td colspan"2" but it didnt do anything

   echo '<form action="' . $_SERVER['PHP_SELF'] . '" method="post" id="crud_form">';
   echo '
';
   echo '
Article Title:	 <input type="text" name="art_title" />
';
   echo '
Author:	 <input type="text" name="author" />
';
   echo '
Date Posted:	 <input type="text" name="d_posted" />
';
   echo '
Article Text:
';
   echo '
<textarea rows="10" columns="60" name="art_text" ></textarea>
';
   echo '
<input type="submit" name="submit_art" value="Submit" />
';
   echo '
';
   echo '</form>';

The CSS

   #crud_form
   {
   color:red;
   position:absolute;
   left:300px;
   top:200px;
   border-style:outset;
   border-width:5px;
   border-color:red;
   background-color:#cccccc;
   }

   #table_articles
   {
   color:red;
   width:450px;
   height:300px;
   }

Thoughts? Thanks for the help.

Body:
You need to use CSS to make the text area occupy all the width allotted to the td tag, for example:

<tr><td colspan="2"><textarea style="width: 100%;" /></td> </tr>


问:
Single Table Inheritance - discriminator map
I am needing to make a formula to DiscriminatorMap in my class, because I have a lot of class, and I can't discrimine each one.

The discr can be the name of the class.

it's possible? (with annotation, xml or other)

```<code>/**
* @ORM\Entity
* @ORM\InheritanceType("SINGLE_TABLE")
* @ORM\DiscriminatorColumn(name="discr", type="string")
* @ORM\DiscriminatorMap({"MidUpperArmCircumference" = MidUpperArmCircumference", "KneeHeight" = "KneeHeight"})
*/
</code>```

thanks.

答:
This is an old question. Doctrine supports single table inheritance pretty well.
The below example is from official docs

```<code><?php
namespace MyProject\Model;

/**
 * @Entity
 * @InheritanceType("SINGLE_TABLE")
 * @DiscriminatorColumn(name="discr", type="string")
 * @DiscriminatorMap({"person" = "Person", "employee" = "Employee"})
 */
class Person
{
    // ...
}

/**
 * @Entity
 */
class Employee extends Person
{
    // ...
}
</code>```

Read more about it here

Body:
I am needing to make a formula to DiscriminatorMap in my class, because I have a lot of class, and I can't discrimine each one.

The discr can be the name of the class.

it's possible? (with annotation, xml or other)

/**
* @ORM\Entity
* @ORM\InheritanceType("SINGLE_TABLE")
* @ORM\DiscriminatorColumn(name="discr", type="string")
* @ORM\DiscriminatorMap({"MidUpperArmCircumference" = MidUpperArmCircumference", "KneeHeight" = "KneeHeight"})
*/

thanks.

Body:
This is an old question. Doctrine supports single table inheritance pretty well.
The below example is from official docs

<?php
namespace MyProject\Model;

/**
 * @Entity
 * @InheritanceType("SINGLE_TABLE")
 * @DiscriminatorColumn(name="discr", type="string")
 * @DiscriminatorMap({"person" = "Person", "employee" = "Employee"})
 */
class Person
{
    // ...
}

/**
 * @Entity
 */
class Employee extends Person
{
    // ...
}

Read more about it here


问:
How to get an HTML file using Python?
I am not very familiar with Python. I am trying to extract the artist names (for a start :)) from the following page: http://www.infolanka.com/miyuru_gee/art/art.html.

How do I retrieve the page? My two main concerns are; what functions to use and how to filter out useless links from the page?

答:
Or go straight forward:</p>

```<code>import urllib

import re
pat = re.compile('<DT><a href="[^"]+">(.+?)</a>')

url = 'http://www.infolanka.com/miyuru_gee/art/art.html'
sock = urllib.urlopen(url)
li = pat.findall(sock.read())
sock.close()

print li
</code>```

Title: How to get an HTML file using Python?

Body:
Or go straight forward:

import urllib

import re
pat = re.compile('<DT><a href="[^"]+">(.+?)</a>')

url = 'http://www.infolanka.com/miyuru_gee/art/art.html'
sock = urllib.urlopen(url)
li = pat.findall(sock.read())
sock.close()

print li


问:
R Markdown - changing font size and font type in html output
I am using R Markdown in RStudio and the knit HTML option to create HTML output. However, the font used in the ouput for plain text blocks is rather small and I would like to change it to a differnt font and increase the font size. Can someone show an example how to set the output font - workable without a lot of knowledge in html?

So far I tried at the top of my markdown document, but this doesn't work.

```<code>---
fontsize: 24pt
---
</code>```

答:
You can change the font size in R Markdown with HTML code tags  your text   . This code is added to the R Markdown document and will alter the output of the HTML output.

For example:

  This is my text number1

  This is my text number 2

  This is my text number 3

  This is my text number 4

  This is my text number 5

  This is my text number 6```

Body:
I am using R Markdown in RStudio and the knit HTML option to create HTML output. However, the font used in the ouput for plain text blocks is rather small and I would like to change it to a differnt font and increase the font size. Can someone show an example how to set the output font - workable without a lot of knowledge in html?

So far I tried at the top of my markdown document, but this doesn't work.

---
fontsize: 24pt
---

Body:
You can change the font size in R Markdown with HTML code tags <font size="1"> your text </font>  . This code is added to the R Markdown document and will alter the output of the HTML output.

For example:

 <font size="1"> This is my text number1</font>

 <font size="2"> This is my text number 2 </font>

 <font size="3"> This is my text number 3</font>

 <font size="4"> This is my text number 4</font>

 <font size="5"> This is my text number 5</font>

 <font size="6"> This is my text number 6</font>


问:
Href how to pass dynamic data
[![enter image description here][1]][1]In href how to pass path with dynamic data, below I'm giving my code:

```<code>var abc = response[i].DocumentName;
var photoName = "<a href='@Url.Content("~/UploadImage/")" + abc +'" target="_blank" >'+response[i].DocumentName+'</a>';
</code>```

in debugger mode i am getting like this:-

```<code>photoName = "<a href='/UploadImage/jpeg2_10514.jpg target="_blank" id="servicedocu">jpeg2_10514.jpg</a>"
</code>```

which is not working for me

答:
Try this:

```<code>var photoName = "<a href=\"@Url.Content('~/UploadImage/')" + abc + "\" target=\"_blank\">" + response[i].DocumentName + "</a>";
</code>```

In Javascript you have to escape doublequotes " with a backslash \ if you want them to appear in the string.

The backslash in + abc + "\" is there to escape the second " to enclose the href in doublequotes.

EDIT

I added the missing doublequote befor the anchor tag according to the tip of karan.

Title: Href how to pass dynamic data

Body:
[![enter image description here][1]][1]In href how to pass path with dynamic data, below I'm giving my code:

var abc = response[i].DocumentName;
var photoName = "'+response[i].DocumentName+'';

in debugger mode i am getting like this:-

photoName = "jpeg2_10514.jpg"

which is not working for me

Body:
Try this:

var photoName = "<a href=\"@Url.Content('~/UploadImage/')" + abc + "\" target=\"_blank\">" + response[i].DocumentName + "</a>";

In Javascript you have to escape doublequotes " with a backslash \ if you want them to appear in the string.

The backslash in + abc + "\" is there to escape the second " to enclose the href in doublequotes.

EDIT

I added the missing doublequote befor the anchor tag according to the tip of karan.


问:
Sorting an Excel Pivot Table by a calculated field
I have the following Excel spreadsheet:

```<code>     A              B              C              D
1   Product        Category         Sale        Margin
2   Product A       Apparel          500          45%
3   Product A       Apparel          400          30%
4   Product A       Shoes            600          55%
5   Product B       Apparel          300          20%
6   Product C       Beauty           100          40%
7   Product C       Shoes            200          65%
8   Product D       Apparel          450          25%
9   Product D       Beauty           700          50%
10  Product D       Beauty           250          35%
</code>```

Based on this data I create a Pivot Table.
In this Pivot table I added the following Calculated Field to get the profit:

```<code>   Profit = Sale * Margin
</code>```

which leads to the following Pivot Table:

```<code>            Sum of Profit
Product A     1.950
Product B        60
Product C       315
Product D     1.540
</code>```

Now, I want to sort this Pivot Table descending so it looks like the following:

```<code>              Sum of Profit
Product A        1.950
Product D        1.540
Product C          315
Product B           60
</code>```

It seems that for a Calculated Field the sorting options in the PivotTable-Tools is not available.

Do you have any other idea how I can achieve this sorting?

NOTE: I know that I could add the calculation of the profit in Column E in the source data. However, my original file is a bit more complex compared to the simplified example above so a Calculated Field is unavoidable.

答:
Right click on a cell in the Calculated Field --> Sort --> Sort largest to smallest.

Or you can try the following code to sort the calculated field.

```<code>Sub SortCalculatedField()
Dim ws As Worksheet
Dim pt As PivotTable

Set ws = Sheets("Sheet1")   'This is the sheet which contains Pivot Table
Set pt = ws.PivotTables(1)
pt.PivotFields("Product").AutoSort xlDescending, "Sum of Profit", pt.PivotColumnAxis.PivotLines(1), 1
End Sub
</code>```

Body:
I have the following Excel spreadsheet:

     A              B              C              D
1   Product        Category         Sale        Margin
2   Product A       Apparel          500          45%
3   Product A       Apparel          400          30%
4   Product A       Shoes            600          55%
5   Product B       Apparel          300          20%
6   Product C       Beauty           100          40%
7   Product C       Shoes            200          65%
8   Product D       Apparel          450          25%
9   Product D       Beauty           700          50%
10  Product D       Beauty           250          35%

Based on this data I create a Pivot Table.
In this Pivot table I added the following Calculated Field to get the profit:

   Profit = Sale * Margin

which leads to the following Pivot Table:

            Sum of Profit
Product A     1.950
Product B        60
Product C       315
Product D     1.540

Now, I want to sort this Pivot Table descending so it looks like the following:

              Sum of Profit
Product A        1.950
Product D        1.540
Product C          315
Product B           60

It seems that for a Calculated Field the sorting options in the PivotTable-Tools is not available.

Do you have any other idea how I can achieve this sorting?

NOTE: I know that I could add the calculation of the profit in Column E in the source data. However, my original file is a bit more complex compared to the simplified example above so a Calculated Field is unavoidable.

Body:
Right click on a cell in the Calculated Field --> Sort --> Sort largest to smallest.

Or you can try the following code to sort the calculated field.

Sub SortCalculatedField()
Dim ws As Worksheet
Dim pt As PivotTable

Set ws = Sheets("Sheet1")   'This is the sheet which contains Pivot Table
Set pt = ws.PivotTables(1)
pt.PivotFields("Product").AutoSort xlDescending, "Sum of Profit", pt.PivotColumnAxis.PivotLines(1), 1
End Sub


问:
Is there a way to test web application using Selenium and either Driver Firefox or Chrome on a server Centos7 without graphical interface?
On my local machine, I arrived to test my applications with Selenium with any problems.

But, when I'm doing the same operations on a server Centos7 (I have no graphical interface), I've many errors such as web element not found.

I'm using Docker containers for selenium (hub and nodes). The installation is OK and I can see my drivers on Http://:4444/grid/console.

Does Selenium require a graphical interface for its work?

答:
Yes. Selenium requires the browser GUI to be present - which is also called viewport.

If you want that Selenium execution happen, without the browser GUI to be present, then you need to use a headless browser, which , as the name suggests is headless, which means there would be no GUI for them.

Examples of these headless browser include PhantomJS- link. Now Chrome also has a headless mode - link, which you can specify using ChromeOptions. Cheers!


问:
QR Codes encoded by DelphiZXingQRCode not decodable with ErrorCorrectionLevel > Low
I am using this Delphi-Unit. I am forced to use this old Delphi implementation, so don't ask about that:
https://github.com/foxitsoftware/DelphiZXingQRCode

The QRcodes it produces are decoded by any decoders just fine, as long as I keep the error correction level at "Low". If I increase the error correction level, the generated codes can not be decoded by any decoder I tried so far. But I am forced (by a standard) to use an error correction level of Medium, no more no less.

However it is not clear how to increase the error correction level (ecl from now on). I assume it to be hardcoded in the file DelphiZXingQRCode on line 3491: Level.FBits := 1. I found some information on hexnumbers representing ecls, but I can't find it now. But I tried those hexnumbers as bits and the ecl-bits on the QRcode changed accordingly. So I assumed the hexnumbers to be correct (1=Low, 0=Medium, 2=High, 3=Quartile).

Here is an example of a QRcode with Level.FBits := 2, meaning I wanted the ecl to be "High". The content ist "Hello world". The cross image in the middle is part of a standard [sic] I have to implement, so don't ask about that.

Has anyone any idea how to fix this? I tried...well...I tried to understand the code but it's too much. I just can't fix it. If I can't get it fixed by someone else, I will have to...find another solution. Which will be a problem.

答:
Solved. See code below. Method GenerateQRCode() now requires a parameter for the ErrorCorrectionLevel: Integers 0-3. Seems to work. I had to remove some unchanged lines, because the file is too large for StackOverflow. Merge yourself.</p>

```<code>    unit DelphiZXingQRCode;

    // ZXing QRCode port to Delphi, by Debenu Pty Ltd
    // www.debenu.com

    // Original copyright notice
    (*
     * Copyright 2008 ZXing authors
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *      http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     *)

    interface

    type
      TQRCodeEncoding = (qrAuto, qrNumeric, qrAlphanumeric, qrISO88591, qrUTF8NoBOM, qrUTF8BOM);
      T2DBooleanArray = array of array of Boolean;

      TDelphiZXingQRCode = class
      protected
        FData: WideString;
        FRows: Integer;
        FColumns: Integer;
        FEncoding: TQRCodeEncoding;
        FQuietZone: Integer;
        FElements: T2DBooleanArray;
        FErrorCorrectionLevel: integer;
        procedure SetEncoding(NewEncoding: TQRCodeEncoding);
        procedure SetData(const NewData: WideString);
        procedure SetQuietZone(NewQuietZone: Integer);
        procedure SetErrorCorrectionLevel(value: integer);
        function GetIsBlack(Row, Column: Integer): Boolean;
        procedure Update;
      public
        constructor Create;
        property Data: WideString read FData write SetData;
        property Encoding: TQRCodeEncoding read FEncoding write SetEncoding;
        property ErrorCorrectionLevel: integer read fErrorCorrectionLevel write SetErrorCorrectionLevel;
        property QuietZone: Integer read FQuietZone write SetQuietZone;
        property Rows: Integer read FRows;
        property Columns: Integer read FColumns;
        property IsBlack[Row, Column: Integer]: Boolean read GetIsBlack;
      end;

    implementation

    uses
      SysUtils,
      contnrs, Math, Classes;

    type
      TByteArray = array of Byte;
      T2DByteArray = array of array of Byte;
      TIntegerArray = array of Integer;

    // File too large for Stackoverflow: Deleted unchanged lines.

    { TErrorCorrectionLevel }

    procedure TErrorCorrectionLevel.Assign(Source: TErrorCorrectionLevel);
    begin
      Self.fOrdinal := Source.FOrdinal;
    end;

    constructor TErrorCorrectionLevel.Create(ordinalValue: integer);
    begin

      fOrdinal:=0;
      if (ordinalValue >= 0) and (ordinalValue <=3) then
        fOrdinal:=ordinalValue;
    end;

    function TErrorCorrectionLevel.GetBits: integer;
    begin
      if fOrdinal = 0 then  // level L
        result:=1
      else
      if fOrdinal = 1 then  // level M
        result:=0
      else
      if fOrdinal = 2 then  // level Q
        result:=3
      else
      if fOrdinal = 3 then  // level H
        result:=2
      else
        result:=1;
    end;

    // File too large for Stackoverflow: Deleted unchanged lines.

    procedure TDelphiZXingQRCode.SetErrorCorrectionLevel(value: integer);
    begin
      if (value < 0) or (value > 3) then
        raise Exception.Create('invalid error correction value. must be in range 0..3.');

      if value <> fErrorCorrectionLevel then
      begin
        FErrorCorrectionLevel:=value;
        Update;
      end;
    end;

    procedure TDelphiZXingQRCode.SetQuietZone(NewQuietZone: Integer);
    begin
      if ((FQuietZone <> NewQuietZone) and (NewQuietZone >= 0) and (NewQuietZone <= 100)) then
      begin
        FQuietZone := NewQuietZone;
        Update;
      end;
    end;

    procedure TDelphiZXingQRCode.Update;
    begin
      FElements := GenerateQRCode(FData, Ord(FEncoding), FErrorCorrectionLevel);
      FRows := Length(FElements) + FQuietZone * 2;
      FColumns := FRows;
    end;
    end.
</code>```

Body:
Solved. See code below. Method GenerateQRCode() now requires a parameter for the ErrorCorrectionLevel: Integers 0-3. Seems to work. I had to remove some unchanged lines, because the file is too large for StackOverflow. Merge yourself.

    unit DelphiZXingQRCode;

    // ZXing QRCode port to Delphi, by Debenu Pty Ltd
    // www.debenu.com

    // Original copyright notice
    (*
     * Copyright 2008 ZXing authors
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *      http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     *)

    interface

    type
      TQRCodeEncoding = (qrAuto, qrNumeric, qrAlphanumeric, qrISO88591, qrUTF8NoBOM, qrUTF8BOM);
      T2DBooleanArray = array of array of Boolean;

      TDelphiZXingQRCode = class
      protected
        FData: WideString;
        FRows: Integer;
        FColumns: Integer;
        FEncoding: TQRCodeEncoding;
        FQuietZone: Integer;
        FElements: T2DBooleanArray;
        FErrorCorrectionLevel: integer;
        procedure SetEncoding(NewEncoding: TQRCodeEncoding);
        procedure SetData(const NewData: WideString);
        procedure SetQuietZone(NewQuietZone: Integer);
        procedure SetErrorCorrectionLevel(value: integer);
        function GetIsBlack(Row, Column: Integer): Boolean;
        procedure Update;
      public
        constructor Create;
        property Data: WideString read FData write SetData;
        property Encoding: TQRCodeEncoding read FEncoding write SetEncoding;
        property ErrorCorrectionLevel: integer read fErrorCorrectionLevel write SetErrorCorrectionLevel;
        property QuietZone: Integer read FQuietZone write SetQuietZone;
        property Rows: Integer read FRows;
        property Columns: Integer read FColumns;
        property IsBlack[Row, Column: Integer]: Boolean read GetIsBlack;
      end;

    implementation

    uses
      SysUtils,
      contnrs, Math, Classes;

    type
      TByteArray = array of Byte;
      T2DByteArray = array of array of Byte;
      TIntegerArray = array of Integer;

    // File too large for Stackoverflow: Deleted unchanged lines.

    { TErrorCorrectionLevel }

    procedure TErrorCorrectionLevel.Assign(Source: TErrorCorrectionLevel);
    begin
      Self.fOrdinal := Source.FOrdinal;
    end;

    constructor TErrorCorrectionLevel.Create(ordinalValue: integer);
    begin

      fOrdinal:=0;
      if (ordinalValue >= 0) and (ordinalValue <=3) then
        fOrdinal:=ordinalValue;
    end;

    function TErrorCorrectionLevel.GetBits: integer;
    begin
      if fOrdinal = 0 then  // level L
        result:=1
      else
      if fOrdinal = 1 then  // level M
        result:=0
      else
      if fOrdinal = 2 then  // level Q
        result:=3
      else
      if fOrdinal = 3 then  // level H
        result:=2
      else
        result:=1;
    end;

    // File too large for Stackoverflow: Deleted unchanged lines.

    procedure TDelphiZXingQRCode.SetErrorCorrectionLevel(value: integer);
    begin
      if (value < 0) or (value > 3) then
        raise Exception.Create('invalid error correction value. must be in range 0..3.');

      if value <> fErrorCorrectionLevel then
      begin
        FErrorCorrectionLevel:=value;
        Update;
      end;
    end;

    procedure TDelphiZXingQRCode.SetQuietZone(NewQuietZone: Integer);
    begin
      if ((FQuietZone <> NewQuietZone) and (NewQuietZone >= 0) and (NewQuietZone <= 100)) then
      begin
        FQuietZone := NewQuietZone;
        Update;
      end;
    end;

    procedure TDelphiZXingQRCode.Update;
    begin
      FElements := GenerateQRCode(FData, Ord(FEncoding), FErrorCorrectionLevel);
      FRows := Length(FElements) + FQuietZone * 2;
      FColumns := FRows;
    end;
    end.


问:
Real world experiences with the ADO.NET Entity Framework and unit testing
I am investigating the ADO.NET Entity Framework in combination with unit testing. A recommended way is described by Scott Allan:

Testability and Entity Framework 4.0

The article involves the code generation with POCOS.

My first impression: The manual effort to introduce and maintain this architecture is high. Before a deep dive I am interested in any real world experience.

答: Using POCO objects makes unit testing easier, but doesn't help you in making the code that uses LINQ queries over those POCO objects testable. Take a look at this article. It describes how to hide EF behind an abstraction, while still allowing to use LINQ queries over it.</p>


问:
How to scroll to bottom of div element Selenium Webdriver
I have a use case wherein there's a div element on the webpage, it appears like a popup dialog as soon as you click a link (its not an actual popup, its something like dialog boxes which opens in Facebook when you click a link to check reactions on your posts etc.)

I'm using Selenium WebDriver with Java to automate tests for this application, my use case involves me to scroll to the bottom of the dialog box where there is a link to show more items, when user clicks show more, it populates another 10 items in the list and so on until there are no other items left for the user to visit.

So basically I have to scroll down on that particular div element till I keep seeing Show More link and when driver is not able to find show more link it should stop.

Note - I can't just scroll to bottom of the page using javascript window.scrollTo() as it will scroll down through whole webpage, however I just want to scroll to bottom of that division element only.

If anybody have any idea on how to achieve this please let me know.

Thanks for the help in advance !

答:
you can use scrollIntoView

scrollIntoView vs moveToElement
scrollIntoView vs moveToElement

Pass  the more items link element as an argument.

```<code>((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
</code>```

You can also use moveToElement

```<code>Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.perform();
</code>```

Body:
you can use scrollIntoView

scrollIntoView vs moveToElement
scrollIntoView vs moveToElement

Pass  the more items link element as an argument.

((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);

You can also use moveToElement

Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.perform();