问:
Call a Form and correct way to release? memory usage
I'm using Delphi 7.

I have two units containing Form1 and Form2. The secondary form will be called many times during some process, and I am very worried about memory usage.

When I start the program, memory usage is around 2.1 MB. When Form2 is called, memory grows to 2.9 MB.  After this process, I close Form2 and call it again to simulate regular usage, and memory grows to 3.1 MB, call again and memory grows to 3.4 MB, 3.6 MB, 3.8 MB, etc.

Memory usage is the main issue.

Form1 is calling Form2 like this:

```<code>uses
  Unit2;

...

private
  { Private declarations }
  FChild : TForm2;
...

FChild := TForm2.Create(nil);
try
  FChild.ShowModal;
finally
  FChild.Free;
end;
</code>```

Inside Unit2:

```<code>procedure TForm2.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  Action := caFree;
end;
</code>```

Am I doing something wrong? Is there a better solution?

Please, this not a simple question, because this program will be running 24 hours, and the second form will be called many times.  This means that sometimes this program will freeze the computer.

I included FASTMM4 inside project:

```<code>program Project1;

uses
  FastMM4,
  Forms,
  Unit1 in 'Unit1.pas' {Form1},
  Unit2 in 'Unit2.pas' {Form2};

{$R *.res}

begin
  FullDebugModeScanMemoryPoolBeforeEveryOperation := True;
  SuppressMessageBoxes:=False;
  Application.Initialize;
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.
</code>```

This program is reading a fingerprint.

Unit1:

```<code>unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls, Unit2;

type
  TForm1 = class(TForm)
    btnForm2: TButton;
    btnReselease: TButton;
    procedure btnForm2Click(Sender: TObject);
    procedure btnReseleaseClick(Sender: TObject);
  private
    { Private declarations }
    FChild : TForm2;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.btnForm2Click(Sender: TObject);

begin
  FChild := TForm2.Create(nil);
  try
    FChild.ShowModal;
  finally
    FChild.Free;
  end;
end;

procedure TForm1.btnReseleaseClick(Sender: TObject);
begin
  if FChild <> nil then
  begin
    FreeAndNil(FChild);
  end;
end;

end.
</code>```

Unit2:

```<code>unit Unit2;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Buttons, pngimage, ExtCtrls, Grids,  XMLIntf, XMLDoc,
  ComCtrls, CPort;

type
  TForm2 = class(TForm)
    btnSyncFP: TBitBtn;
    btnExitFP: TBitBtn;
    btnDeleteFP: TBitBtn;
    btnCaptureFP: TBitBtn;
    ComImage: TImage;
    FPGrid: TStringGrid;
    prgBar: TProgressBar;
    lblbar: TLabel;
    ComPortA: TComPort;
    ComDataPacket1: TComDataPacket;
    procedure LoadUsers2;
    procedure FormCreate(Sender: TObject);
    procedure ComPortAAfterOpen(Sender: TObject);
    procedure ComPortAAfterClose(Sender: TObject);
    procedure btnExitFPClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
//  Form2: TForm2;
  L1, L2: TStringList;

implementation
{$R *.dfm}

procedure TForm2.LoadUsers2;
var
  XML : IXMLDOCUMENT;
  CurNode, CNode : IXMLNODE;
  i : Integer;
begin
  XML := NewXMLDocument;
  XML.LoadFromFile('usuario.xml');
  XML.Active := True;
  CurNode := XML.DocumentElement.ChildNodes[0]; // users
  FPGrid.RowCount := CurNode.ChildNodes.Count+1;
  prgBar.Min := 0;
  prgBar.Max := CurNode.ChildNodes.Count-1;
  lblBar.Caption := 'Carregando usuários...';
  for i := 0 to CurNode.ChildNodes.Count-1 do
  begin
    CNode := CurNode.ChildNodes[i]; // groups
    with CNode do
    begin
      FPGrid.Cells[2,i+1] := Attributes['group'];
      FPGrid.Cells[1,i+1] := Attributes['id'];
      FPGrid.Cells[0,i+1] := Attributes['name'];
      FPGrid.Cells[3,i+1] := Attributes['fingerID'];
      FPGrid.Cells[4,i+1] := Attributes['level'];
      FPGrid.Cells[5,i+1] := Attributes['status'];
    end;
    if FPGrid.Cells[3,i+1]<>'' then L1.Add(FPGrid.Cells[3,i+1]);
    prgBar.Position := i;
  end;
  XML := nil;
end;

procedure TForm2.FormCreate(Sender: TObject);
begin
  LoadUsers2;
  with FPGrid do
  begin
    Font.Name := 'Tahoma';
    Font.Size := 12;
    ColCount := 4;
    Cells[0,0] := 'Name';  Cells[1,0] := 'ID';
    Cells[2,0] := 'Group'; Cells[3,0] := 'Read ID';
    Cells[4,0] := 'Level'; Cells[5,0] := 'Status';
    ScrollBars := ssVertical;
    Options := Options + [goRowSelect];
  end;
  ComPortA.Open;
end;

procedure TForm2.ComPortAAfterOpen(Sender: TObject);
begin
  ComImage.Picture.LoadFromFile('conn_on.png');
end;

procedure TForm2.ComPortAAfterClose(Sender: TObject);
begin
  ComImage.Picture.LoadFromFile('conn_off.png');
end;

procedure TForm2.btnExitFPClick(Sender: TObject);
begin
  ComPortA.Close;
  Close;
end;

procedure TForm2.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  Action := caFree;
end;

end.
</code>```

I know that Task Manager is the best to verify leak memory, but after few hours, the program is growing faster and not realeasing memory.

I let the program running all night and memory is backing, but there is a long time not enough as user usage.

答:
No, apart from a potential error where the form may be "Freed" twice, you appear to be doing everything correctly, assuming that your Form2 implementation does not itself introduce memory leaks.

I am assuming that you are monitoring "memory use" by using Task Manager.  If so, this is highly misleading.

Your application is managing its memory using the Delphi heap manager.  This heap manager will allocate memory (requesting it from the OS) as required but when it is freed it is not immediately returned to the system (OS), but simply marked as no longer in use.  Then, when memory is required by the application in the future, the heap manager can "recycle" this unused memory instead of having to go back to the OS to ask for more memory (which is a relatively "expensive" operation).

However, the way that the heap manager determines whether unused memory can be recycled to satisfy a new request can mean that memory that could potentially be recycled may not be, for example as the result of fragmentation.

Imagine your application allocated 500 bytes of memory then a further 100 bytes and then another 500 bytes:

```<code>[1] [used] 500 bytes
[2] [used] 100 bytes
[3] [used] 500 bytes
</code>```

Imagine then that the two 500 bytes blocks are freed, making them available for re-use.

```<code>[1] [free] 500 bytes
[2] [used] 100 bytes
[3] [free] 500 bytes
</code>```

You might think that a request for 1000 bytes (or even 600, 700, 800 bytes etc) would be able to use this "recyclable" memory.

But that request for 1000 bytes requires a single, contiguous block, and with that 100 byte block still in use, those two 500 byte blocks can only be used for requests for (a maximum of) 500 bytes each.  So, a request for 1000 bytes has to be satisfied by allocating a new 1000 byte block:

```<code>[1] [free] 500 bytes
[2] [used] 100 bytes
[3] [free] 500 bytes
[4] [used] 1000 bytes
</code>```

Your application is still only "using" 1100 bytes, but to do so, 2100 bytes have been allocated from the OS.

The net result of all this is that memory "use" can appear to grow in Task Manager when in fact what is really happening is that your application is simply "holding on" to allocated memory it is no longer actually using, just in case it might need it in the future.

If the OS reached a point where it needed memory back, then all processes would be asked to relinquish such memory, and your application would be no different.

You can simulate this by minimising and restoring your application.  Unless your application is genuinely using all of the memory currently allocated, you should see a drop in memory use.  This drop might be slight or it could be significant, depending on the memory usage profile of your application.

When a (Delphi) application is minimized it will return some/as much memory to the system, on the basis that if the user has minimized it then it is now a "backgrond" process which is not likely to need to have any demands for memoy in the near future.

You can trigger this behaviour with some code in your application OnIdle event, but doing so is mostly pointless.  It may give the impression of reduced memory use in Task Manager, but will potentially reduce performance of your application and doesn't actually reduce your memory usage.

What Can I Do About It ?

The Delphi runtime has always supported the ability to replace the application heap manager with alternative implementations.

A popular one (which has been adopted as the new standard since Delphi 2006) is FastMM.  This implements strategies that avoid or reduce memory fragmentation and provides other performance and debugging improvements (it can be configured to report memory leaks and incorrectly used references to destroyed objects, for example).

FastMM  is open source and can be used even in a Delphi 7 application.  All you need to do is download the source and add FastMM as the first unit used in your project dpr file.

Body:
I'm using Delphi 7.

I have two units containing Form1 and Form2. The secondary form will be called many times during some process, and I am very worried about memory usage.

When I start the program, memory usage is around 2.1 MB. When Form2 is called, memory grows to 2.9 MB.  After this process, I close Form2 and call it again to simulate regular usage, and memory grows to 3.1 MB, call again and memory grows to 3.4 MB, 3.6 MB, 3.8 MB, etc.

Memory usage is the main issue.

Form1 is calling Form2 like this:

uses
  Unit2;

...

private
  { Private declarations }
  FChild : TForm2;
...

FChild := TForm2.Create(nil);
try
  FChild.ShowModal;
finally
  FChild.Free;
end;

Inside Unit2:

procedure TForm2.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  Action := caFree;
end;

Am I doing something wrong? Is there a better solution?

Please, this not a simple question, because this program will be running 24 hours, and the second form will be called many times.  This means that sometimes this program will freeze the computer.

I included FASTMM4 inside project:

program Project1;

uses
  FastMM4,
  Forms,
  Unit1 in 'Unit1.pas' {Form1},
  Unit2 in 'Unit2.pas' {Form2};

{$R *.res}

begin
  FullDebugModeScanMemoryPoolBeforeEveryOperation := True;
  SuppressMessageBoxes:=False;
  Application.Initialize;
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.

This program is reading a fingerprint.

Unit1:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls, Unit2;

type
  TForm1 = class(TForm)
    btnForm2: TButton;
    btnReselease: TButton;
    procedure btnForm2Click(Sender: TObject);
    procedure btnReseleaseClick(Sender: TObject);
  private
    { Private declarations }
    FChild : TForm2;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.btnForm2Click(Sender: TObject);

begin
  FChild := TForm2.Create(nil);
  try
    FChild.ShowModal;
  finally
    FChild.Free;
  end;
end;

procedure TForm1.btnReseleaseClick(Sender: TObject);
begin
  if FChild <> nil then
  begin
    FreeAndNil(FChild);
  end;
end;

end.

Unit2:

unit Unit2;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Buttons, pngimage, ExtCtrls, Grids,  XMLIntf, XMLDoc,
  ComCtrls, CPort;

type
  TForm2 = class(TForm)
    btnSyncFP: TBitBtn;
    btnExitFP: TBitBtn;
    btnDeleteFP: TBitBtn;
    btnCaptureFP: TBitBtn;
    ComImage: TImage;
    FPGrid: TStringGrid;
    prgBar: TProgressBar;
    lblbar: TLabel;
    ComPortA: TComPort;
    ComDataPacket1: TComDataPacket;
    procedure LoadUsers2;
    procedure FormCreate(Sender: TObject);
    procedure ComPortAAfterOpen(Sender: TObject);
    procedure ComPortAAfterClose(Sender: TObject);
    procedure btnExitFPClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
//  Form2: TForm2;
  L1, L2: TStringList;

implementation
{$R *.dfm}

procedure TForm2.LoadUsers2;
var
  XML : IXMLDOCUMENT;
  CurNode, CNode : IXMLNODE;
  i : Integer;
begin
  XML := NewXMLDocument;
  XML.LoadFromFile('usuario.xml');
  XML.Active := True;
  CurNode := XML.DocumentElement.ChildNodes[0]; // users
  FPGrid.RowCount := CurNode.ChildNodes.Count+1;
  prgBar.Min := 0;
  prgBar.Max := CurNode.ChildNodes.Count-1;
  lblBar.Caption := 'Carregando usuários...';
  for i := 0 to CurNode.ChildNodes.Count-1 do
  begin
    CNode := CurNode.ChildNodes[i]; // groups
    with CNode do
    begin
      FPGrid.Cells[2,i+1] := Attributes['group'];
      FPGrid.Cells[1,i+1] := Attributes['id'];
      FPGrid.Cells[0,i+1] := Attributes['name'];
      FPGrid.Cells[3,i+1] := Attributes['fingerID'];
      FPGrid.Cells[4,i+1] := Attributes['level'];
      FPGrid.Cells[5,i+1] := Attributes['status'];
    end;
    if FPGrid.Cells[3,i+1]<>'' then L1.Add(FPGrid.Cells[3,i+1]);
    prgBar.Position := i;
  end;
  XML := nil;
end;

procedure TForm2.FormCreate(Sender: TObject);
begin
  LoadUsers2;
  with FPGrid do
  begin
    Font.Name := 'Tahoma';
    Font.Size := 12;
    ColCount := 4;
    Cells[0,0] := 'Name';  Cells[1,0] := 'ID';
    Cells[2,0] := 'Group'; Cells[3,0] := 'Read ID';
    Cells[4,0] := 'Level'; Cells[5,0] := 'Status';
    ScrollBars := ssVertical;
    Options := Options + [goRowSelect];
  end;
  ComPortA.Open;
end;

procedure TForm2.ComPortAAfterOpen(Sender: TObject);
begin
  ComImage.Picture.LoadFromFile('conn_on.png');
end;

procedure TForm2.ComPortAAfterClose(Sender: TObject);
begin
  ComImage.Picture.LoadFromFile('conn_off.png');
end;

procedure TForm2.btnExitFPClick(Sender: TObject);
begin
  ComPortA.Close;
  Close;
end;

procedure TForm2.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  Action := caFree;
end;

end.

I know that Task Manager is the best to verify leak memory, but after few hours, the program is growing faster and not realeasing memory.

I let the program running all night and memory is backing, but there is a long time not enough as user usage.

Body:
No, apart from a potential error where the form may be "Freed" twice, you appear to be doing everything correctly, assuming that your Form2 implementation does not itself introduce memory leaks.

I am assuming that you are monitoring "memory use" by using Task Manager.  If so, this is highly misleading.

Your application is managing its memory using the Delphi heap manager.  This heap manager will allocate memory (requesting it from the OS) as required but when it is freed it is not immediately returned to the system (OS), but simply marked as no longer in use.  Then, when memory is required by the application in the future, the heap manager can "recycle" this unused memory instead of having to go back to the OS to ask for more memory (which is a relatively "expensive" operation).

However, the way that the heap manager determines whether unused memory can be recycled to satisfy a new request can mean that memory that could potentially be recycled may not be, for example as the result of fragmentation.

Imagine your application allocated 500 bytes of memory then a further 100 bytes and then another 500 bytes:

[1] [used] 500 bytes
[2] [used] 100 bytes
[3] [used] 500 bytes

Imagine then that the two 500 bytes blocks are freed, making them available for re-use.

[1] [free] 500 bytes
[2] [used] 100 bytes
[3] [free] 500 bytes

You might think that a request for 1000 bytes (or even 600, 700, 800 bytes etc) would be able to use this "recyclable" memory.

But that request for 1000 bytes requires a single, contiguous block, and with that 100 byte block still in use, those two 500 byte blocks can only be used for requests for (a maximum of) 500 bytes each.  So, a request for 1000 bytes has to be satisfied by allocating a new 1000 byte block:

[1] [free] 500 bytes
[2] [used] 100 bytes
[3] [free] 500 bytes
[4] [used] 1000 bytes

Your application is still only "using" 1100 bytes, but to do so, 2100 bytes have been allocated from the OS.

The net result of all this is that memory "use" can appear to grow in Task Manager when in fact what is really happening is that your application is simply "holding on" to allocated memory it is no longer actually using, just in case it might need it in the future.

If the OS reached a point where it needed memory back, then all processes would be asked to relinquish such memory, and your application would be no different.

You can simulate this by minimising and restoring your application.  Unless your application is genuinely using all of the memory currently allocated, you should see a drop in memory use.  This drop might be slight or it could be significant, depending on the memory usage profile of your application.

When a (Delphi) application is minimized it will return some/as much memory to the system, on the basis that if the user has minimized it then it is now a "backgrond" process which is not likely to need to have any demands for memoy in the near future.

You can trigger this behaviour with some code in your application OnIdle event, but doing so is mostly pointless.  It may give the impression of reduced memory use in Task Manager, but will potentially reduce performance of your application and doesn't actually reduce your memory usage.

What Can I Do About It ?

The Delphi runtime has always supported the ability to replace the application heap manager with alternative implementations.

A popular one (which has been adopted as the new standard since Delphi 2006) is FastMM.  This implements strategies that avoid or reduce memory fragmentation and provides other performance and debugging improvements (it can be configured to report memory leaks and incorrectly used references to destroyed objects, for example).

FastMM  is open source and can be used even in a Delphi 7 application.  All you need to do is download the source and add FastMM as the first unit used in your project dpr file.


来源: stackexchange

问:
Swift 3.0 Get User Location Coordinates from Different View Controller
I have two view controllers - one with the mapView that is able to obtain user location coordinations through locationManager, and a second VC that I wish to be able to pull these user coordinates.

First VC: MapView

```<code>func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    var coordinatesOfUser = locations.last?.coordinate
    print("The value of usercoordinates are \(coordinatesOfUser)")

    // here I want to be able to pull this variable, coordinatesOfUser

    if let location = locations.last {
        let span = MKCoordinateSpanMake(0.00775, 0.00775)
        let myLocation = CLLocationCoordinate2DMake(location.coordinate.latitude,location.coordinate.longitude)
        let region = MKCoordinateRegionMake(myLocation, span)
        map.setRegion(region, animated: true)
    }
    self.map.showsUserLocation = true
    locationManager.stopUpdatingLocation()

}
</code>```

Second VC:

I was thinking of calling the locationManager function in this VC. Is this the most efficient way to pull the coordinates to this VC? And if so, how would I go about doing it?

答:
Here's a couple options to solve this:

Delegation: Your secondVC could have a delegate that allows the first view controller to get coordinates from it. The advantage here is that you could receive updates as the come in.

```<code>protocol MyLocationDelegate: class {
    func newLocationArrived(location: CLLocation)
}

class FirstVC: UIViewController, MyLocationDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func newLocationArrived(location: CLLocation) {
        print(location)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let dest = segue.destination as? SecondVC {
            dest.delegate = self
        }
    }
}

class SecondVC: UIViewController, CLLocationManagerDelegate {

    /// ... ...

    weak var delegate: MyLocationDelegate?

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        /// do something with the location

        /// provide the data via delegation
        delegate?.newLocationArrived(location: CLLocation())
    }
}
</code>```

Notifications: Post a notification via NSNotificationCenter. Also able to receive updates as the come in, just send via notification center instead of through a delegate.

postNotificationName:object:userInfo:

Child View Controller: Depending on whether the second view controller and its view are a child of the first, this could allow direct access. Not always an option.

Singleton (CLLocationManager): If you plan to use Location Services in other places throughout the app, you can move the CLLocationManager into its own class with a Singleton. Other view controllers can reference that class for their specific needs. This can also be helpful when using the background or significant change locations as they might need to use the LaunchOptions Key to restart the location manager.

```<code>class MyLocationManager: CLLocationManager, CLLocationManagerDelegate {

    static let shared = MyLocationManager()

    var locations = [CLLocation]()

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        for location in locations {
            self.locations.append(location)
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two view controllers - one with the mapView that is able to obtain user location coordinations through locationManager, and a second VC that I wish to be able to pull these user coordinates.

First VC: MapView

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    var coordinatesOfUser = locations.last?.coordinate
    print("The value of usercoordinates are \(coordinatesOfUser)")

    // here I want to be able to pull this variable, coordinatesOfUser

    if let location = locations.last {
        let span = MKCoordinateSpanMake(0.00775, 0.00775)
        let myLocation = CLLocationCoordinate2DMake(location.coordinate.latitude,location.coordinate.longitude)
        let region = MKCoordinateRegionMake(myLocation, span)
        map.setRegion(region, animated: true)
    }
    self.map.showsUserLocation = true
    locationManager.stopUpdatingLocation()

}

Second VC:

I was thinking of calling the locationManager function in this VC. Is this the most efficient way to pull the coordinates to this VC? And if so, how would I go about doing it?

Body:
Here's a couple options to solve this:

Delegation: Your secondVC could have a delegate that allows the first view controller to get coordinates from it. The advantage here is that you could receive updates as the come in.

protocol MyLocationDelegate: class {
    func newLocationArrived(location: CLLocation)
}

class FirstVC: UIViewController, MyLocationDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func newLocationArrived(location: CLLocation) {
        print(location)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let dest = segue.destination as? SecondVC {
            dest.delegate = self
        }
    }
}

class SecondVC: UIViewController, CLLocationManagerDelegate {

    /// ... ...

    weak var delegate: MyLocationDelegate?

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        /// do something with the location

        /// provide the data via delegation
        delegate?.newLocationArrived(location: CLLocation())
    }
}

Notifications: Post a notification via NSNotificationCenter. Also able to receive updates as the come in, just send via notification center instead of through a delegate.

postNotificationName:object:userInfo:

Child View Controller: Depending on whether the second view controller and its view are a child of the first, this could allow direct access. Not always an option.

Singleton (CLLocationManager): If you plan to use Location Services in other places throughout the app, you can move the CLLocationManager into its own class with a Singleton. Other view controllers can reference that class for their specific needs. This can also be helpful when using the background or significant change locations as they might need to use the LaunchOptions Key to restart the location manager.

class MyLocationManager: CLLocationManager, CLLocationManagerDelegate {

    static let shared = MyLocationManager()

    var locations = [CLLocation]()

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        for location in locations {
            self.locations.append(location)
        }
    }
}


问:
click in datatable to filter other charts (dc.js)
I need to filter other charts when I click a row in the datatable.

I did

```<code>my_table.on('pretransition', function (table) {
     table.selectAll('td.dc-table-column')
          .on('click',function(d){
                table.filter(d.key)
                dc.redrawAll();
           })
});
</code>```

but nothing happens in the other charts.

Can you help me, please?

答:
If the table dimension is a dimension...

The data that ordinarily populates a data table is the raw rows from the original data set, not key/value pairs.

So it is likely that d.key is undefined.

I'd advise you first to stick

```<code>console.log(d)
</code>```

into your click handler to see what your data looks like, to make sure d.key is valid.

Second, remember that a chart filters through its dimension. So you will need to pass a value to table.filter() that is a valid key for your dimension, and then it will filter out all rows for which the key is different. This may not be just the one row that you chose.

Typically a table dimension is chosen for the way it orders the values for the rows. You might actually want to filter some other dimension. But hopefully this is enough to get you started.

But what if the the table dimension is a group?

The above technique will only work if your table takes a crossfilter dimension as its dimension. If, as in the fiddle you linked in the comments, you're using a group as your dimension, that object has no .filter() method, so the table.filter() method won't do anything.

If you only need to filter the one item that was clicked, you could just do

```<code>foodim.filter(d.key)
</code>```

This has an effect but it's not that useful.

If you need the toggle functionality used in dc's ordinal charts, you'll need to simulate it. It's not all that complicated:

```<code>// global
var filterKeys = [];

// inside click event

                if(filterKeys.indexOf(d.key)===-1)
                  filterKeys.push(d.key);
                else
                  filterKeys = filterKeys.filter(k => k != d.key);
                if(filterKeys.length === 0)
                  foodim.filter(null);
                else
                  foodim.filterFunction(function(d) {
                    return filterKeys.indexOf(d) !== -1;
                  })
</code>```

Example fiddle: https://jsfiddle.net/gordonwoodhull/kfmfkLj0/9/

Body:
I need to filter other charts when I click a row in the datatable.

I did

my_table.on('pretransition', function (table) {
     table.selectAll('td.dc-table-column')
          .on('click',function(d){
                table.filter(d.key)
                dc.redrawAll();
           })
});

but nothing happens in the other charts.

Can you help me, please?

Body:
If the table dimension is a dimension...

The data that ordinarily populates a data table is the raw rows from the original data set, not key/value pairs.

So it is likely that d.key is undefined.

I'd advise you first to stick

console.log(d)

into your click handler to see what your data looks like, to make sure d.key is valid.

Second, remember that a chart filters through its dimension. So you will need to pass a value to table.filter() that is a valid key for your dimension, and then it will filter out all rows for which the key is different. This may not be just the one row that you chose.

Typically a table dimension is chosen for the way it orders the values for the rows. You might actually want to filter some other dimension. But hopefully this is enough to get you started.

But what if the the table dimension is a group?

The above technique will only work if your table takes a crossfilter dimension as its dimension. If, as in the fiddle you linked in the comments, you're using a group as your dimension, that object has no .filter() method, so the table.filter() method won't do anything.

If you only need to filter the one item that was clicked, you could just do

foodim.filter(d.key)

This has an effect but it's not that useful.

If you need the toggle functionality used in dc's ordinal charts, you'll need to simulate it. It's not all that complicated:

// global
var filterKeys = [];

// inside click event

                if(filterKeys.indexOf(d.key)===-1)
                  filterKeys.push(d.key);
                else
                  filterKeys = filterKeys.filter(k => k != d.key);
                if(filterKeys.length === 0)
                  foodim.filter(null);
                else
                  foodim.filterFunction(function(d) {
                    return filterKeys.indexOf(d) !== -1;
                  })

Example fiddle: https://jsfiddle.net/gordonwoodhull/kfmfkLj0/9/


问:
How to remove css property in jQuery
```<code>if(prev_clicked)
{
    $("#accordion li a.category").css('background-image', 'url("img/off_all_channel.png")');
    $("#accordion li a.comment").css('background-image', 'url("img/on_all_online.png")');
    $(".icha0").removeProperty("background-color");
    $(".icha0").removeProperty("opacity");
}
else
{
   $(".icha0").css("background-color","#D5D5D2");
   $(".icha0").css("opacity","0.70");
}
</code>```

I am trying to remove two css properties that I added but It seems not working.
Any though?

答:
We have two ways, either you can directly remove the applied CSS style class which is applied to DOM element or remove the applied CSS style from element</p>

```<code>//Remove the class associated with element

$('#ID').removeClass("cssClass");

//Remove the CSS style from DOM element

$('p').css({"color":""});
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to remove css property in jQuery

Body:
if(prev_clicked)
{
    $("#accordion li a.category").css('background-image', 'url("img/off_all_channel.png")');
    $("#accordion li a.comment").css('background-image', 'url("img/on_all_online.png")');
    $(".icha0").removeProperty("background-color");
    $(".icha0").removeProperty("opacity");
}
else
{
   $(".icha0").css("background-color","#D5D5D2");
   $(".icha0").css("opacity","0.70");
}

I am trying to remove two css properties that I added but It seems not working.
Any though?

Body:
We have two ways, either you can directly remove the applied CSS style class which is applied to DOM element or remove the applied CSS style from element

//Remove the class associated with element

$('#ID').removeClass("cssClass");

//Remove the CSS style from DOM element

$('p').css({"color":""});


问:
Removing characters from strings with LINQ
I'm trying to brush up on my LINQ by writing some simple extension methods. Is there any better way to write such a function as below that removes a given list of characters from a string (using LINQ)?

It helps me to think of the extension methods that LINQ relies on first:

```<code>public static string Remove(this string s, IEnumerable<char> chars)
{
    string removeChars = string.Concat(chars);

    return new string(s.ToCharArray().Where(c => !removeChars.Contains(c)).ToArray());
}
</code>```

But that's pretty ugly. Ergo LINQ.

The difference that I notice in the LINQ statement is that I have to use 'select' whereas with the extension method, I don't have to.

```<code>/// <summary>Strip characters out of a string.</summary>
/// <param name="chars">The characters to remove.</param>
public static string Remove(this string s, IEnumerable<char> chars)
{
    string removeChars = string.Concat(chars);

    var stripped = from c in s.ToCharArray()
                   where !removeChars.Contains(c)
                   select c;

    return new string(stripped.ToArray());
}
</code>```

So I'm wondering if this (last snippet above) is the tersest LINQ statement to accomplish removal of characters.

答:
try this for terseness

```<code>public static string Remove(this string source, IEnumerable<char> chars) {
  return new String(source.Where(x => !chars.Contains(x)).ToArray());
}
</code>```

EDIT

Updated to correct it removing duplicates from source

OwnerDisplayName: Chris

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to brush up on my LINQ by writing some simple extension methods. Is there any better way to write such a function as below that removes a given list of characters from a string (using LINQ)?

It helps me to think of the extension methods that LINQ relies on first:

public static string Remove(this string s, IEnumerable<char> chars)
{
    string removeChars = string.Concat(chars);

    return new string(s.ToCharArray().Where(c => !removeChars.Contains(c)).ToArray());
}

But that's pretty ugly. Ergo LINQ.

The difference that I notice in the LINQ statement is that I have to use 'select' whereas with the extension method, I don't have to.

/// Strip characters out of a string.
/// <param name="chars">The characters to remove.</param>
public static string Remove(this string s, IEnumerable<char> chars)
{
    string removeChars = string.Concat(chars);

    var stripped = from c in s.ToCharArray()
                   where !removeChars.Contains(c)
                   select c;

    return new string(stripped.ToArray());
}

So I'm wondering if this (last snippet above) is the tersest LINQ statement to accomplish removal of characters.

LastEditorDisplayName: Chris

Body:
try this for terseness

public static string Remove(this string source, IEnumerable<char> chars) {
  return new String(source.Where(x => !chars.Contains(x)).ToArray());
}

EDIT

Updated to correct it removing duplicates from source

OwnerDisplayName: JaredPar

LastEditorDisplayName: JaredPar


问:
How can I select random words from an external file in java processing?
I have this assignment that I have to make a word cloud of the most common words used in an external text file which all words will start from the center and expand/animate to a word cloud... I already made a word counter to determine which words are most often used in the text file, now that I know which words are most often used, how can I select at least 15 random words from the top 50 most used words in the text file?

if that question can be easily answered how can I overlap all the selected words on the canvas?

note: I am very noob at java and processing so a code would help...

here is my code:

```<code>    String[] words;
    IntDict concordance;
    int index = 0;

    void setup() {
      size(500, 500);
      background(0);
      String[] lines = loadStrings("alice_just_text.txt");
      String entireplay = join(lines, " ");
      words = splitTokens(entireplay, ",.?!:-;:()03 ");
      concordance = new IntDict();
      frameRate(5);

      for (int i = 0; i < words.length; i++) {
        concordance.increment(words[i].toLowerCase());
      }
      concordance.sortValuesReverse();

      String[] keys = concordance.keyArray();
      for (int i = 0; i < keys.length; i++) {
        int count = concordance.get(keys[i]); //word counts
        println(keys[i], count);

      }

    }

    void draw() {

      background(0);
      textSize(64);
      textAlign(CENTER);
      text(words[index], width / 2, height / 2);
      index++;

    }
</code>```

答:
This should do the trick</p>

```<code>String[] top = Arrays.copyOfRange(keys, 0, 50);
List<String> list = Arrays.asList(top);
Collections.shuffle(list);
top = (String[]) list.toArray();

for (int i = 0; i < 15; i++) {
    System.out.println(top[i]); //do something
}
</code>```

Body:
I have this assignment that I have to make a word cloud of the most common words used in an external text file which all words will start from the center and expand/animate to a word cloud... I already made a word counter to determine which words are most often used in the text file, now that I know which words are most often used, how can I select at least 15 random words from the top 50 most used words in the text file?

if that question can be easily answered how can I overlap all the selected words on the canvas?

note: I am very noob at java and processing so a code would help...

here is my code:

    String[] words;
    IntDict concordance;
    int index = 0;

    void setup() {
      size(500, 500);
      background(0);
      String[] lines = loadStrings("alice_just_text.txt");
      String entireplay = join(lines, " ");
      words = splitTokens(entireplay, ",.?!:-;:()03 ");
      concordance = new IntDict();
      frameRate(5);

      for (int i = 0; i < words.length; i++) {
        concordance.increment(words[i].toLowerCase());
      }
      concordance.sortValuesReverse();

      String[] keys = concordance.keyArray();
      for (int i = 0; i < keys.length; i++) {
        int count = concordance.get(keys[i]); //word counts
        println(keys[i], count);

      }

    }

    void draw() {

      background(0);
      textSize(64);
      textAlign(CENTER);
      text(words[index], width / 2, height / 2);
      index++;

    }

Body:
This should do the trick

String[] top = Arrays.copyOfRange(keys, 0, 50);
List<String> list = Arrays.asList(top);
Collections.shuffle(list);
top = (String[]) list.toArray();

for (int i = 0; i < 15; i++) {
    System.out.println(top[i]); //do something
}


问:
What web.config setting will allow apple-app-site-association to be served?
I have added the apple-app-site-association file to the root of a website, but IIS is not delivering the file.

What is the best way to make the server serve this specific file without a file extension? Is there a way within a web.config to explicitly say "serve this file"?

答:
I was having the same issue and found this amazing post:

Serving apple-app-site-association from IIS
IIS only serves files of known types, defined by their file extension. Since apple-app-site-association doesn’t include a file extention, IIS throws a 404 error, when I try to open it with a browser. I fixed this by adding a mimeMap in the web.config file:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <staticContent>
      <!-- required for apple-app-site-association: -->
      <mimeMap fileExtension="." mimeType="application/json" />
    </staticContent>
  </system.webServer>
</configuration>
</code>```

Body:
I was having the same issue and found this amazing post:

Serving apple-app-site-association from IIS
IIS only serves files of known types, defined by their file extension. Since apple-app-site-association doesn’t include a file extention, IIS throws a 404 error, when I try to open it with a browser. I fixed this by adding a mimeMap in the web.config file:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <staticContent>
      <!-- required for apple-app-site-association: -->
      <mimeMap fileExtension="." mimeType="application/json" />
    </staticContent>
  </system.webServer>
</configuration>


问:
Using Excel's FIND Function to search for wildcard characters
I would like to extract a substring to the right of a ** by using the FIND function. However, when I use the following formula,

=RIGHT(A2, FIND("~**", A2))

I receive the #VALUE error message. My understanding is that to search for wildcard characters in Excel strings, you must precede the wild-card with a ~ so I don't get why this formula does not work. Please see the attached image for the string and substring (intended) fields.String and Substring fields

Body:
Consider:

=MID(A2,FIND("**",A2)+2,9999)


问:
When I try to delete list I got a list size greater than list size+1
```<code>List<Studentdb> list = teacherDao.viewstudent(facultyid, batchid1);
System.out.println("" + list);
int i = 0;
for (Iterator<Studentdb> s = list.iterator(); s.hasNext(); ) {
     System.out.println("" + i);
     System.out.println("list========" + list.get(i).getRoll());
     if (teacherDao.viewmarks(subjectcode, list.get(i).getRoll())) {
           list.remove(s);
     }
    i++;
}
</code>```

When I try to delete a selected list i get the error java.lang.IndexOutOfBoundsException: Index: 3, Size: 3.

Here I have list size 3 i.e index 0 1 2 and I got the error in index 3.

答:
Just include a condition such that it breaks, after reaching at the position size-1.
And i hope u know very well that if the size of a list is n, the list gets indexing from 0 to n-1.
In your error message, what it actually says is that, Your are trying to iterate to an item which is out of the allocated area of the list.</p>

Body:
List<Studentdb> list = teacherDao.viewstudent(facultyid, batchid1);
System.out.println("" + list);
int i = 0;
for (Iterator<Studentdb> s = list.iterator(); s.hasNext(); ) {
     System.out.println("" + i);
     System.out.println("list========" + list.get(i).getRoll());
     if (teacherDao.viewmarks(subjectcode, list.get(i).getRoll())) {
           list.remove(s);
     }
    i++;
}

When I try to delete a selected list i get the error java.lang.IndexOutOfBoundsException: Index: 3, Size: 3.

Here I have list size 3 i.e index 0 1 2 and I got the error in index 3.


问:
scraping data in dt dd tags with links inside them
Actually I want to scrape data from a website "https://www.crunchbase.com/organization/ani-technologies#/entity" where my data is present inside dt and dd tags and since bot are not allowed on the website. So I saved the page and applied beautifulsoup module on that saved page by this way,though I have mentioned actual url in the code

```<code>soup = BeautifulSoup(open(r"C:\Users\acer\Desktop\pythonbooks\tam.html").read())
</code>```

```<code>import requests
ctr=1
file=requests.get("https://www.crunchbase.com/organization/ani-technologies#/entity")
soup = BeautifulSoup(file).read()
dl_data = soup.find_all("dd")
for dlitem in dl_data:
    print(ctr,dlitem.string)
    ctr+=1
</code>```

Actual Output:

```<code>0 3 Acquisitions
1 None
2 Bengaluru, Karnataka
3 Ola is a mobile app for cab booking in India.
4 None
5 None
6 olacab link
7 None
8 December 3, 2010
9 ANI Technologies Pvt Ltd, Olacabs.com, Ola Cabs, Olacabs
10 media@olacabs.com
11 None
</code>```

Here at several places I got None due to the facts that there were hyperlinks to the contents.for e.g. on the page "https://www.crunchbase.com/organization/ani-technologies#/entity" the categories tab have 5 categories named :E-Commerce, Internet, Transportation, Apps and Mobile and each one is connected to a hyperlink so I cant get the text that I want i.e. these 5 categories.

What I want as output as:

```<code>0 3 Acquisitions
1 (All that text (though not important to me))
2 Bengaluru, Karnataka
3 Ola is a mobile app for cab booking in India.
4 (all that text(though not important to me))
==>5 (E-Commerce, Internet, Transportation, Apps, Mobile)(Extremely important)
6 olacab link
7 (all that text(though not important to me))
8 December 3, 2010
9 ANI Technologies Pvt Ltd, Olacabs.com, Ola Cabs, Olacabs
10 media@olacabs.com
11 (all that text(though not important to me))
</code>```

It will be most helpful if I can get dictionary something like this :

```<code>{"Headquarters":["Bengaluru,Karnataka"],
 "Description":["Ola is a mobile app for cab booking in India."],
 "Category": ["E-Commerce", "Internet", "Transportation", "Apps", "Mobile"]}
</code>```

答:
Question: ... I cant get the text that I want ... if I can get dictionary ...

Get text/href from all
text
, to aggregate into a dict, for instance:

```<code>from collections import OrderedDict
os_dict = OrderedDict()

for div_class in ['definition-list-container', 'details definition-list']:
    divs = soup.find_all("div", class_=div_class)
    key = '?'
    for div in divs:
        for child in div.findChildren():
            if child.name == 'dt':
                key = child.text[:-1]
            if child.name == 'dd':
                if child.select('a[href]'):
                    a_list = child.find_all("a")
                    if key in ['Social:']:
                        os_dict[key] = [a['href'] for a in a_list]
                    elif len(a_list) == 1:
                        os_dict[key] = a_list[0].text
                    else:
                        os_dict[key] = [a.text for a in a_list]
                else:
                    os_dict[key] = child.text

for n, key in enumerate(os_dict, 1):
    print('{:>2}: {:>20}:\t{}'.format(n, key, os_dict[key]))
</code>```

Outuput:

```<code> 1:          Acquisition:   3 Acquisitions
 2:  Total Equity Fundin:   ['11 Rounds', '24 Investors']
 3:         Headquarters:   Bengaluru, Karnataka
 4:          Description:   Ola is a mobile app for cab booking in India.
 5:             Founders:   ['Bhavish Aggarwal', 'Ankit Bhati']
 6:           Categories:   ['E-Commerce', 'Internet', 'Transportation', 'Apps', 'Mobile']
 7:              Website:   http://www.olacabs.com
 8:              Social::   ['http://www.facebook.com/olacabs', 'http://twitter.com/olacabs', 'http://www.linkedin.com/company/olacabs-com']
 9:              Founded:   December 3, 2010
10:              Aliases:   ANI Technologies Pvt Ltd, Olacabs.com, Ola Cabs, Olacabs
11:              Contact:   media@olacabs.com
12:            Employees:   8 in Crunchbase
</code>```

Beautiful Soup Documentation: href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all" rel="nofollow noreferrer">find-all

  Signature: find_all(name, attrs, recursive, string, limit, **kwargs)

```<code>dl_data = soup.find_all("dd")
for n, dlitem in enumerate(dl_data, 1):
    if dlitem.select('a[href]'):
        a_text = [a.text for a in dlitem.find_all("a")]
        print('{}: {}'.format(n, a_text))
    else:
        print('{}: {}'.format(n, dlitem.text))
</code>```

Tested with Python:3.4.2 - bs4:4.6.0

Body:
Actually I want to scrape data from a website "https://www.crunchbase.com/organization/ani-technologies#/entity" where my data is present inside dt and dd tags and since bot are not allowed on the website. So I saved the page and applied beautifulsoup module on that saved page by this way,though I have mentioned actual url in the code

soup = BeautifulSoup(open(r"C:\Users\acer\Desktop\pythonbooks\tam.html").read())

import requests
ctr=1
file=requests.get("https://www.crunchbase.com/organization/ani-technologies#/entity")
soup = BeautifulSoup(file).read()
dl_data = soup.find_all("dd")
for dlitem in dl_data:
    print(ctr,dlitem.string)
    ctr+=1

Actual Output:

0 3 Acquisitions
1 None
2 Bengaluru, Karnataka
3 Ola is a mobile app for cab booking in India.
4 None
5 None
6 olacab link
7 None
8 December 3, 2010
9 ANI Technologies Pvt Ltd, Olacabs.com, Ola Cabs, Olacabs
10 media@olacabs.com
11 None

Here at several places I got None due to the facts that there were hyperlinks to the contents.for e.g. on the page "https://www.crunchbase.com/organization/ani-technologies#/entity" the categories tab have 5 categories named :E-Commerce, Internet, Transportation, Apps and Mobile and each one is connected to a hyperlink so I cant get the text that I want i.e. these 5 categories.

What I want as output as:

0 3 Acquisitions
1 (All that text (though not important to me))
2 Bengaluru, Karnataka
3 Ola is a mobile app for cab booking in India.
4 (all that text(though not important to me))
==>5 (E-Commerce, Internet, Transportation, Apps, Mobile)(Extremely important)
6 olacab link
7 (all that text(though not important to me))
8 December 3, 2010
9 ANI Technologies Pvt Ltd, Olacabs.com, Ola Cabs, Olacabs
10 media@olacabs.com
11 (all that text(though not important to me))

It will be most helpful if I can get dictionary something like this :

{"Headquarters":["Bengaluru,Karnataka"],
 "Description":["Ola is a mobile app for cab booking in India."],
 "Category": ["E-Commerce", "Internet", "Transportation", "Apps", "Mobile"]}

Body:
Question: ... I cant get the text that I want ... if I can get dictionary ...

Get text/href from all <dd><a href=...>text</dd>, to aggregate into a dict, for instance:

from collections import OrderedDict
os_dict = OrderedDict()

for div_class in ['definition-list-container', 'details definition-list']:
    divs = soup.find_all("div", class_=div_class)
    key = '?'
    for div in divs:
        for child in div.findChildren():
            if child.name == 'dt':
                key = child.text[:-1]
            if child.name == 'dd':
                if child.select('a[href]'):
                    a_list = child.find_all("a")
                    if key in ['Social:']:
                        os_dict[key] = [a['href'] for a in a_list]
                    elif len(a_list) == 1:
                        os_dict[key] = a_list[0].text
                    else:
                        os_dict[key] = [a.text for a in a_list]
                else:
                    os_dict[key] = child.text

for n, key in enumerate(os_dict, 1):
    print('{:>2}: {:>20}:\t{}'.format(n, key, os_dict[key]))

Outuput:

 1:          Acquisition:   3 Acquisitions
 2:  Total Equity Fundin:   ['11 Rounds', '24 Investors']
 3:         Headquarters:   Bengaluru, Karnataka
 4:          Description:   Ola is a mobile app for cab booking in India.
 5:             Founders:   ['Bhavish Aggarwal', 'Ankit Bhati']
 6:           Categories:   ['E-Commerce', 'Internet', 'Transportation', 'Apps', 'Mobile']
 7:              Website:   http://www.olacabs.com
 8:              Social::   ['http://www.facebook.com/olacabs', 'http://twitter.com/olacabs', 'http://www.linkedin.com/company/olacabs-com']
 9:              Founded:   December 3, 2010
10:              Aliases:   ANI Technologies Pvt Ltd, Olacabs.com, Ola Cabs, Olacabs
11:              Contact:   media@olacabs.com
12:            Employees:   8 in Crunchbase

Beautiful Soup Documentation: find-all

  Signature: find_all(name, attrs, recursive, string, limit, **kwargs)

dl_data = soup.find_all("dd")
for n, dlitem in enumerate(dl_data, 1):
    if dlitem.select('a[href]'):
        a_text = [a.text for a in dlitem.find_all("a")]
        print('{}: {}'.format(n, a_text))
    else:
        print('{}: {}'.format(n, dlitem.text))

Tested with Python:3.4.2 - bs4:4.6.0


问:
cp hundreds of files to different directories
The title not might be the best, I apologize, I'm rather new to scripting.

I'm trying to copy 2 files from each directory and place these compounds in a separate directory that only shares directory names.

for clarity;

```<code>/path/to/directory/all/variable_directories/
</code>```

Inside this directory will be multiple files, I need 2 files which will have the same name in every individual variable directory.

I am trying to copy these 2 files from each individual variable directory and put them in variable directories based on the basename of /variable_directory/

the copy destination will be;

```<code>/path/to/magical/shit/subset/set_with_variable_name/variable_directories/
</code>```

Only some of the destination directories are located in each /set_with_variable_name/

The script will need to be able to go through each /set_with_variable_name/ until it finds the directory that shares the basename of the directory that these files are originally being cp'd from

There's about 100 directories
to cp from and to and about 200 files total that need to be copied and sorted appropriately.

I can get it to cp ALL the files to the SAME directory using;

```<code>#! /usr/bin/env bash
for i in */;
do cd $i;
cp filename /path/to/destination/;
cp other_filename /path/to/destination/;
cd ..;
done;
</code>```

It's the sorting the files to the correct destinations that I am completely lost at.

I appreciate any help, I'm a novice to this type of scripting

答:
Looks like you need something like that.</p>

```<code># looping through all the variable directories
for var_dir in <path1>/all/*; do

    # creating the destination directory if not exists
    mkdir -p "<path2>/set_with_variable_name/$(basename ${var_dir})"

    # copying the first file
    cp "${var_dir}/filename1" "<path2>/set_with_variable_name/$(basename ${var_dir})/filename1"

    # and the second
    cp "${var_dir}/filename2" "<path2>/set_with_variable_name/$(basename ${var_dir})/filename2"
done
</code>```

Body:
The title not might be the best, I apologize, I'm rather new to scripting.

I'm trying to copy 2 files from each directory and place these compounds in a separate directory that only shares directory names.

for clarity;

/path/to/directory/all/variable_directories/

Inside this directory will be multiple files, I need 2 files which will have the same name in every individual variable directory.

I am trying to copy these 2 files from each individual variable directory and put them in variable directories based on the basename of /variable_directory/

the copy destination will be;

/path/to/magical/shit/subset/set_with_variable_name/variable_directories/

Only some of the destination directories are located in each /set_with_variable_name/

The script will need to be able to go through each /set_with_variable_name/ until it finds the directory that shares the basename of the directory that these files are originally being cp'd from

There's about 100 directories
to cp from and to and about 200 files total that need to be copied and sorted appropriately.

I can get it to cp ALL the files to the SAME directory using;

#! /usr/bin/env bash
for i in */;
do cd $i;
cp filename /path/to/destination/;
cp other_filename /path/to/destination/;
cd ..;
done;

It's the sorting the files to the correct destinations that I am completely lost at.

I appreciate any help, I'm a novice to this type of scripting

Body:
Looks like you need something like that.

# looping through all the variable directories
for var_dir in <path1>/all/*; do

    # creating the destination directory if not exists
    mkdir -p "<path2>/set_with_variable_name/$(basename ${var_dir})"

    # copying the first file
    cp "${var_dir}/filename1" "<path2>/set_with_variable_name/$(basename ${var_dir})/filename1"

    # and the second
    cp "${var_dir}/filename2" "<path2>/set_with_variable_name/$(basename ${var_dir})/filename2"
done


问:
C++: set multiple variables from array
I have the following program:

```<code>#include <iostream>
using namespace std;

int main()
{
    int array[] = {1, 2, 3};
    int a = array[0],
        b = array[1],
        c = array[2];

    cout << c << endl;
}
</code>```

This prints 3, so far so good. But I wonder if there is a more elegant syntax for declaring multiple variables from an array at once. For example (just an idea, does not compile):

```<code>int [a, b, c] = array;
</code>```

Is there any feature like this in C++ or one of the new standards? I can't be the only one looking it.

Alternatively: what is your most elegant way to set multiple variables from an array at once?

答:
What you are looking for is called structured bindings and it will be available in C++17.  They will allow you to create references to the elements of arrays, certain classes/structs and tuple like objects.

Since your looking for a pre C++17 solution really the best you can do is use std::tie to construct tuples that refer to what you want to assign like

```<code>int array[] = {1, 2, 3};
int a, b, c;
std::tie(a, b, c) = std::tie(array[0], array[1], array[2])
</code>```

But that really doesn't save you much.

Title: C++: set multiple variables from array

Body:
I have the following program:

#include <iostream>
using namespace std;

int main()
{
    int array[] = {1, 2, 3};
    int a = array[0],
        b = array[1],
        c = array[2];

    cout << c << endl;
}

This prints 3, so far so good. But I wonder if there is a more elegant syntax for declaring multiple variables from an array at once. For example (just an idea, does not compile):

int [a, b, c] = array;

Is there any feature like this in C++ or one of the new standards? I can't be the only one looking it.

Alternatively: what is your most elegant way to set multiple variables from an array at once?

Body:
What you are looking for is called structured bindings and it will be available in C++17.  They will allow you to create references to the elements of arrays, certain classes/structs and tuple like objects.

Since your looking for a pre C++17 solution really the best you can do is use std::tie to construct tuples that refer to what you want to assign like

int array[] = {1, 2, 3};
int a, b, c;
std::tie(a, b, c) = std::tie(array[0], array[1], array[2])

But that really doesn't save you much.


问:
simplemodal iframe with close (X) icon?
I'm using simplemodal to display an external web page in an iframe. It works perfect. But I'm not sure my users are going to get the Esc key, or clicking outside the modal to close the modal window. I'd like to add a close icon "X" in the corner but i cant get it to appear. Is this supported for iframe? I could sure use and example. I'm trying to use what I see on simplemodal home but i'm not getting it.

Many Thanks for a simple modal,
Mike

答: Getting rid of closeHTML:"" will fix the problem and the X image will work. </p>

Title: simplemodal iframe with close (X) icon?


问:
Slow performance Azure 'Web App' + Azure SQL DB
I've moved an existing asp.net web-api over from an Azure VM (with IIS and MSSQL installed locally) to an Azure web app and Azure SQL database (both west-europe). I'm noticing a dramatic increase in processing duration between the two for the same workload. Tasks that take 10-15ms on the VM, take at least 150ms in the hosted service environment. Both internal processing, not including network latency to/from the vm or web app. Both with empty databases and the same code-base. Same database schema with the same indexing.

The VM was a simple 2-core/7GB SSD machine. But even when I set my web app to a premium 4-core/7GB and my database to a premium 250DTU, the performance does not increase at all. In fact, its the same on a basic 2-core web app and 10DTU database. So the bottleneck has to be somewhere else.

How would I go about finding out what causes the slow processing? The web app and database show no performance alerts and don't advise scaling up either.

答:
Run the following query per session/workload to know what is the type of wait occurring during those workloads:

--your query here

```<code>go

select *
from sys.dm_exec_session_wait_stats
where session_id = @@spid
order by wait_time_ms desc
</code>```

The last SELECT statement will provide you all waits for current session.

You can also enable Query Store.

http://www.sqlcoffee.com/Azure_0010.htm

And run the following query to know what makes queries wait during execution

```<code>select  wait_category_desc, sum(total_query_wait_time_ms) as [sum ms], count(*) as [interval cnt],  avg(avg_query_wait_time_ms) as [avg ms], sum(total_query_wait_time_ms / avg_query_wait_time_ms) as [wait cnt]
from sys.query_store_wait_stats
group by wait_category_desc
order by [sum ms] desc
</code>```

The following article will tell you the meaning of each wait category.

https://learn.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-query-store-wait-stats-transact-sql

Hope this helps.

Body:
Run the following query per session/workload to know what is the type of wait occurring during those workloads:

--your query here

go

select *
from sys.dm_exec_session_wait_stats
where session_id = @@spid
order by wait_time_ms desc

The last SELECT statement will provide you all waits for current session.

You can also enable Query Store.

http://www.sqlcoffee.com/Azure_0010.htm

And run the following query to know what makes queries wait during execution

select  wait_category_desc, sum(total_query_wait_time_ms) as [sum ms], count(*) as [interval cnt],  avg(avg_query_wait_time_ms) as [avg ms], sum(total_query_wait_time_ms / avg_query_wait_time_ms) as [wait cnt]
from sys.query_store_wait_stats
group by wait_category_desc
order by [sum ms] desc

The following article will tell you the meaning of each wait category.

https://learn.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-query-store-wait-stats-transact-sql

Hope this helps.


问:
Common approach to design web page components layout
Starting to design web page layout from the scratch for a first time and want to know what's the best practice to set web page and all components on it measurements.
The page will have horizontal header with a navigation bar in it and a three columns beneath it.
That's what I've come up with so far:

fixed hight in pixels for header part with horizontally aligned nav links

fixed hight and width in pixels for web components

components resides in a three columns (div elements) that has min-width set

Do I miss something or it's a good way to go?

PS  I'm perfectly aware of Bootstrap etc, but cannot use any framework in this project, only pure html/css

答: Here is my solution: Try Quick Slicer for the initial layout sketch, and then edit the code, fine tune the CSS (.scss in fact), refactor the dimensions to absolute pixels or ems (if necessary?), and fill the content texts to meet your needs.


问:
Does python time.strftime process timezone options correctly (for RFC 3339)
I'm trying to get RFC3339 compatible output from python's time module, using the time.strftime() function.

With the Linux 'date' command, I can use a format string like the following: "date +%F_%T%:z"

```<code>$ date +%F_%T%:z
2017-06-29_16:13:29-07:00
</code>```

When used with python time.strftime, the %:z appears to not be supported.

```<code>$ python
>>> import time
>>> print time.strftime("%F %T%:z")
2017-06-29 16:16:15%:z
</code>```

Apparently, '%z' is supported, but '%:z' is not:

```<code>>>> print time.strftime("%F %T%z")
2017-05-29 16:15:35-0700
</code>```

RFC3339 specifically uses the timezone offset with the embedded colon.
That would be 07:00 in my case, instead of 0700.

I believe the omission of support for the "%:z' option is due to the underlying C implementation of strftime() not supporting the versions of timezone offset formatters with colons.  That is '%:z', '%::z', etc.

Is there any workaround for this (e.g. another python module, or some option I'm missing int the 'time' module), other than writing code to get %z output and reformat it in %:z format, to solve this problem?

EDIT: Another question (Generate RFC 3339 timestamp in Python) gives solutions for other modules that can be used to output RFC3339 output.  I'm going to self-answer with information that I found for the question in the title.

答:
The strict answer to the question in the title "Does python time.strftime process timezone options correctly (for RFC3339)?" is: No.

The "%:z" supported by the Linux 'date' command is a GNU extension, and is not in the POSIX spec, or in the C implementation of strftime (as of this writing).

With regards to workarounds (requested in the body of the question), answers in Generate RFC 3339 timestamp in Python can be used as alternatives time.strftime to output RFC3339-compliant software.

Specifically, I used the pytz module to get timezone information, and datetime class isoformat() function to print in RFC3339-compliant format (with a colon in the timezone offset portion of the output).  Like so:
(in Python 2.7 on Ubuntu 14.04)

```<code>>>> import pytz, datetime
>>> latz = pytz.timezone("America/Los_Angeles")
>>> latz
<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>
>>> dt = datetime.datetime.now(latz)
>>> dt2 = datetime.datetime(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0, latz)
>>> dt2.isoformat()
'2017-07-06T11:50:07-08:00'
</code>```

Note the conversion from dt to dt2, to set microseconds to 0.  This prevents isoformat from printing microseconds as a decimal portion of seconds in the isoformat output (which RFC3339 does not support)

Body:
I'm trying to get RFC3339 compatible output from python's time module, using the time.strftime() function.

With the Linux 'date' command, I can use a format string like the following: "date +%F_%T%:z"

$ date +%F_%T%:z
2017-06-29_16:13:29-07:00

When used with python time.strftime, the %:z appears to not be supported.

$ python
>>> import time
>>> print time.strftime("%F %T%:z")
2017-06-29 16:16:15%:z

Apparently, '%z' is supported, but '%:z' is not:

>>> print time.strftime("%F %T%z")
2017-05-29 16:15:35-0700

RFC3339 specifically uses the timezone offset with the embedded colon.
That would be 07:00 in my case, instead of 0700.

I believe the omission of support for the "%:z' option is due to the underlying C implementation of strftime() not supporting the versions of timezone offset formatters with colons.  That is '%:z', '%::z', etc.

Is there any workaround for this (e.g. another python module, or some option I'm missing int the 'time' module), other than writing code to get %z output and reformat it in %:z format, to solve this problem?

EDIT: Another question (Generate RFC 3339 timestamp in Python) gives solutions for other modules that can be used to output RFC3339 output.  I'm going to self-answer with information that I found for the question in the title.

Body:
The strict answer to the question in the title "Does python time.strftime process timezone options correctly (for RFC3339)?" is: No.

The "%:z" supported by the Linux 'date' command is a GNU extension, and is not in the POSIX spec, or in the C implementation of strftime (as of this writing).

With regards to workarounds (requested in the body of the question), answers in Generate RFC 3339 timestamp in Python can be used as alternatives time.strftime to output RFC3339-compliant software.

Specifically, I used the pytz module to get timezone information, and datetime class isoformat() function to print in RFC3339-compliant format (with a colon in the timezone offset portion of the output).  Like so:
(in Python 2.7 on Ubuntu 14.04)

>>> import pytz, datetime
>>> latz = pytz.timezone("America/Los_Angeles")
>>> latz
<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>
>>> dt = datetime.datetime.now(latz)
>>> dt2 = datetime.datetime(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0, latz)
>>> dt2.isoformat()
'2017-07-06T11:50:07-08:00'

Note the conversion from dt to dt2, to set microseconds to 0.  This prevents isoformat from printing microseconds as a decimal portion of seconds in the isoformat output (which RFC3339 does not support)


问:
How to do error handling in a REST API with Express middleware routing
Assume we have a REST API with the following route:

app.post("/accounts/:accountId", isAuthorized, isSelf, updateAccount);

Within this scenario, a lot can go wrong. The user could be unauthorized because he is not logged in, or because he is trying to update an account which is not his, or he is missing a required property value. Using middleware you can extract certain validation, so it can be used across multiple routes.

The situation

I am creating a POST to this route, but I do not sent an authorization header. The isAuthorized, successfully captures the error, and instead of calling the next function, it will use a res.send(403) or something. The isSelf and updateAccount function would do something similair.

The problem

I need to manually follow a pattern across all the functions to return a similar error handling. Which is - as a developer - pretty error prone. Since it's fairly easy to mess up conventions when you would need to manage it across all kind of files.

The question

What is the simplest way to manage errors?

Please note that all the middleware functions are custom functions, so they can be written to follow a generalized approach.

答:
You have to define your last middleware to be the error handling function like this:

```<code>app.use((err, req, res, next) => {
    res.status(err.status).json(err);
});
</code>```

And in your route you can do:

```<code>app.get('/',() => {
    var err = {};
    err.message = 'Not found'
    err.status = 404;
    next(err)
})
</code>```

Body:
You have to define your last middleware to be the error handling function like this:

app.use((err, req, res, next) => {
    res.status(err.status).json(err);
});

And in your route you can do:

app.get('/',() => {
    var err = {};
    err.message = 'Not found'
    err.status = 404;
    next(err)
})


问:
How to Clone an Eclipse Workspace
I am wondering how to create new clean Eclipse workspace but having all settings from an existing one.
Maybe something like cloning but without projects?</p>

答: Just copy the whole workspace on your local file system. That works for me because my new feature branch is got the same pom file and thus the overall build matches up. This way I don't need to import all the projects again.</p>

Title: How to Clone an Eclipse Workspace


问:
passing relu function to all element of a numpy array
I am trying to pass a relu function to each individual element of a numpy array, when I try it with a sigmoid function, it works but with the relu function, it returns:

```<code>ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code>```

relu function:

```<code>def relu(x):
    return max(0, x)
</code>```

sigmoid function:

```<code>def sigmoid(x):
    return 1 / (1 + np.exp(-x))
</code>```

I tried doing relu(myArray) but it returns the valueError, same with map(relu, myArray)

it works fine with sigmoid function, why is it doing that and how can I fix it? thanks

答: You need numpy.maximum. The regular built-in max doesn't broadcast over array inputs.

Body:
I am trying to pass a relu function to each individual element of a numpy array, when I try it with a sigmoid function, it works but with the relu function, it returns:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

relu function:

def relu(x):
    return max(0, x)

sigmoid function:

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

I tried doing relu(myArray) but it returns the valueError, same with map(relu, myArray)

it works fine with sigmoid function, why is it doing that and how can I fix it? thanks


问:
Best approach for (cross-platform) real-time data streaming in PHP?
I've been wondering how to do "true" (semi) real-time data streaming with PHP.

Possible applications: chat rooms, auctions, games, etc.

By "true", I mean the data is not just written somewhere and polled continuously, but actually streaming to the client somehow.

By "semi", I mean it's okay if only the stream from the server to the client is real-time, and messages from the client to the server are not.

For the communication between the client and server, I'd like to stick with plain HTTP (AJAX) rather than some other protocol.

Streaming to the client with HTTP is possible by manually flushing the output buffer.

The question is what to connect that script to on the server-side?

And once it's connected, to do a blocking read, rather than polling for changes.

The shared memory (shmop) extension would work, but it's not cross-platform.

Perhaps memcached would work? But I'm not sure if there's a way to do a blocking read, so it comes down to polling again - although I'm sure memcached is pretty fast, I just don't like the idea of continuous polling.

Any ideas?

答:
If you're using HTML and Javascript, then you want WebSockets.  If it's Flash or anything else, then normal TCP sockets.

The idea for either is that you run a server file (written in PHP), that waits for connections.  Once it's connected to one or more clients, data can be pushed both ways.  There are a few PHP WebSocket projects out there.  Check out this:

http://code.google.com/p/phpwebsocket

There's also a framework called Skeleton that I've been contributing to that has a WebSocket server library built in.  Still in the unstable stages, though.

http://code.google.com/p/skeleton

Unfortunately, WebSockets are still a new technology, so they're not supported universally.  As @Christian mentioned, you may want to use the Socket.IO library.


问:
Mobx @inject @observer order
I have a fetch in my componentDidMount that does not refresh the appState data when I do @observer @inject('appState') but it would consistently work when I have @inject('appState') @observer .

At the same time, I'm getting a warning in the console that my order is wrong.

Mobx observer: You are trying to use 'observer' on a component that already has 'inject'. Please apply 'observer' before applying 'inject'

Which is the correct order and why?

答: Decorators are sugar for function calls, so @a @b class C is a similar to a(b(class C)), in other words, the inner most (or right most) is the first applied decorator. So applying observer before applying inject means: inject("stores")(observer(Component)), in other words, the order that works for you is the order that is intended: @inject('appState') @oberver Component

Title: Mobx @inject @observer order


问:
Issues with Loop -- Cannot Move Past First Iteration
I am trying to copy data from a series of sheets (dynamically created based on user preferences) into a master sheet located at the end. However, after the first loop, Excel runs into an object oriented error (1004).

```<code>Dim MacroWorkbook As Workbook
Set MacroWorkbook = Thisworkbook

Dim NumSheets As Integer
Dim DataSheets As Integer
Dim LCounter As Single

'Count the number of sheets
NumSheets = MacroWorkbook.Worksheets.Count
'Count the number of sheets minus the mastersheet (located at the end).
DataSheets = NumSheets - 1

'As long as the counter is less than the number of total sheets (i.e. master sheet)
Do While LCounter < NumSheets
    LCounter = LCounter + 1
    MacroWorkbook.Sheets(LCounter).Range(Range("A2"), Range("AU5001")).Copy
    MacroWorkbook.Sheets(NumSheets).Range("A1").End(xlDown).PasteSpecial Paste:=xlPasteValues
Loop
</code>```

1) Why can't Excel execute on the second loop?

2) Does the error have to do with using Copy/Paste? Is there a more efficient/less clunky way of doing this?

答:
Probably because you need to add sheet references to all ranges, but your code would appear to be overwriting each time you paste? And your Do line should refer to DataSheets rather than NumSheets I think.</p>

```<code>Dim MacroWorkbook As Workbook
Set MacroWorkbook = ThisWorkbook

Dim NumSheets As Integer
Dim DataSheets As Integer
Dim LCounter As Single

'Count the number of sheets
NumSheets = MacroWorkbook.Worksheets.Count
'Count the number of sheets minus the mastersheet (located at the end).
DataSheets = NumSheets - 1

'As long as the counter is less than the number of total sheets (i.e. master sheet)
Do While LCounter < NumSheets
    LCounter = LCounter + 1
    With MacroWorkbook
        .Sheets(LCounter).Range(.Sheets(LCounter).Range("A2"), .Sheets(LCounter).Range("AU5000")).Copy
        .Sheets(NumSheets).Range("A2").PasteSpecial Paste:=xlPasteValues
    End With
Loop
</code>```

Body:
I am trying to copy data from a series of sheets (dynamically created based on user preferences) into a master sheet located at the end. However, after the first loop, Excel runs into an object oriented error (1004).

Dim MacroWorkbook As Workbook
Set MacroWorkbook = Thisworkbook

Dim NumSheets As Integer
Dim DataSheets As Integer
Dim LCounter As Single

'Count the number of sheets
NumSheets = MacroWorkbook.Worksheets.Count
'Count the number of sheets minus the mastersheet (located at the end).
DataSheets = NumSheets - 1

'As long as the counter is less than the number of total sheets (i.e. master sheet)
Do While LCounter < NumSheets
    LCounter = LCounter + 1
    MacroWorkbook.Sheets(LCounter).Range(Range("A2"), Range("AU5001")).Copy
    MacroWorkbook.Sheets(NumSheets).Range("A1").End(xlDown).PasteSpecial Paste:=xlPasteValues
Loop

1) Why can't Excel execute on the second loop?

2) Does the error have to do with using Copy/Paste? Is there a more efficient/less clunky way of doing this?

Body:
Probably because you need to add sheet references to all ranges, but your code would appear to be overwriting each time you paste? And your Do line should refer to DataSheets rather than NumSheets I think.

Dim MacroWorkbook As Workbook
Set MacroWorkbook = ThisWorkbook

Dim NumSheets As Integer
Dim DataSheets As Integer
Dim LCounter As Single

'Count the number of sheets
NumSheets = MacroWorkbook.Worksheets.Count
'Count the number of sheets minus the mastersheet (located at the end).
DataSheets = NumSheets - 1

'As long as the counter is less than the number of total sheets (i.e. master sheet)
Do While LCounter < NumSheets
    LCounter = LCounter + 1
    With MacroWorkbook
        .Sheets(LCounter).Range(.Sheets(LCounter).Range("A2"), .Sheets(LCounter).Range("AU5000")).Copy
        .Sheets(NumSheets).Range("A2").PasteSpecial Paste:=xlPasteValues
    End With
Loop


问:
Remove all constraints affecting a UIView
I have a UIView which is placed on the screen via several constraints. Some of the constraints are owned by the superview, others are owned by other ancestors (e.g. perhaps the view property of a UIViewController).

I want to remove all of these old constraints, and place it somewhere new using new constraints.

How can I do this without creating an IBOutlet for every single constraint and having to remember which view owns said constraint?

To elaborate, the naive approach would be to create a bunch of IBOutlets for each of the constraints, and would then involve calling code such as:

```<code>[viewA removeConstraint:self.myViewsLeftConstraint];
[viewB removeConstraint:self.myViewsTopConstraint];
[viewB removeConstraint:self.myViewsBottomConstraint];
[self.view removeConstraint:self.myViewsRightConstraint];
</code>```

The problem with this code is that even in the simplest case, I would need to create 2 IBOutlets. For complex layouts, this could easily reach 4 or 8 required IBOutlets. Furthermore, I would need to ensure that my call to remove the constraint is being called on the proper view. For example, imagine that myViewsLeftConstraint is owned by viewA. If I were to accidentally call [self.view removeConstraint:self.myViewsLeftConstraint], nothing would happen.

Note: The method constraintsAffectingLayoutForAxis looks promising, but is intended for debugging purposes only.

Update: Many of the answers I am receiving deal with self.constraints, self.superview.constraints, or some variant of those. These solutions won't work since those methods return only the constraints owned by the view, not the ones affecting the view.

To clarify the problem with these solutions, consider this view hierarchy:

Grandfather

Father

Me

Son

Daughter

Brother

Uncle

Now imagine we create the following constraints, and always attach them to their nearest common ancestor:

C0: Me: same top as Son (owned by Me)

C1: Me: width = 100 (owned by Me)

C2: Me: same height as Brother (owned by Father)

C3: Me: same top as Uncle (owned by Grandfather)

C4: Me: same left as Grandfather (owned by Grandfather)

C5: Brother: same left as Father (owned by Father)

C6: Uncle: same left as Grandfather (owned by Grandfather)

C7: Son: same left as Daughter (owned by Me)

Now imagine we want to remove all constraints affecting Me. Any proper solution should remove [C0,C1,C2,C3,C4] and nothing else.

If I use self.constraints (where self is Me), I will get [C0,C1,C7], since those are the only constraints owned by Me. Obviously it wouldn't be enough to remove this since it is missing [C2,C3,C4]. Furthermore, it is removing C7 unnecessarily.

If I use self.superview.constraints (where self is Me), I will get [C2,C5], since those are the constraints owned by Father. Obviously we cannot remove all these since C5 is completely unrelated to Me.

If I use grandfather.constraints, I will get [C3,C4,C6]. Again, we cannot remove all of these since C6 should remain intact.

The brute force approach is to loop over each of the view's ancestors (including itself), and seeing if firstItem or secondItem are the view itself; if so, remove that constraint. This will lead to a correct solution, returning [C0,C1,C2,C3,C4], and only those constraints.

However, I'm hoping there is a more elegant solution than having to loop through the entire list of ancestors.

答:
(As of July 31, 2017)

SWIFT 3

```<code>self.yourCustomView.removeFromSuperview()
self.yourCustomViewParentView.addSubview(self.yourCustomView)
</code>```

Objective C

```<code>[self.yourCustomView removeFromSuperview];
[self.yourCustomViewParentView addSubview:self.yourCustomView];
</code>```

This is the easiest way to quickly remove all constraints that exist on a UIView. Just be sure to add the UIView back with it's new constraints or new frame afterwards =)

Body:
I have a UIView which is placed on the screen via several constraints. Some of the constraints are owned by the superview, others are owned by other ancestors (e.g. perhaps the view property of a UIViewController).

I want to remove all of these old constraints, and place it somewhere new using new constraints.

How can I do this without creating an IBOutlet for every single constraint and having to remember which view owns said constraint?

To elaborate, the naive approach would be to create a bunch of IBOutlets for each of the constraints, and would then involve calling code such as:

[viewA removeConstraint:self.myViewsLeftConstraint];
[viewB removeConstraint:self.myViewsTopConstraint];
[viewB removeConstraint:self.myViewsBottomConstraint];
[self.view removeConstraint:self.myViewsRightConstraint];

The problem with this code is that even in the simplest case, I would need to create 2 IBOutlets. For complex layouts, this could easily reach 4 or 8 required IBOutlets. Furthermore, I would need to ensure that my call to remove the constraint is being called on the proper view. For example, imagine that myViewsLeftConstraint is owned by viewA. If I were to accidentally call [self.view removeConstraint:self.myViewsLeftConstraint], nothing would happen.

Note: The method constraintsAffectingLayoutForAxis looks promising, but is intended for debugging purposes only.

Update: Many of the answers I am receiving deal with self.constraints, self.superview.constraints, or some variant of those. These solutions won't work since those methods return only the constraints owned by the view, not the ones affecting the view.

To clarify the problem with these solutions, consider this view hierarchy:

Grandfather

Father

Me

Son

Daughter

Brother

Uncle

Now imagine we create the following constraints, and always attach them to their nearest common ancestor:

C0: Me: same top as Son (owned by Me)

C1: Me: width = 100 (owned by Me)

C2: Me: same height as Brother (owned by Father)

C3: Me: same top as Uncle (owned by Grandfather)

C4: Me: same left as Grandfather (owned by Grandfather)

C5: Brother: same left as Father (owned by Father)

C6: Uncle: same left as Grandfather (owned by Grandfather)

C7: Son: same left as Daughter (owned by Me)

Now imagine we want to remove all constraints affecting Me. Any proper solution should remove [C0,C1,C2,C3,C4] and nothing else.

If I use self.constraints (where self is Me), I will get [C0,C1,C7], since those are the only constraints owned by Me. Obviously it wouldn't be enough to remove this since it is missing [C2,C3,C4]. Furthermore, it is removing C7 unnecessarily.

If I use self.superview.constraints (where self is Me), I will get [C2,C5], since those are the constraints owned by Father. Obviously we cannot remove all these since C5 is completely unrelated to Me.

If I use grandfather.constraints, I will get [C3,C4,C6]. Again, we cannot remove all of these since C6 should remain intact.

The brute force approach is to loop over each of the view's ancestors (including itself), and seeing if firstItem or secondItem are the view itself; if so, remove that constraint. This will lead to a correct solution, returning [C0,C1,C2,C3,C4], and only those constraints.

However, I'm hoping there is a more elegant solution than having to loop through the entire list of ancestors.

Body:
(As of July 31, 2017)

SWIFT 3

self.yourCustomView.removeFromSuperview()
self.yourCustomViewParentView.addSubview(self.yourCustomView)

Objective C

[self.yourCustomView removeFromSuperview];
[self.yourCustomViewParentView addSubview:self.yourCustomView];

This is the easiest way to quickly remove all constraints that exist on a UIView. Just be sure to add the UIView back with it's new constraints or new frame afterwards =)


问:
Distinguish sender from receiver with Socket.io
I have built a web application using JavaScript stack (MongoDB, ExpressJS, AngularJS, NodeJS). The registration works, the authentication works, the chat is which is using Socket.io works but I need a way of distinguishing which client is sending and which client is receiving the message in order to perform further functions with the user's data.

P.S. Since this is a project that I can not publish there are no code snippets in my post, hopefully it is alright

答:
The ultimate design will depend on what you are trying to achieve. Is is "a one-to-one chat" service or maybe a "one to many broadcast". Is the service anonymous? How do you want users find each other? How secure does it need to be?

As a starting point I would assign a unique identifier (UID) to each connection (client). This will allow the server to direct traffic by creating "conversation" pairings or perhaps a list of listeners (subscribers) and writers (publishers).

A connected user could then enter the UID of a second connected user and your service can post messages back and forth using the uid pairing.

conversation(user123,user0987)

  user123 send to user0987

  user0987 send to user123

or go bulletin board/chat room style:

create a "board" - just a destination that is a list of all text sent

 user123 "joins" board "MiscTalk"

 user0987 "joins board "MiscTalk"

each sends text to the server, server adds that text to the board and each client polls the board for changes.

Every Socket can send or recieve, your program must track "who" is connected on a socket and direct traffic between them.


问:
Bash reading users y/n answer does not work (read command inside while loop reading find output)
I have a problem here. Seems like my Bash script is ignoring everything that is between do and done. Don't know why, maybe you will see the problem. Thanks in advance.

```<code>katalogas=$1
find $katalogas -type f -mtime +3 | while read $failai
do
read -p "Run command $foo? [yn]" answer
if [[ $answer = y ]] ; then
  rm $failai
fi
done
</code>```

答:
use the command reset
and then execute your shell script.

Body:
I have a problem here. Seems like my Bash script is ignoring everything that is between do and done. Don't know why, maybe you will see the problem. Thanks in advance.

katalogas=$1
find $katalogas -type f -mtime +3 | while read $failai
do
read -p "Run command $foo? [yn]" answer
if [[ $answer = y ]] ; then
  rm $failai
fi
done


问:
Transform a list into a map - foreach or streams?
I want to transform a List<String> into a Map<String, Integer>. The lists' values should serve as keys, and the map value will be statically initialized.

I want to keep the order of the list, thus using a LinkedHashMap, and ignore duplicates.

Question: is there any advantage using the java8 stream API? Because, comparing the following, simply regarding the syntax I'd never go for the verbose stream api, but always sticking to the old foreach loop:

```<code>    //foreach
    Map<String, Integer> map = new LinkedHashMap<>();
    for (String k : abk) {
        if (k != null) map.put(k, STATIC_VAL);
    }

    //streams
    Map<String, Integer> map2 = abk.stream()
            .filter(Objects::nonNull)
            .collect(Collectors.toMap(
                        Function.identity(),
                        k -> STATIC_VAL,
                        (v1, v2) -> v1,
                        LinkedHashMap::new));
</code>```

Would you stick to the old approach or go with new lambda expressions?

答:
There's a variant on the traditional for loop that you can use as well:

```<code>Map<String, Integer> map = new LinkedHashMap<>();
abk.forEach(k -> if (k != null) map.put(k, STATIC_VAL));
</code>```

But it's just a matter of style. Either this way or the traditional for loop looks good to me. Using streams, on the other hand, is more verbose and less readable, IMO.

Body:
I want to transform a List<String> into a Map<String, Integer>. The lists' values should serve as keys, and the map value will be statically initialized.

I want to keep the order of the list, thus using a LinkedHashMap, and ignore duplicates.

Question: is there any advantage using the java8 stream API? Because, comparing the following, simply regarding the syntax I'd never go for the verbose stream api, but always sticking to the old foreach loop:

    //foreach
    Map<String, Integer> map = new LinkedHashMap<>();
    for (String k : abk) {
        if (k != null) map.put(k, STATIC_VAL);
    }

    //streams
    Map<String, Integer> map2 = abk.stream()
            .filter(Objects::nonNull)
            .collect(Collectors.toMap(
                        Function.identity(),
                        k -> STATIC_VAL,
                        (v1, v2) -> v1,
                        LinkedHashMap::new));

Would you stick to the old approach or go with new lambda expressions?

Body:
There's a variant on the traditional for loop that you can use as well:

Map<String, Integer> map = new LinkedHashMap<>();
abk.forEach(k -> if (k != null) map.put(k, STATIC_VAL));

But it's just a matter of style. Either this way or the traditional for loop looks good to me. Using streams, on the other hand, is more verbose and less readable, IMO.


问:
How to use v-select but not repeat itself while using v-for
I have array of json in groupData, how to pass the data to v-select

I know what I am doing is wrong by using v-for inside v-select, but I am not sure how to pass data:

```<code><v-select multiple
  v-for="group in groupsData"
  :value.sync="selected"
  :options="[{label: group.group_name, value: group.id}]">
</v-select>
</code>```

Plugin URL: https://sagalbot.github.io/vue-select/

This is how it's done with vue.js without v-select plugin and this works:

```<code><select v-model="selected" multiple>
  <option v-for="group in groupsData" v-bind:value="group.group_id">{{group.group_name}}</option>
</select>
</code>```

Thanks in advance.

答:
Typically I use a computed property.

```<code>new Vue({
  el:"#app",
  data:{
    groupsData: groups,
    selected:[]
  },
  computed:{
    selectOptions(){
      return this.groupsData.map(g => ({label: g.group_name, value: g.id}))
    }
  }
})
</code>```

And in your template

```<code><v-select multiple
          :value.sync="selected"
          :options="selectOptions">
</v-select>
</code>```

Working example.

Body:
I have array of json in groupData, how to pass the data to v-select

I know what I am doing is wrong by using v-for inside v-select, but I am not sure how to pass data:

<v-select multiple
  v-for="group in groupsData"
  :value.sync="selected"
  :options="[{label: group.group_name, value: group.id}]">
</v-select>

Plugin URL: https://sagalbot.github.io/vue-select/

This is how it's done with vue.js without v-select plugin and this works:

<select v-model="selected" multiple>
  <option v-for="group in groupsData" v-bind:value="group.group_id">{{group.group_name}}</option>
</select>

Thanks in advance.

Body:
Typically I use a computed property.

new Vue({
  el:"#app",
  data:{
    groupsData: groups,
    selected:[]
  },
  computed:{
    selectOptions(){
      return this.groupsData.map(g => ({label: g.group_name, value: g.id}))
    }
  }
})

And in your template

<v-select multiple
          :value.sync="selected"
          :options="selectOptions">
</v-select>

Working example.


答:
Just use

```<code>result = map(relu, array)
</code>```

to apply your function to every element of the array.

```<code>    import numpy as np

    def relu(x):
        return max(0, x)

    array = np.arange(-10,10)

    result = map(relu, array)
    print(result)
</code>```

Works for me.

Title: passing relu function to all element of a numpy array

Body:
Just use

result = map(relu, array)

to apply your function to every element of the array.

    import numpy as np

    def relu(x):
        return max(0, x)

    array = np.arange(-10,10)

    result = map(relu, array)
    print(result)

Works for me.