问:
Downloading files using Indy TIdHTTP
I currently have a program that downloads a file from my VPS and extracts it. I want to make it download straight from the original website, but it doesn't want to work. I want to make it download this link:

https://bintray.com/oxidemod/builds/download_file?file_path=Oxide-Rust.zip

Instead of this:

http://41.185.91.51/RSM/Oxide-Rust.zip

Edit: Using this link:

https://dl.bintray.com/oxidemod/builds/Oxide-Rust.zip

Also doesnt work, even when using the SSL protocol.

I'm using RAD Studio 10.2 Tokyo.

I found the following post, but I'm struggling to add it to my current project:

Downloaded files using TIdHTTP INDY 10

Here is my current project code:

```<code>unit uOxideModInstaller;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.ComCtrls,
  Vcl.StdCtrls, IdBaseComponent, IdComponent,
  IdTCPConnection, IdTCPClient, IdHTTP, System.Zip;

type

  TDownload = class;

  Tfrmoxidemodinstaller = class(TForm)
    lbl1: TLabel;
    pb1: TProgressBar;
    btn1: TButton;
    btn2: TButton;
    lblstatus: TLabel;
    procedure btn2Click(Sender: TObject);
    procedure btn1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

  TDownload = class(TThread)
  private
    httpclient: TIdHTTP;
    url: string;
    filename: string;
    maxprogressbar: integer;
    progressbarstatus: integer;
    procedure ExtractZip(ZipFile: string; ExtractPath: string);
    procedure idhttp1Work(ASender: TObject; AWorkMode: TWorkMode;
      AWorkCount: Int64);
    procedure idhttp1WorkBegin(ASender: TObject; AWorkMode: TWorkMode;
      AWorkCountMax: Int64);
    procedure UpdateProgressBar;
    procedure SetMaxProgressBar;
  protected
    procedure Execute; override;
  public
    constructor Create(CreateSuspended: boolean; aurl, afilename: string);
    destructor Destroy; override;
  end;

var
  frmoxidemodinstaller: Tfrmoxidemodinstaller;

implementation

{$R *.dfm}
{ Thread }

constructor TDownload.Create(CreateSuspended: boolean; aurl, afilename: string);
begin
  inherited Create(CreateSuspended);
  httpclient := TIdHTTP.Create(nil);
  httpclient.OnWorkBegin := idhttp1WorkBegin;
  httpclient.OnWork := idhttp1Work;
  url := aurl;
  filename := afilename;
end;

procedure TDownload.idhttp1Work(ASender: TObject; AWorkMode: TWorkMode;
  AWorkCount: Int64);
begin
  progressbarstatus := AWorkCount;
  Queue(UpdateProgressBar);

end;

procedure TDownload.idhttp1WorkBegin(ASender: TObject; AWorkMode: TWorkMode;
  AWorkCountMax: Int64);
begin
  maxprogressbar := AWorkCountMax;
  Queue(SetMaxProgressBar);
end;

procedure TDownload.Execute;
var
  Stream: TMemoryStream;
begin
  Stream := TMemoryStream.Create;
  try
    httpclient.Get(url, Stream);
    Stream.SaveToFile(filename);
  finally
    Stream.Free;
  end;
end;

procedure TDownload.UpdateProgressBar;
var
  ZipFile: string;
begin
  frmoxidemodinstaller.pb1.Position := progressbarstatus;
  frmoxidemodinstaller.lblstatus.Caption := 'Downloading...';

  if frmoxidemodinstaller.pb1.Position = frmoxidemodinstaller.pb1.Max then
  begin
    frmoxidemodinstaller.lblstatus.Caption := 'Done Downloading. Installing...';
    Sleep(2000);
    ExtractZip('oxide.zip', GetCurrentDir);
  end;
end;

procedure TDownload.SetMaxProgressBar;
begin
  frmoxidemodinstaller.pb1.Max := maxprogressbar;
end;

destructor TDownload.Destroy;
begin
  FreeAndNil(httpclient);
  inherited Destroy;
end;

{ TForm1 }

procedure TDownload.ExtractZip(ZipFile, ExtractPath: string);
begin
  if TZipFile.IsValid(ZipFile) then
  begin
    TZipFile.ExtractZipFile(ZipFile, ExtractPath);
    frmoxidemodinstaller.lblstatus.Caption := 'Oxide Installed!';
    DeleteFile(ZipFile);
  end
  else
  begin
    ShowMessage('Error installing oxide!');
    frmoxidemodinstaller.lblstatus.Caption := 'Error Installing Oxide!';
  end;
end;

procedure Tfrmoxidemodinstaller.btn1Click(Sender: TObject);
var
  DownloadThread: TDownload;
  link: string;
begin
  link := 'http://41.185.91.51/RSM/Oxide-Rust.zip';
  DownloadThread := TDownload.Create(true, link, 'oxide.zip');
  DownloadThread.FreeOnTerminate := true;
  DownloadThread.Start;
end;

procedure Tfrmoxidemodinstaller.btn2Click(Sender: TObject);
begin
  Close;
end;

end.
</code>```

答:
This url:

https://bintray.com/oxidemod/builds/download_file?file_path=Oxide-Rust.zip

Returns an HTTP 302 redirect to this url:

https://dl.bintray.com/oxidemod/builds/Oxide-Rust.zip

Because of this, you need to handle HTTP redirections.  Set the TIdHTTP.HandleRedirects property to true (it is false by default).

If you are using Delphi 10.2 Tokyo or later, you can alternatively use Delphi's own System.Net.HttpClient.THTTPClient instead.  It does not need any external SSL libraries, like TIdHTTP does.  Be sure to set the THTTPClient.HandleRedirects property to true.

Title: Downloading files using Indy TIdHTTP

Body:
I currently have a program that downloads a file from my VPS and extracts it. I want to make it download straight from the original website, but it doesn't want to work. I want to make it download this link:

https://bintray.com/oxidemod/builds/download_file?file_path=Oxide-Rust.zip

Instead of this:

http://41.185.91.51/RSM/Oxide-Rust.zip

Edit: Using this link:

https://dl.bintray.com/oxidemod/builds/Oxide-Rust.zip

Also doesnt work, even when using the SSL protocol.

I'm using RAD Studio 10.2 Tokyo.

I found the following post, but I'm struggling to add it to my current project:

Downloaded files using TIdHTTP INDY 10

Here is my current project code:

unit uOxideModInstaller;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.ComCtrls,
  Vcl.StdCtrls, IdBaseComponent, IdComponent,
  IdTCPConnection, IdTCPClient, IdHTTP, System.Zip;

type

  TDownload = class;

  Tfrmoxidemodinstaller = class(TForm)
    lbl1: TLabel;
    pb1: TProgressBar;
    btn1: TButton;
    btn2: TButton;
    lblstatus: TLabel;
    procedure btn2Click(Sender: TObject);
    procedure btn1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

  TDownload = class(TThread)
  private
    httpclient: TIdHTTP;
    url: string;
    filename: string;
    maxprogressbar: integer;
    progressbarstatus: integer;
    procedure ExtractZip(ZipFile: string; ExtractPath: string);
    procedure idhttp1Work(ASender: TObject; AWorkMode: TWorkMode;
      AWorkCount: Int64);
    procedure idhttp1WorkBegin(ASender: TObject; AWorkMode: TWorkMode;
      AWorkCountMax: Int64);
    procedure UpdateProgressBar;
    procedure SetMaxProgressBar;
  protected
    procedure Execute; override;
  public
    constructor Create(CreateSuspended: boolean; aurl, afilename: string);
    destructor Destroy; override;
  end;

var
  frmoxidemodinstaller: Tfrmoxidemodinstaller;

implementation

{$R *.dfm}
{ Thread }

constructor TDownload.Create(CreateSuspended: boolean; aurl, afilename: string);
begin
  inherited Create(CreateSuspended);
  httpclient := TIdHTTP.Create(nil);
  httpclient.OnWorkBegin := idhttp1WorkBegin;
  httpclient.OnWork := idhttp1Work;
  url := aurl;
  filename := afilename;
end;

procedure TDownload.idhttp1Work(ASender: TObject; AWorkMode: TWorkMode;
  AWorkCount: Int64);
begin
  progressbarstatus := AWorkCount;
  Queue(UpdateProgressBar);

end;

procedure TDownload.idhttp1WorkBegin(ASender: TObject; AWorkMode: TWorkMode;
  AWorkCountMax: Int64);
begin
  maxprogressbar := AWorkCountMax;
  Queue(SetMaxProgressBar);
end;

procedure TDownload.Execute;
var
  Stream: TMemoryStream;
begin
  Stream := TMemoryStream.Create;
  try
    httpclient.Get(url, Stream);
    Stream.SaveToFile(filename);
  finally
    Stream.Free;
  end;
end;

procedure TDownload.UpdateProgressBar;
var
  ZipFile: string;
begin
  frmoxidemodinstaller.pb1.Position := progressbarstatus;
  frmoxidemodinstaller.lblstatus.Caption := 'Downloading...';

  if frmoxidemodinstaller.pb1.Position = frmoxidemodinstaller.pb1.Max then
  begin
    frmoxidemodinstaller.lblstatus.Caption := 'Done Downloading. Installing...';
    Sleep(2000);
    ExtractZip('oxide.zip', GetCurrentDir);
  end;
end;

procedure TDownload.SetMaxProgressBar;
begin
  frmoxidemodinstaller.pb1.Max := maxprogressbar;
end;

destructor TDownload.Destroy;
begin
  FreeAndNil(httpclient);
  inherited Destroy;
end;

{ TForm1 }

procedure TDownload.ExtractZip(ZipFile, ExtractPath: string);
begin
  if TZipFile.IsValid(ZipFile) then
  begin
    TZipFile.ExtractZipFile(ZipFile, ExtractPath);
    frmoxidemodinstaller.lblstatus.Caption := 'Oxide Installed!';
    DeleteFile(ZipFile);
  end
  else
  begin
    ShowMessage('Error installing oxide!');
    frmoxidemodinstaller.lblstatus.Caption := 'Error Installing Oxide!';
  end;
end;

procedure Tfrmoxidemodinstaller.btn1Click(Sender: TObject);
var
  DownloadThread: TDownload;
  link: string;
begin
  link := 'http://41.185.91.51/RSM/Oxide-Rust.zip';
  DownloadThread := TDownload.Create(true, link, 'oxide.zip');
  DownloadThread.FreeOnTerminate := true;
  DownloadThread.Start;
end;

procedure Tfrmoxidemodinstaller.btn2Click(Sender: TObject);
begin
  Close;
end;

end.


来源: stackexchange

问:
Can`t sort by price correctly, although sorting by name works very well
Trying to make this small bookstore app and wanted to add option to sort books by price and name, ascending and descending. Sorting by price occurs in very strange order, and can't find the reason for that, please if some could help and explain to me, I'm pretty new in Angular. Thank you!

Here is the source code: https://github.com/EgomortIncognitus/bookstore

Here is the code from sort-by.pipe.ts:

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'sortBy'
})
export class SortByPipe implements PipeTransform {

  transform(array: Array<string>, args?: any): any {

    if (array) {

      let sortField = args[0];
      let sortDirection = args[1];
      let modifier = 1;

      if (sortDirection === 'desc') {
        modifier = -1;
      }

      array.sort((a: any, b: any) => {
        if (a[sortField] < b[sortField]) {
          return -1 * modifier;
        } else if (a[sortField] > b[sortField]) {
          return 1 * modifier;
        } else {
          return 0;
        }
      });

      return array;
    }
  }

}
</code>```

答:
Sort by name and sort by number is not same in Javascript

Check this out: https://www.w3schools.com/jsref/jsref_sort.asp

ContentLicense: CC BY-SA 3.0

Body:
Trying to make this small bookstore app and wanted to add option to sort books by price and name, ascending and descending. Sorting by price occurs in very strange order, and can't find the reason for that, please if some could help and explain to me, I'm pretty new in Angular. Thank you!

Here is the source code: https://github.com/EgomortIncognitus/bookstore

Here is the code from sort-by.pipe.ts:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'sortBy'
})
export class SortByPipe implements PipeTransform {

  transform(array: Array<string>, args?: any): any {

    if (array) {

      let sortField = args[0];
      let sortDirection = args[1];
      let modifier = 1;

      if (sortDirection === 'desc') {
        modifier = -1;
      }

      array.sort((a: any, b: any) => {
        if (a[sortField]  b[sortField]) {
          return 1 * modifier;
        } else {
          return 0;
        }
      });

      return array;
    }
  }

}


问:
swift progessindicator for OS X
i have a loop, which shows me all my address book contacts.
now i would like to show an NSProgressIndicator, which should show the progress from 0 (=start request contacts) until 100 (=all contacts requested). for this I tried something like this:

```<code>let addressBook = ABAddressBook.shared()
let people = addressBook?.people()
for person in people!  as! [ABPerson] {
   print(person)
   ProgressIndicator.increment(by: 0.22)
}
</code>```

why increment by 0.22?

i have 451 contacts
100/451 = 0,22% per contact

but what happens?
i start my app. the print result will show each contact and when all contacts were requested > the progress indicator jumps to 100% directly.

what do I wrong?

Second try:

```<code>DispatchQueue.global(qos: .background).async {
   let addressBook = ABAddressBook.shared()
   let people = addressBook?.people()
   let stepPercent = 100 / (people?.count)!
   for person in people!  as! [ABPerson] {
      print(person)
      DispatchQueue.main.async {
         self.ProgressIndicator.increment(by: Double(stepPercent))
   }
}
</code>```

答:
My Solution:

```<code>DispatchQueue.global(qos: .background).async {
            let addressBook = ABAddressBook.shared()
            let people = addressBook?.people()
            print(Double((people?.count)!))
            let stepPercent = 100.00 / (Double((people?.count)!))
            print(stepPercent)
            for person in people!  as! [ABPerson] {
                print(person)
            DispatchQueue.main.async {
                self.ProgressIndicator.increment(by: Double(stepPercent))
            }
        }
</code>```

thanks for support

Title: swift progessindicator for OS X

Body:
i have a loop, which shows me all my address book contacts.
now i would like to show an NSProgressIndicator, which should show the progress from 0 (=start request contacts) until 100 (=all contacts requested). for this I tried something like this:

let addressBook = ABAddressBook.shared()
let people = addressBook?.people()
for person in people!  as! [ABPerson] {
   print(person)
   ProgressIndicator.increment(by: 0.22)
}

why increment by 0.22?

i have 451 contacts
100/451 = 0,22% per contact

but what happens?
i start my app. the print result will show each contact and when all contacts were requested > the progress indicator jumps to 100% directly.

what do I wrong?

Second try:

DispatchQueue.global(qos: .background).async {
   let addressBook = ABAddressBook.shared()
   let people = addressBook?.people()
   let stepPercent = 100 / (people?.count)!
   for person in people!  as! [ABPerson] {
      print(person)
      DispatchQueue.main.async {
         self.ProgressIndicator.increment(by: Double(stepPercent))
   }
}

Body:
My Solution:

DispatchQueue.global(qos: .background).async {
            let addressBook = ABAddressBook.shared()
            let people = addressBook?.people()
            print(Double((people?.count)!))
            let stepPercent = 100.00 / (Double((people?.count)!))
            print(stepPercent)
            for person in people!  as! [ABPerson] {
                print(person)
            DispatchQueue.main.async {
                self.ProgressIndicator.increment(by: Double(stepPercent))
            }
        }

thanks for support


问:
How to print the JSON object in Android using a try block
I need to get the JSON object from MySQL database, and to print it as string. Also, I need to pass that string to a try block to open required class activity. Here, I have attached my code below, check my code and let me know.

My JSON object sample:

```<code>{ "id": "381", "task": "user_confirm", "message": "New booking details" }
</code>```

My Android Code:

```<code>public void onMessageReceived(final RemoteMessage remoteMessage) {
    Intent intent = new Intent(this, Login_Activity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
    notificationBuilder.setContentTitle(getResources().getString(R.string.app_name));
    notificationBuilder.setContentText(remoteMessage.getNotification().getBody());
    notificationBuilder.setAutoCancel(true);
    notificationBuilder.setSmallIcon(R.mipmap.main_logo);
    notificationBuilder.setContentIntent(pendingIntent);

    Uri path = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.bike_start);
    notificationBuilder.setSound(path);
    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0,notificationBuilder.build());

    if (remoteMessage.getData().size() > 0) {
        try {
            JSONObject json = new JSONObject(remoteMessage.getData());
            Log.e("JsonOutput", json.toString());
            sendNotification(json);
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }
    if (remoteMessage.getNotification()!=null){
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }

    //        sendNotification1(String.valueOf(remoteMessage), image);
    // Log.e("body", body);
}

private void sendNotification(JSONObject json) {
    Log.e(TAG, "Notifications JSON1 " + json.toString());

    try {
         JSONObject data = json.getJSONObject("data");
         Log.d("data", String.valueOf(data));
         //parsing json data
         id = data.get("id").toString();
         message = data.get("message").toString();
         task = data.get("task").toString();
         Log.d("Id values", id);
         Log.d("Message", message);
    }
}
</code>```

Output:

Notifications JSON1 {"id":"381","task":"user_confirm","message":"New booking details"}

答:
Use like this for FCM:</p>

```<code>if (remoteMessage.getData().size() > 0) {
        String message=remoteMessage.getData().get("message");
}
</code>```

Body:
I need to get the JSON object from MySQL database, and to print it as string. Also, I need to pass that string to a try block to open required class activity. Here, I have attached my code below, check my code and let me know.

My JSON object sample:

{ "id": "381", "task": "user_confirm", "message": "New booking details" }

My Android Code:

public void onMessageReceived(final RemoteMessage remoteMessage) {
    Intent intent = new Intent(this, Login_Activity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
    notificationBuilder.setContentTitle(getResources().getString(R.string.app_name));
    notificationBuilder.setContentText(remoteMessage.getNotification().getBody());
    notificationBuilder.setAutoCancel(true);
    notificationBuilder.setSmallIcon(R.mipmap.main_logo);
    notificationBuilder.setContentIntent(pendingIntent);

    Uri path = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.bike_start);
    notificationBuilder.setSound(path);
    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0,notificationBuilder.build());

    if (remoteMessage.getData().size() > 0) {
        try {
            JSONObject json = new JSONObject(remoteMessage.getData());
            Log.e("JsonOutput", json.toString());
            sendNotification(json);
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }
    if (remoteMessage.getNotification()!=null){
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }

    //        sendNotification1(String.valueOf(remoteMessage), image);
    // Log.e("body", body);
}

private void sendNotification(JSONObject json) {
    Log.e(TAG, "Notifications JSON1 " + json.toString());

    try {
         JSONObject data = json.getJSONObject("data");
         Log.d("data", String.valueOf(data));
         //parsing json data
         id = data.get("id").toString();
         message = data.get("message").toString();
         task = data.get("task").toString();
         Log.d("Id values", id);
         Log.d("Message", message);
    }
}

Output:

Notifications JSON1 {"id":"381","task":"user_confirm","message":"New booking details"}

Body:
Use like this for FCM:

if (remoteMessage.getData().size() > 0) {
        String message=remoteMessage.getData().get("message");
}


问:
invalid security certificate and domain names
I recently purchased a security certificate for a website valid for www.example.com but not for *.example.com (wildcard version - more expensive)
The problem i have now is that although users can type http://example.com , the secure version (ssl enabled pages) https://example.com raises the invalid certificate exception - which is totally understandable.

How can i redirect https traffic to the www.example.com version before the request actually hits the server? i tried url rewritting and redirects without any luck. any ideas ?

The website is built using ASP.NET and Hosted on an IIS 7 server.

Thanks!

答:
Spend another few bucks for a (~$30 at Godaddy) for a cheap cert for the shorter domain example.com.

It seems unlikely that a significant number of users users are typing in https://example.com.  If they are typing in an address they are probably using http:// or nothing.  You should be able to setup 2 virtual hosts, one for http://example.com/, and one for http(s)://www.example.com.  Redirect everything from example.com to www.example.com

SSL is negotiated first, so there isn't really anything you can do to redirect connections from https://example.com to https://www.example.com if https://example.com has an invalid certificate.

OwnerDisplayName: seylom

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Zoredache


问:
What provides the fastest membership lookup in C#?
Why do we have to avoid membership lookup using Contains() on any native container within lambda expressions?

答:
Let's consider the following:

```<code>var source = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var matches = new[] { 12, 2, 19, 8, 40, 12, 123, 121, 1212, 122334, 2, 102, 10, 29 };
foreach (var item in source.Where(i => matches.Contains(i)))
{
    Console.WriteLine(item);
}
</code>```

Now, let's consider how many items in matches i has to be compared with before we know whether to write it out or not:

```<code>1: 14
2: 2
3: 14
5: 14
6: 14
7: 14
8: 4
9: 14
10: 13
</code>```

While we sometimes get the answer quite quickly, we generally don't especially if the answer is that we shouldn't, so we've got 103 comparisons to process 10 items. We also waste time comparing values we've already checked (the fact that 2 is in matches twice).

We're doing an O(m) operation n times so the algorithm is O(nm).

We can do better with:

```<code>var source = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var matches = new HashSet<int> { 12, 2, 19, 8, 40, 12, 123, 121, 1212, 122334, 2, 102, 10, 29 };
foreach (var item in source.Where(i => matches.Contains(i)))
{
    Console.WriteLine(item);
}
</code>```

Because Contains on a hash-set is O(1) the algorithm overall is O(n), which is about as good as it can be.

Some important things to note though are:

If the above being done on a database then whatever type matches was it would be turned into a CONTAINS part of the WHERE clause in the SQL produced, so it doesn't matter (CONTAINS is still much slower than = up to a certain number of chained = but the factors in play are different).

With relatively small sets of matches it's cheaper to take the O(n) cost of the Contains than the constant costs of creating and searching the hash-set. (The above examples will probably take about the same time to run).

So it's not something to never do, but something where you should be aware of the costs and how they are affected by the source data and the way they are run, and how to improve performance when the cost is particularly high.

It's also not particularly significant that we're using lambdas, except that lambdas letting us write some code quickly lets us write some code with hidden inefficiencies quickly, whereas if we had to write two separate foreach loops the fact that the algorithm is O(nm) would be more obvious.

Body:
Let's consider the following:

var source = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var matches = new[] { 12, 2, 19, 8, 40, 12, 123, 121, 1212, 122334, 2, 102, 10, 29 };
foreach (var item in source.Where(i => matches.Contains(i)))
{
    Console.WriteLine(item);
}

Now, let's consider how many items in matches i has to be compared with before we know whether to write it out or not:

1: 14
2: 2
3: 14
5: 14
6: 14
7: 14
8: 4
9: 14
10: 13

While we sometimes get the answer quite quickly, we generally don't especially if the answer is that we shouldn't, so we've got 103 comparisons to process 10 items. We also waste time comparing values we've already checked (the fact that 2 is in matches twice).

We're doing an O(m) operation n times so the algorithm is O(nm).

We can do better with:

var source = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var matches = new HashSet<int> { 12, 2, 19, 8, 40, 12, 123, 121, 1212, 122334, 2, 102, 10, 29 };
foreach (var item in source.Where(i => matches.Contains(i)))
{
    Console.WriteLine(item);
}

Because Contains on a hash-set is O(1) the algorithm overall is O(n), which is about as good as it can be.

Some important things to note though are:

If the above being done on a database then whatever type matches was it would be turned into a CONTAINS part of the WHERE clause in the SQL produced, so it doesn't matter (CONTAINS is still much slower than = up to a certain number of chained = but the factors in play are different).

With relatively small sets of matches it's cheaper to take the O(n) cost of the Contains than the constant costs of creating and searching the hash-set. (The above examples will probably take about the same time to run).

So it's not something to never do, but something where you should be aware of the costs and how they are affected by the source data and the way they are run, and how to improve performance when the cost is particularly high.

It's also not particularly significant that we're using lambdas, except that lambdas letting us write some code quickly lets us write some code with hidden inefficiencies quickly, whereas if we had to write two separate foreach loops the fact that the algorithm is O(nm) would be more obvious.


问:
Exclude one class file in gradle Android Studio
In my projects, I need to import third party jar file and Facebook SDK.

```<code>compile files('libs/SkinSDK.jar')
compile 'com.facebook.android:facebook-android-sdk:4.14.0'
</code>```

Both include same BundleJSONConverter class. So, I cannot do generate signed APK. It always shows duplicate entry com/facebook/internal/BundleJSONConverter.

So, I want to exclude in Facebook or SkinSDK.jar. I tried like

```<code>compile ('com.facebook.android:facebook-android-sdk:4.14.0') {
    exclude group: 'com.facebook.internal', module: 'BundleJSONConverter'
}
</code>```

It's not working and showing same error.

答:
Bumped into similar situation. This is what I did, not elegant as I hoped, but it works:

Rename the jar file (SkinSDK.jar in your case): .zip instead of .jar

Go "inside" the zip file (I'm using DoubleCommander, there are many other utilities for that), or extract it to a temporary folder.

Delete the duplicate class that causes the problem. Go "outside" the zip file.

Rename (or re-pack) the file from .zip to .jar . Compile.

Hope it works...

Body:
In my projects, I need to import third party jar file and Facebook SDK.

compile files('libs/SkinSDK.jar')
compile 'com.facebook.android:facebook-android-sdk:4.14.0'

Both include same BundleJSONConverter class. So, I cannot do generate signed APK. It always shows duplicate entry com/facebook/internal/BundleJSONConverter.

So, I want to exclude in Facebook or SkinSDK.jar. I tried like

compile ('com.facebook.android:facebook-android-sdk:4.14.0') {
    exclude group: 'com.facebook.internal', module: 'BundleJSONConverter'
}

It's not working and showing same error.


问:
Conda: update gcc and isl error
I have installed conda 4.3.22 and want to update conda gcc from 4.8.5 to 6.2.0. By using the following command I am getting an error because of the isl version. However, by trying to install a newer version of isl I am getting an error because of the gcc version. This is a rather dumb problem but I am not sure on how to get around it.

```<code>$ conda install -c salford_systems gcc-6=6.2.0
Fetching package metadata ...........
Solving package specifications:

PackageNotFoundError: Dependency missing in current linux-64 channels:
  - gcc-6 6.2.0* -> isl >=0.17,<=0.17.1

$ conda install -c conda-forge isl=0.17.1
Fetching package metadata ...........
Solving package specifications: .

UnsatisfiableError: The following specifications were found to be in conflict:
  - gcc -> isl >=0.10,<=0.14
  - isl 0.17.1*
Use "conda info <package>" to see the dependencies for each package.
</code>```

Edit 1:
As it was pointed out in the comments by darthbith, a combined command is not working and throws the following error:

```<code>$ conda install -c conda-forge -c salford_systems gcc-6=6.2.0 isl=0.17.1
Fetching package metadata .............
Solving package specifications: .

UnsatisfiableError: The following specifications were found to be in conflict:
  - gcc -> isl 0.12.*
  - gcc-6 6.2.0*
Use "conda info <package>" to see the dependencies for each package.
</code>```

Do I understand it correct, that gcc and gcc-6 are different packages of which both require a different version of isl and thus leading to my problem? I only would need a newer version of gcc which supports GLIBCXX_3.4.21.

Thanks in advance.

答:
I was able to solve my problem, thank you darthbith for helping me out.

Since gcc and gcc-6 are in fact two different packages, the solution was to delete gcc. After that, I had to update isl before I could install gcc-6. The commands used were:

```<code>conda uninstall gcc
conda install -c conda-forge isl=0.17.1
conda install -c salford_systems gcc-6=6.2.0
</code>```

Title: Conda: update gcc and isl error

Body:
I have installed conda 4.3.22 and want to update conda gcc from 4.8.5 to 6.2.0. By using the following command I am getting an error because of the isl version. However, by trying to install a newer version of isl I am getting an error because of the gcc version. This is a rather dumb problem but I am not sure on how to get around it.

$ conda install -c salford_systems gcc-6=6.2.0
Fetching package metadata ...........
Solving package specifications:

PackageNotFoundError: Dependency missing in current linux-64 channels:
  - gcc-6 6.2.0* -> isl >=0.17,<=0.17.1

$ conda install -c conda-forge isl=0.17.1
Fetching package metadata ...........
Solving package specifications: .

UnsatisfiableError: The following specifications were found to be in conflict:
  - gcc -> isl >=0.10,<=0.14
  - isl 0.17.1*
Use "conda info <package>" to see the dependencies for each package.

Edit 1:
As it was pointed out in the comments by darthbith, a combined command is not working and throws the following error:

$ conda install -c conda-forge -c salford_systems gcc-6=6.2.0 isl=0.17.1
Fetching package metadata .............
Solving package specifications: .

UnsatisfiableError: The following specifications were found to be in conflict:
  - gcc -> isl 0.12.*
  - gcc-6 6.2.0*
Use "conda info <package>" to see the dependencies for each package.

Do I understand it correct, that gcc and gcc-6 are different packages of which both require a different version of isl and thus leading to my problem? I only would need a newer version of gcc which supports GLIBCXX_3.4.21.

Thanks in advance.

Body:
I was able to solve my problem, thank you darthbith for helping me out.

Since gcc and gcc-6 are in fact two different packages, the solution was to delete gcc. After that, I had to update isl before I could install gcc-6. The commands used were:

conda uninstall gcc
conda install -c conda-forge isl=0.17.1
conda install -c salford_systems gcc-6=6.2.0


问:
How routing to home can be done in React
I am new to React.I am trying to change the route inside a function.I am used react-router-dom for routing.I used "react-router-dom": "^4.1.1".The function is,

```<code> LogIn(email, password){

            this.props.LogInAction(email, password);
            if(this.props.loginstatus == true){

                    /* Here I need to go to '/home' */

            }
</code>```

答:
You can import withRouter on page like this:

```<code>import { withRouter } from 'react-router-dom';
</code>```

And then use this to make redirection as:

```<code>if(this.props.loginstatus == true){
    this.props.history.push('/home');
}
</code>```

And don't forget to declare withRouter while exporting class as:

```<code>export default withRouter(className);
</code>```

Body:
I am new to React.I am trying to change the route inside a function.I am used react-router-dom for routing.I used "react-router-dom": "^4.1.1".The function is,

 LogIn(email, password){

            this.props.LogInAction(email, password);
            if(this.props.loginstatus == true){

                    /* Here I need to go to '/home' */

            }

Body:
You can import withRouter on page like this:

import { withRouter } from 'react-router-dom';

And then use this to make redirection as:

if(this.props.loginstatus == true){
    this.props.history.push('/home');
}

And don't forget to declare withRouter while exporting class as:

export default withRouter(className);


问:
Is there a way to reference the Java class for a Kotlin top-level function?
I want to load a resource in a top level function using Class.getResourceAsStream().

Is there any way to get a reference to the class that the top level function will be compiled into so that I can write, for example

```<code>val myThing = readFromStream(MYCLASS.getResourceAsStream(...))
</code>```

答:
As linters like detekt would flag anonymous classes as EmptyClassBlock you could also use something like

```<code>internal object Resources

fun resourceStream(name: String): InputStream {
    return Resources.javaClass.getResourceAsStream(name)
}
</code>```

Body:
I want to load a resource in a top level function using Class.getResourceAsStream().

Is there any way to get a reference to the class that the top level function will be compiled into so that I can write, for example

val myThing = readFromStream(MYCLASS.getResourceAsStream(...))

Body:
As linters like detekt would flag anonymous classes as EmptyClassBlock you could also use something like

internal object Resources

fun resourceStream(name: String): InputStream {
    return Resources.javaClass.getResourceAsStream(name)
}


问:
Retrieve all values from HashMap keys in an ArrayList Java
Good day, this is kind of confusing me now(brain freeze!) and seem to be missing something. Have an ArrayList which i populate with a HashMap. now i put in my HashMap and arraylist.

```<code> Map.put(DATE, value1);
 Map.put(VALUE, value2);

 arraylist.put(Map);
</code>```

Since am parsing a JSON, the arraylist increases in significant size. now my question is how do you get the values from both map keys in the arraylist?  i have tried this

```<code>  if(!list.isEmpty()){   // list is an ArrayList

            for(int k = 0; k < list.size(); k++){
                map = (HashMap)list.get(k);
            }

        }

        Log.d(TAG, "map size is" + map.size());

        String [] keys = new String[map.size()];
        String [] date_value = new String[map.size()];

        String [] value_values = new String[map.size()];

        int i = 0;
        Set entries = map.entrySet();
        Iterator iterator = entries.iterator();

        while(iterator.hasNext()){

            Map.Entry mapping = (Map.Entry)iterator.next();
            keys[i] = mapping.getKey().toString();
            date_value[i] = map.get(keys[i]);

            if(keys[i].equals(DATE)){
                date_value[i] = map.get(keys[i]);

            } else if(keys[i].equals(VALUE)){
                value_values[i] = map.get(keys[i]);
            }

                   i++;
                 }
</code>```

But i can't seem to get all the values. the Map size always return a value of 2, which is just the elements. how can i get all the values from the Map keys in the ArrayList? Thanks

答:
Suppose I have Hashmap with key datatype as  KeyDataType
and  value datatype as  ValueDataType

```<code>HashMap<KeyDataType,ValueDataType> list;
</code>```

Add all items you needed to it.
Now you can retrive all hashmap keys to a list by.

```<code>KeyDataType[] mKeys;
mKeys=list.keySet().toArray(new KeyDataType[list.size()]);
</code>```

So, now you got your all keys in an array mkeys[]

you can now retrieve any value by calling

```<code> list.get(mkeys[position]);
</code>```

Body:
Good day, this is kind of confusing me now(brain freeze!) and seem to be missing something. Have an ArrayList which i populate with a HashMap. now i put in my HashMap and arraylist.

 Map.put(DATE, value1);
 Map.put(VALUE, value2);

 arraylist.put(Map);

Since am parsing a JSON, the arraylist increases in significant size. now my question is how do you get the values from both map keys in the arraylist?  i have tried this

  if(!list.isEmpty()){   // list is an ArrayList

            for(int k = 0; k < list.size(); k++){
                map = (HashMap)list.get(k);
            }

        }

        Log.d(TAG, "map size is" + map.size());

        String [] keys = new String[map.size()];
        String [] date_value = new String[map.size()];

        String [] value_values = new String[map.size()];

        int i = 0;
        Set entries = map.entrySet();
        Iterator iterator = entries.iterator();

        while(iterator.hasNext()){

            Map.Entry mapping = (Map.Entry)iterator.next();
            keys[i] = mapping.getKey().toString();
            date_value[i] = map.get(keys[i]);

            if(keys[i].equals(DATE)){
                date_value[i] = map.get(keys[i]);

            } else if(keys[i].equals(VALUE)){
                value_values[i] = map.get(keys[i]);
            }

                   i++;
                 }

But i can't seem to get all the values. the Map size always return a value of 2, which is just the elements. how can i get all the values from the Map keys in the ArrayList? Thanks

Body:
Suppose I have Hashmap with key datatype as  KeyDataType
and  value datatype as  ValueDataType

HashMap<KeyDataType,ValueDataType> list;

Add all items you needed to it.
Now you can retrive all hashmap keys to a list by.

KeyDataType[] mKeys;
mKeys=list.keySet().toArray(new KeyDataType[list.size()]);

So, now you got your all keys in an array mkeys[]

you can now retrieve any value by calling

 list.get(mkeys[position]);


问:
Rails Multiple Validation
I have a model with two columns 'name' and 'size'. I am trying to validate the uniqueness of size only if name and size together doesn't exist in database.

For example.

Name = Shirt and Size = L are in database then Name = Shirt and Size = L shouldn't pass the unique validation rather Name = Pant and Size = L should pass the uniqueness.

答:
Here you can do just like that </p>

```<code>validates :name, uniqueness: { scope: :size,
message: "should be unique" }
</code>```

Title: Rails Multiple Validation

Body:
Here you can do just like that

validates :name, uniqueness: { scope: :size,
message: "should be unique" }


问:
How to set this height of collection view?

Here in "image-1" you can see that the Blue colour CollectionView1 and the red colour is CollectionView2 by default i gave the height of the CollectionView1 - 115...as it shows....but when I debug it (pic in "image2") it shows its height as 184....i need to add a left and bottom anchor since its height is not correct I cant proceed it

答:
Please check attribute of your both collection view cells and for example you can use</p>

```<code> func collectionView(collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{

        if collectionView == YourCollectionView1 {
           return CGSizeMake(collectionView.bounds.size.width/2 - 1, 196)
            }
        }else {
            return CGSizeMake(90, 90)
        }
    }
</code>```

Body:
Please check attribute of your both collection view cells and for example you can use

 func collectionView(collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{

        if collectionView == YourCollectionView1 {
           return CGSizeMake(collectionView.bounds.size.width/2 - 1, 196)
            }
        }else {
            return CGSizeMake(90, 90)
        }
    }


问:
customizing virtualTree in qooxdoo doesn't work as expected
I'm using qooxdoo to build a custom virtualTree, which works fine as expected until I open/close/reopen a node.
It's a mess then. I don't know which part I'm missing.

here's a code sample:
virtual tree

To reproduce, please open a node (for example "Dep1"). You can hover childrens and everything is fine. Now close the node and reopen it. Now icons get changed in node and node receives the hover effect, which is not the case when we initially opened it.

Am I missing something?

Regards

code below:

var data = {
 "label": "ROOT",

 "children" : [
    {
      "LDEP" : "Dep1",
      "children" : [
        {
          "CVEH" : 1,
          "LVEH" : "veh1_1"
        },
        {
          "CVEH" : 2,
          "LVEH" : "veh1_2"
        }
      ]
    },

    {
      "LDEP" : "Dep2",
      "children" : [
        {
          "CVEH" : 3,
          "LVEH" : "veh2_1"
        },
        {
          "CVEH" : 4,
          "LVEH" : "veh2_2"
        }
      ]
    },

  ]

};
var model = qx.data.marshal.Json.createModel(data, false);
var vtree = new qx.ui.tree.VirtualTree(model, "children", "children");

this.getRoot().add(vtree,
{
  left : 100,
  right : 100,
  top  : 50
});

vtree.set({
 showTopLevelOpenCloseIcons : true,
 hideRoot : true,
 backgroundColor : "gray"
});

/* label options */
vtree.setLabelOptions({
    converter : function(value, model)
    {
     if (value){
      return  "" + model.get("LDEP") + "";
     }
     else
     {
      return model.get("LVEH");
     }
    }
});

/*
 * icon options, if a dep then return a generic symbol else return
 * vehicle icon
 */
vtree.setIconPath("children");
vtree.setIconOptions({
  converter : function(value, model)
  {
   if (value){
    return "icon/22/mimetypes/text-html.png";
   }
   else
   {
    return "icon/22/mimetypes/media-image.png"
   }
  }
});

var delegate = {
    bindItem : function(controller, item, index)
    {
      controller.bindDefaultProperties(item, index);

      //set icon size to 24x24 for leaves
      var icon = item.getChildControl("icon");
      if(item.getModel().getChildren){
       //dept
       item.setBackgroundColor("gray");
      } else {
       //vehicle
       item.setBackgroundColor("white");
       icon.set({
        width  : 32,
        height  : 32,
        scale : true,
        marginTop : -4
       });
      }

      //labels, accept html
      var lbl = item.getChildControl("label");
      lbl.set({
       rich : true,
       textColor : "black"
      });

      //change color on pointerin and pointerout of vehicles
      if (!item.getModel().getChildren){
       item.addListener("pointerover", function(){
        item.getChildControl("label").fadeIn(100);
        item.setBackgroundColor("blue");
        item.getChildControl("label").setTextColor("orange");
       });

       item.addListener("pointerout", function(){
        item.setBackgroundColor("white");
        item.getChildControl("label").setTextColor("black");
       });
      }
    },

    /*
     * sorting
     */
    sorter : function(a, b){
     var A = (a.getChildren? a.get("LDEP") : a.get("LVEH")).toUpperCase(),
        B = (b.getChildren? b.get("LDEP") : b.get("LVEH")).toUpperCase();

     return A > B ? 1 : A < B ? -1 : 0;
    }
};

vtree.setDelegate(delegate);```

答:
To understand the effects you are observing, it needs understanding on how virtual widgets work in qooxdoo.

Virtual widget means that you are able do display huge amounts of data, only having a few widgets rendering the visible content. Imagine a tree with hundreds of nodes and child nodes, but you only have 10 nodes visible at one time. The virtual widget then instantiates as many real widgets as needed and re-uses those widgets to display the visible part of the tree.

The virtual tree widget, which diplays nodes an leaves of a tree, reuses the instantiated widgets by changing the model of the widget and it's appearance. This way it may happen that on user interaction, a virtual tree node is rendered by an item which formely displayed a leafe.

All this is done via the delegates bindItem member function which is called every time a real widget is re-used for a virtual item. So adding an event listener in bindItem adds subsequent more and more event listeners to a single widget tree/leaf instance, showing the effects you described.

To achieve what you want, you have to add your logic into the configureItem delegate member, which is only called once on instantiation of a tree item widget. There you have to differentiate between the item currently displaying a node or a leaf which you can simply accomplish by getting the current appearance of that item via item.getAppearance(). The result will be either virtual-tree-file for a leaf and virtual-tree-folder for a node.

The event listeners which are added for pointerover and pointerout should then add the styles needed depending on the appearance.

Note all this should better be handeled by a custom appearance theme, where you could add most styles you used based on the widgets states like hover, besides the animation for the label child control with the fading in label.

Please paste the following gist into the qooxdoo playground where I've created an example which demonstrates all the speech above:

https://gist.github.com/level420/ba4e25f98618064f91f5aa6cb6bb1124


问:
Can't slide navigation drawer
I am doing a project in the android studio, and I need a navigation drawer, I made a navigation but the problem I can't slide it left and right its block without moving.

slide problem

```<code><?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="radiofm.arabelradio.MainActivity"
    android:background="#e10716"
    >

<android.support.design.widget.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        app:menu="@menu/navigation_menu"
        android:layout_gravity="start"
        >

    </android.support.design.widget.NavigationView>

    <ImageButton
        android:id="@+id/id_play"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:scaleType="fitCenter"
        android:background="#e10716"
        android:layout_marginBottom="84dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="250dp"
        android:layout_height="100dp"
        android:layout_marginTop="55dp"
        app:srcCompat="@drawable/arabel"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>
</code>```

My java code
I am doing a project in the android studio and I need a navigation drawer, I made a navigation but the problem I can't slide it left and right its block without moving

```<code>public class MainActivity extends AppCompatActivity {

    ImageButton id_play;
    MediaPlayer mediaPlayer;
    boolean prepared = false;
    boolean started =false;
    String stream ="http://arabelfm.ice.infomaniak.ch/arabelprodcastfm.mp3";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        id_play = (ImageButton) findViewById(R.id.id_play);
        id_play.setEnabled(false);
        //id_play.setText("LOADING");
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        new PlayerTask().execute(stream);
        id_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (started){
                    started=false;
                    mediaPlayer.pause();
                    id_play.setImageResource(R.drawable.play);
                   // id_play.setText("PLAY");
                }
                else {
                    started=true;
                    mediaPlayer.start();
                    id_play.setImageResource(R.drawable.pause);

                    //id_play.setText("PAUSE");

                }

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

答:
Try adding the logic manually:</p>

```<code>toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
    drawerLayout.openDrawer(GravityCompat.START);
}
});
</code>```

Title: Can't slide navigation drawer

Body:
I am doing a project in the android studio, and I need a navigation drawer, I made a navigation but the problem I can't slide it left and right its block without moving.

slide problem

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="radiofm.arabelradio.MainActivity"
    android:background="#e10716"
    >

<android.support.design.widget.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        app:menu="@menu/navigation_menu"
        android:layout_gravity="start"
        >

    </android.support.design.widget.NavigationView>

    <ImageButton
        android:id="@+id/id_play"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:scaleType="fitCenter"
        android:background="#e10716"
        android:layout_marginBottom="84dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="250dp"
        android:layout_height="100dp"
        android:layout_marginTop="55dp"
        app:srcCompat="@drawable/arabel"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

My java code
I am doing a project in the android studio and I need a navigation drawer, I made a navigation but the problem I can't slide it left and right its block without moving

public class MainActivity extends AppCompatActivity {

    ImageButton id_play;
    MediaPlayer mediaPlayer;
    boolean prepared = false;
    boolean started =false;
    String stream ="http://arabelfm.ice.infomaniak.ch/arabelprodcastfm.mp3";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        id_play = (ImageButton) findViewById(R.id.id_play);
        id_play.setEnabled(false);
        //id_play.setText("LOADING");
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        new PlayerTask().execute(stream);
        id_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (started){
                    started=false;
                    mediaPlayer.pause();
                    id_play.setImageResource(R.drawable.play);
                   // id_play.setText("PLAY");
                }
                else {
                    started=true;
                    mediaPlayer.start();
                    id_play.setImageResource(R.drawable.pause);

                    //id_play.setText("PAUSE");

                }

            }
        });
    }

Body:
Try adding the logic manually:

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
    drawerLayout.openDrawer(GravityCompat.START);
}
});


问:
What happens in the background of array initialization in c?
Given that this is legal

```<code>uint8_t bytes[4] = { 1, 2, 3, 4 };
</code>```

And this is not:

```<code>uint8_t bytes2[4];
bytes2 = { 1, 2, 3, 4 };
</code>```

what does { 1, 2, 3, 4 } represent?

Am assuming it's neither an rvalue or an lvalue. A preprocessor code candy that expands to something?

答:
Initialization and assignment are fundamentally different things. As for the language C, you just have to accept the fact that they are distinguished, but of course, there's a technical reason it's defined this way:

In many systems, you can have a data segment in your executable file. This segment could be read/write and given an initialized array like

```<code>uint8_t foo[] = {1, 2, 3, 4}; // assume this has static storage duration
</code>```

the compiler could just decide to output this exact byte sequence directly into your executable. So there's no code at all doing an assignment, the data is already there in memory when your program starts.

OTOH, arrays cannot be assigned to (only their individual members). That's how C is defined, and it's sometimes unfortunate.

Body:
Given that this is legal

uint8_t bytes[4] = { 1, 2, 3, 4 };

And this is not:

uint8_t bytes2[4];
bytes2 = { 1, 2, 3, 4 };

what does { 1, 2, 3, 4 } represent?

Am assuming it's neither an rvalue or an lvalue. A preprocessor code candy that expands to something?

Body:
Initialization and assignment are fundamentally different things. As for the language C, you just have to accept the fact that they are distinguished, but of course, there's a technical reason it's defined this way:

In many systems, you can have a data segment in your executable file. This segment could be read/write and given an initialized array like

uint8_t foo[] = {1, 2, 3, 4}; // assume this has static storage duration

the compiler could just decide to output this exact byte sequence directly into your executable. So there's no code at all doing an assignment, the data is already there in memory when your program starts.

OTOH, arrays cannot be assigned to (only their individual members). That's how C is defined, and it's sometimes unfortunate.


问:
What are best practices for dealing with out of memory errors?
I'm wondering, what are good practices for dealing with out of memory errors.

```<code>void SomeTask()
{
   try
   {
      SomeObj obj = new SomeObj();
   }
   catch( std::bad_alloc& )
   {
      // What should be done here?
   }

   // ... more code ...
}
</code>```

I feel like silently returning is wrong because the program could be running in an indeterminate state. So, what should happen here, should I leave the program to crash, or is there a better alternative? This program runs as a service, so I can't just pop up an error message. I guess it might be possible to log something if there's enough memory left to do that. But, I'm just wondering, what do you think I should do in this kind of situation?

Thanks.

答:
The first thing that you should do is try to free up more memory. If you have to periodically scrub objects, now is the time to do it. If all goes well, you may just be able to keep running.

Failing that, you should try to save whatever needs saving to disk and die, if you need extra memory for this, make sure you grab it upfront on startup. Since continuing to run is impossible, you should just die (abort or rethrow the exception).

Body:
I'm wondering, what are good practices for dealing with out of memory errors.

void SomeTask()
{
   try
   {
      SomeObj obj = new SomeObj();
   }
   catch( std::bad_alloc& )
   {
      // What should be done here?
   }

   // ... more code ...
}

I feel like silently returning is wrong because the program could be running in an indeterminate state. So, what should happen here, should I leave the program to crash, or is there a better alternative? This program runs as a service, so I can't just pop up an error message. I guess it might be possible to log something if there's enough memory left to do that. But, I'm just wondering, what do you think I should do in this kind of situation?

Thanks.


问:
Collate child elements
For every property element of type=CHOICE, I want to collate the choice elements. So given:

```<code><property>
  <name>lookup_mode</name>
  <type>CHOICE</type>
  <defaultValue>1</defaultValue>
  <choices>
      <value>1</value>
      <value>2</value>
      <value>3</value>
  </choices>
  <choiceNames>
      <value>Challenge</value>
      <value>Pass Through</value>
      <value>Not Supported</value>
  </choiceNames>
</property>
</code>```

the output is:

```<code><property>
  <name>lookup_mode</name>
  <type>CHOICE</type>
  <defaultValue>1</defaultValue>
  <choices>
    <choice>
      <index>1</index>
      <choiceName>Challenge</choiceName>
    </choice>
    <choice>
      <index>2</index>
      <choiceName>Pass Through</choiceName>
    </choice>
    <choice>
      <index>3</index>
      <choiceName>Not Supported</choiceName>
    </choice>
  </choices>
</property>
</code>```

I tried template:

```<code><xsl:template match="propertyDescriptor[type/text()='CHOICE']">
  <xsl:copy>
    <choices>
      <xsl:for-each select="choices/value">
        <choice>
          <index><xsl:value-of select="."/></index>
          <choiceName><xsl:value-of select="../../choiceNames/value"/></choiceName>
        </choice>
      </xsl:for-each>
    </choices>
    <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
</xsl:template>
</code>```

If I use the choice as index for the loop then choiceName values are repeated for every choice, and vice versa:

```<code><property>
   <choices>
      <choice>
         <index>0</index>
         <choiceName>Challenge Pass Through Not Supported</choiceName>
      </choice>
      <choice>
         <index>1</index>
         <choiceName>Challenge Pass Through Not Supported</choiceName>
      </choice>
      <choice>
         <index>2</index>
         <choiceName>Challenge Pass Through Not Supported</choiceName>
      </choice>
   </choices>
   ...
</code>```

I'm following XSLT Jumpstarter (2015) where the author tackles similar operations in Chapter 6, Changing the Structure and order of Content. Element collation (like printer page collation) is not covered. I would think there was some stock pattern to follow?
Thanks in advance.

答:
The result you are looking for can be achieved by:

```<code><xsl:template match="property[type='CHOICE']">
    <xsl:copy>
        <xsl:copy-of select="name | type | defaultValue"/>
        <choices>
            <xsl:for-each select="choices/value">
                <xsl:variable name="i" select="position()" />
                <choice>
                    <index>
                        <xsl:value-of select="."/>
                    </index>
                    <choiceName>
                        <xsl:value-of select="../../choiceNames/value[$i]"/>
                    </choiceName>
                </choice>
            </xsl:for-each>
        </choices>
    </xsl:copy>
</xsl:template>
</code>```

The (main) reason why your attempt doesn't work is that your instruction:

```<code><xsl:value-of select="../../choiceNames/value"/>
</code>```

selects all choiceNames/value nodes and returns the string-value of either the first one (in XSLT 1.0) or all of them (in XSLT 2.0), without considering which choices/value node is the current one.

Title: Collate child elements

Body:
For every property element of type=CHOICE, I want to collate the choice elements. So given:

<property>
  <name>lookup_mode</name>
  <type>CHOICE</type>
  <defaultValue>1</defaultValue>
  <choices>
      <value>1</value>
      <value>2</value>
      <value>3</value>
  </choices>
  <choiceNames>
      <value>Challenge</value>
      <value>Pass Through</value>
      <value>Not Supported</value>
  </choiceNames>
</property>

the output is:

<property>
  <name>lookup_mode</name>
  <type>CHOICE</type>
  <defaultValue>1</defaultValue>
  <choices>
    <choice>
      <index>1</index>
      <choiceName>Challenge</choiceName>
    </choice>
    <choice>
      <index>2</index>
      <choiceName>Pass Through</choiceName>
    </choice>
    <choice>
      <index>3</index>
      <choiceName>Not Supported</choiceName>
    </choice>
  </choices>
</property>

I tried template:

<xsl:template match="propertyDescriptor[type/text()='CHOICE']">
  <xsl:copy>
    <choices>
      <xsl:for-each select="choices/value">
        <choice>
          <index><xsl:value-of select="."/></index>
          <choiceName><xsl:value-of select="../../choiceNames/value"/></choiceName>
        </choice>
      </xsl:for-each>
    </choices>
    <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
</xsl:template>

If I use the choice as index for the loop then choiceName values are repeated for every choice, and vice versa:

<property>
   <choices>
      <choice>
         <index>0</index>
         <choiceName>Challenge Pass Through Not Supported</choiceName>
      </choice>
      <choice>
         <index>1</index>
         <choiceName>Challenge Pass Through Not Supported</choiceName>
      </choice>
      <choice>
         <index>2</index>
         <choiceName>Challenge Pass Through Not Supported</choiceName>
      </choice>
   </choices>
   ...

I'm following XSLT Jumpstarter (2015) where the author tackles similar operations in Chapter 6, Changing the Structure and order of Content. Element collation (like printer page collation) is not covered. I would think there was some stock pattern to follow?
Thanks in advance.

Body:
The result you are looking for can be achieved by:

<xsl:template match="property[type='CHOICE']">
    <xsl:copy>
        <xsl:copy-of select="name | type | defaultValue"/>
        <choices>
            <xsl:for-each select="choices/value">
                <xsl:variable name="i" select="position()" />
                <choice>
                    <index>
                        <xsl:value-of select="."/>
                    </index>
                    <choiceName>
                        <xsl:value-of select="../../choiceNames/value[$i]"/>
                    </choiceName>
                </choice>
            </xsl:for-each>
        </choices>
    </xsl:copy>
</xsl:template>

The (main) reason why your attempt doesn't work is that your instruction:

<xsl:value-of select="../../choiceNames/value"/>

selects all choiceNames/value nodes and returns the string-value of either the first one (in XSLT 1.0) or all of them (in XSLT 2.0), without considering which choices/value node is the current one.


问:
How to custom switch button?
I am looking to Custom The Switch Button to becoming as following :

How to achieve this ?

答:
More info on this link: http://www.mokasocial.com/2011/07/sexily-styled-toggle-buttons-for-android/

```<code><ToggleButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/toggle_me"/>
</code>```

and the drawable will be something like:

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true"
        android:drawable="@drawable/toggle_me_on" /> <!-- checked -->
    <item android:drawable="@drawable/toggle_me_off" /> <!-- default/unchecked -->
</selector>
</code>```

Title: How to custom switch button?

Body:
More info on this link: http://www.mokasocial.com/2011/07/sexily-styled-toggle-buttons-for-android/

<ToggleButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/toggle_me"/>

and the drawable will be something like:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true"
        android:drawable="@drawable/toggle_me_on" /> <!-- checked -->
    <item android:drawable="@drawable/toggle_me_off" /> <!-- default/unchecked -->
</selector>


问:
How to get ASCII values of a string in VB.net
I want to be able so get the ASCII values of all the characters in a string.
I can get the ASCII value of a character but i cannot do it for the whole string.

My attempt:

```<code>dim input as string = console.readline()
dim value as integer = ASC(input)

'Then I am changing its value by +1 to write the input in a secret code form.
console.writeline(CHR(value+1))
</code>```

I want to be able to get the ASCII values for all characters in the string so i can change the all letters in the string +1 character in the alphabet.
Any help appreciated, thanks.

答:
```<code>Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
      System.EventArgs) Handles Button2.Click

        Dim a As Integer
        a = Asc(TextBox1.Text)
        MessageBox.Show(a)

    End Sub
End Class
</code>```

Body:
I want to be able so get the ASCII values of all the characters in a string.
I can get the ASCII value of a character but i cannot do it for the whole string.

My attempt:

dim input as string = console.readline()
dim value as integer = ASC(input)

'Then I am changing its value by +1 to write the input in a secret code form.
console.writeline(CHR(value+1))

I want to be able to get the ASCII values for all characters in the string so i can change the all letters in the string +1 character in the alphabet.
Any help appreciated, thanks.


问:
Find pixels with given RGB colors
I would like to get all coordinates from the pixels with a given RGB color in Python. Here is the code that I'm using but it doesn't work. I want to find all pixels with a yellow color.

```<code>from PIL import Image
def find_rgb(imagename, r_query, g_query, b_query):
    img = Image.open(imagename)
    rgb = img.convert('RGB')
    for x in range(507):
        for y in range(337):
            r, g, b, = rgb.getpixel((x, y))
            if r >= r_query and g >= g_query and b <= b_query:
                return (x,y)
</code>```

And how can you do it that Python only gives the coordinates if there are at least three pixels with the same color? (They mustn't be the exact same color, they can be for example 156,173,87 and 155,173,87.)

答:
```<code>from PIL import Image
def find_rgb(imagename, r_query, g_query, b_query):
    img = Image.open(imagename)
    pix = img.load()
    coordinates= []
    for x in range(img.size[0]):
        for y in range(img.size[1]):
            r, g, b = pix[x,y]
            if matching_algo(r, g, b, r_query, g_query, b_query):
                # print("{},{} contains {}-{}-{} ".format(x, y, r, g, b))
                coordinates.append((x, y))
    return(coordinates)

def matching_algo(r, g, b, r_query, g_query, b_query):
    if r == r_query and g == g_query:
        return True
    elif r == r_query and b == b_query:
        return True
    elif b == b_query and g == g_query:
        return  True
    else:
        return False

if __name__== "__main__":
    find_rgb('dead_parrot.jpg', 255, 255, 0)
</code>```

Give this a try, you can improve my matching algorithm implementation.
I removed your convert() code and used load() instead

Title: Find pixels with given RGB colors

Body:
I would like to get all coordinates from the pixels with a given RGB color in Python. Here is the code that I'm using but it doesn't work. I want to find all pixels with a yellow color.

from PIL import Image
def find_rgb(imagename, r_query, g_query, b_query):
    img = Image.open(imagename)
    rgb = img.convert('RGB')
    for x in range(507):
        for y in range(337):
            r, g, b, = rgb.getpixel((x, y))
            if r >= r_query and g >= g_query and b <= b_query:
                return (x,y)

And how can you do it that Python only gives the coordinates if there are at least three pixels with the same color? (They mustn't be the exact same color, they can be for example 156,173,87 and 155,173,87.)

Body:
from PIL import Image
def find_rgb(imagename, r_query, g_query, b_query):
    img = Image.open(imagename)
    pix = img.load()
    coordinates= []
    for x in range(img.size[0]):
        for y in range(img.size[1]):
            r, g, b = pix[x,y]
            if matching_algo(r, g, b, r_query, g_query, b_query):
                # print("{},{} contains {}-{}-{} ".format(x, y, r, g, b))
                coordinates.append((x, y))
    return(coordinates)

def matching_algo(r, g, b, r_query, g_query, b_query):
    if r == r_query and g == g_query:
        return True
    elif r == r_query and b == b_query:
        return True
    elif b == b_query and g == g_query:
        return  True
    else:
        return False

if __name__== "__main__":
    find_rgb('dead_parrot.jpg', 255, 255, 0)

Give this a try, you can improve my matching algorithm implementation.
I removed your convert() code and used load() instead


问:
Reduce Border bottom length
Hi I want to know that whether can i reduce length of border bottom. I have a div and i have given border-bottom: 2px to that div i want to reduce the length of border. Is this possible.

I have this nav-bar and i have given css to its div want to reduce length of border. How can i do that.

This is my html

```<code>               <div class="row">
        <div class="col-sm-12 col-xs-12 col-lg-12 col-md-12 welcome">
            <ul class="nav navbar-nav navbar-nav-primary">
                <li class="active">
                    <a href="#one" data-toggle="tab">
                        <i class="fa fa-map-marker" aria-hidden="true"></i> <span class="li-text">Location</span>
                    </a>
                </li>
                <li>
                    <a href="#two" data-toggle="tab">
                        <i class="fa fa-heartbeat" aria-hidden="true"></i> <span class="li-text">Heartbeats</span>
                    </a>
                </li>
                <li>
                    <a href="#three" data-toggle="tab">
                        <i class="fa fa-power-off" aria-hidden="true"></i>
                        <span class="li-text">Reboots</span>
                    </a>
                </li>
                <li>
                    <a href="#four" data-toggle="tab">
                        <i class="fa fa-compress" aria-hidden="true"></i>
                        <span class="li-text">Reconnects</span>
                    </a>
                </li>
                <li>
                    <a href="#five" data-toggle="tab">
                        <i class="fa fa-battery-full" aria-hidden="true"></i>
                        <span class="li-text">Charge</span>
                    </a>
                </li>

            </ul>

        </div>
</code>```

This is my CSS

```<code>        .welcome {
              border-bottom: 2px solid #bcbcbc;
              margin-left: 10px;
             }
</code>```

答:
You can use this for set height and width for set length</p>

```<code>.welcome{
width:1000px;
border-bottom:1px solid magenta;
height:100px;
}
</code>```

Title: Reduce Border bottom length

Body:
Hi I want to know that whether can i reduce length of border bottom. I have a div and i have given border-bottom: 2px to that div i want to reduce the length of border. Is this possible.

I have this nav-bar and i have given css to its div want to reduce length of border. How can i do that.

This is my html

                         Location

                         Heartbeats

                        Reboots

                        Reconnects

                        Charge

This is my CSS

        .welcome {
              border-bottom: 2px solid #bcbcbc;
              margin-left: 10px;
             }

Body:
You can use this for set height and width for set length

.welcome{
width:1000px;
border-bottom:1px solid magenta;
height:100px;
}


问:
filter by is_active boolean field in django
I want to have an is_active field for all the models in my application and when ever I create an api, I want to filter only the active ones and send the response. Is there a generic way to do this? As of now I am keeping a boolean field is_active and every time I retrieve the objects, I am writing a filter. below is the code :

My models.py

```<code>class Crew(models.Model):
    crew_id = models.AutoField(primary_key=True)
    crew_code = models.CharField(max_length=200, null=False, unique=True)
    crew_name = models.CharField(max_length=200, null=False)
    crew_password = models.CharField(max_length=200, null=False)
    is_active = models.BooleanField(default=True)
</code>```

My views.py :

```<code>@api_view(['GET'])
def get_crews(request):
    c = Crew.objects.filter(is_active=True)
    serializer = CrewSerializer(c, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)
</code>```

答:
You can write custom model manager:

```<code>class IsActiveManager(models.Manager):
    def get_queryset(self):
        return super(IsActiveManager, self).get_queryset().filter(is_active=True)

class Crew(models.Model):
    ...
    objects = IsActiveManager()
</code>```

Now Crew.objects.all() will return only is_active record.

Body:
I want to have an is_active field for all the models in my application and when ever I create an api, I want to filter only the active ones and send the response. Is there a generic way to do this? As of now I am keeping a boolean field is_active and every time I retrieve the objects, I am writing a filter. below is the code :

My models.py

class Crew(models.Model):
    crew_id = models.AutoField(primary_key=True)
    crew_code = models.CharField(max_length=200, null=False, unique=True)
    crew_name = models.CharField(max_length=200, null=False)
    crew_password = models.CharField(max_length=200, null=False)
    is_active = models.BooleanField(default=True)

My views.py :

@api_view(['GET'])
def get_crews(request):
    c = Crew.objects.filter(is_active=True)
    serializer = CrewSerializer(c, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)

Body:
You can write custom model manager:

class IsActiveManager(models.Manager):
    def get_queryset(self):
        return super(IsActiveManager, self).get_queryset().filter(is_active=True)

class Crew(models.Model):
    ...
    objects = IsActiveManager()

Now Crew.objects.all() will return only is_active record.


问:
How do I alter the timezone of a DateTime in Ruby?
Reading, writing, and serializing dates and times while keeping the time zone constant is becoming annoying.  I'm using Ruby (and Rails 3.0) and am trying to alter the time zone of a DateTime. (to UTC) but not the time itself.

I want this:

```<code>t = DateTime.now
t.hour
-> 4
t.offset = 0
t.hour
-> 4
t.utc?
-> true
</code>```

The closest I have come is this, but it's not intuitive.

```<code>t = DateTime.now
t.hour
-> 4
t += t.offset
t = t.utc
t.hour
-> 4
t.utc?
-> true
</code>```

Is there any better way?

答:
Using Rails 3, you're looking for DateTime.change()</p>

```<code>dt = DateTime.now
=> Mon, 20 Dec 2010 18:59:43 +0100
dt = dt.change(:offset => "+0000")
=> Mon, 20 Dec 2010 18:59:43 +0000
</code>```

Body:
Reading, writing, and serializing dates and times while keeping the time zone constant is becoming annoying.  I'm using Ruby (and Rails 3.0) and am trying to alter the time zone of a DateTime. (to UTC) but not the time itself.

I want this:

t = DateTime.now
t.hour
-> 4
t.offset = 0
t.hour
-> 4
t.utc?
-> true

The closest I have come is this, but it's not intuitive.

t = DateTime.now
t.hour
-> 4
t += t.offset
t = t.utc
t.hour
-> 4
t.utc?
-> true

Is there any better way?

Body:
Using Rails 3, you're looking for DateTime.change()

dt = DateTime.now
=> Mon, 20 Dec 2010 18:59:43 +0100
dt = dt.change(:offset => "+0000")
=> Mon, 20 Dec 2010 18:59:43 +0000


问:
Can`t sort by price correctly, although sorting by name works very well
Trying to make this small bookstore app and wanted to add option to sort books by price and name, ascending and descending. Sorting by price occurs in very strange order, and can't find the reason for that, please if some could help and explain to me, I'm pretty new in Angular. Thank you!

Here is the source code: https://github.com/EgomortIncognitus/bookstore

Here is the code from sort-by.pipe.ts:

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'sortBy'
})
export class SortByPipe implements PipeTransform {

  transform(array: Array<string>, args?: any): any {

    if (array) {

      let sortField = args[0];
      let sortDirection = args[1];
      let modifier = 1;

      if (sortDirection === 'desc') {
        modifier = -1;
      }

      array.sort((a: any, b: any) => {
        if (a[sortField] < b[sortField]) {
          return -1 * modifier;
        } else if (a[sortField] > b[sortField]) {
          return 1 * modifier;
        } else {
          return 0;
        }
      });

      return array;
    }
  }

}
</code>```

答:
You are sorting strings which will be done lexicographically.

As an example, "9" > "800000" but 9 < 800000.

Body:
Trying to make this small bookstore app and wanted to add option to sort books by price and name, ascending and descending. Sorting by price occurs in very strange order, and can't find the reason for that, please if some could help and explain to me, I'm pretty new in Angular. Thank you!

Here is the source code: https://github.com/EgomortIncognitus/bookstore

Here is the code from sort-by.pipe.ts:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'sortBy'
})
export class SortByPipe implements PipeTransform {

  transform(array: Array<string>, args?: any): any {

    if (array) {

      let sortField = args[0];
      let sortDirection = args[1];
      let modifier = 1;

      if (sortDirection === 'desc') {
        modifier = -1;
      }

      array.sort((a: any, b: any) => {
        if (a[sortField]  b[sortField]) {
          return 1 * modifier;
        } else {
          return 0;
        }
      });

      return array;
    }
  }

}


问:
Is it good that we link dao entity classes with mvc form
I am learning hibernate with spring. While implementing i am creating entity class like below

```<code>@Entity
@Table(name = "USER_DETAILS", uniqueConstraints = @UniqueConstraint(columnNames = "USER_ID"))
public class UserInfo implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "USER_KEY", unique = true, nullable = false)
    private Long userKey;

    @Column(name = "USER_ID", unique = true, nullable = false)
    private String userId;

//getters and setters
}
</code>```

And i am designing a html page to get above input from user. As per the tutorial they are creating a DTO class with same variables which are in the DAO entity class and implementing JSR303 validation after that attaching that DTO to the form like below.

```<code><sf:form action="/addUser" commandName="userDTO"
                method="post">
//input text boxes

</sf:form>
</code>```

Its difficult to understand why we need to create a same DAO Entity class again without hibernate annotations and the same variables in the name of DTO. Please share some guidelines.

Is it a best practice or is it any performance / structural  reason that we need to create DTO class for html form.

What will happen if we directly attach DAO entity class with form.

Please give some ideas / guidelines.

答:
For simple application like pet application you can use entity for web layer.
The first problems came when you add N-to-Many relation in your entity model.

Hibernate use interfaces list Set , but with it's own implementation like PersistentSet that has keep information about hibernate session, also you web part /level should has hibernate jar to work with this implementation of set :)

Lazy loading. if you close hibenate session you will get LazyInitializationException , you avoid this you should keep your hib session open till you not finish work with entity in web level

Body:
I am learning hibernate with spring. While implementing i am creating entity class like below

@Entity
@Table(name = "USER_DETAILS", uniqueConstraints = @UniqueConstraint(columnNames = "USER_ID"))
public class UserInfo implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "USER_KEY", unique = true, nullable = false)
    private Long userKey;

    @Column(name = "USER_ID", unique = true, nullable = false)
    private String userId;

//getters and setters
}

And i am designing a html page to get above input from user. As per the tutorial they are creating a DTO class with same variables which are in the DAO entity class and implementing JSR303 validation after that attaching that DTO to the form like below.

<sf:form action="/addUser" commandName="userDTO"
                method="post">
//input text boxes

</sf:form>

Its difficult to understand why we need to create a same DAO Entity class again without hibernate annotations and the same variables in the name of DTO. Please share some guidelines.

Is it a best practice or is it any performance / structural  reason that we need to create DTO class for html form.

What will happen if we directly attach DAO entity class with form.

Please give some ideas / guidelines.


问:
How can I make the background of UICollection view as transparent without making the cells in it transparent in Swift
I have a collection view and of course I also have the cells in it. If in the property inspector I change the alpha of collection view to 0, the cells in it also become transparent. Is there a way to make the background transparent of the collection view only so the image behind it is visible? </p>

答:
using in Swift 3:</p>

```<code>collectionView.backgroundColor = UIColor.clear.withAlphaComponent(0)
</code>```

Body:
using in Swift 3:

collectionView.backgroundColor = UIColor.clear.withAlphaComponent(0)


问:
Exclude fields serializing using Groovy JsonOutput
How to exclude specific fields from being serialized when using the JsonOutput.toJson(..) in groovy?

Given class:

```<code>class Dummy {
  String f1
  transient String f2
}
</code>```

Code:

```<code>// synthetic getter and setter should be preserved
Dummy dummy = new Dummy(f1: "hello", f2: "world")
String json = JsonOutput. toJson(dummy )
println json
</code>```

Will result in:

```<code>{"f1":"hello", "f2":"world"}
</code>```

Should result in:

```<code>{"f1":"hello"}
</code>```

答:
You can also make the f2 property explicitly private

```<code>class Dummy {

String f1
private String f2

}
</code>```

Update:
I don't believe there is a "clear" way of doing this - correct me if I'm wrong. The only solution I can think of is defining a getter method with an unusual naming, ex:

```<code>class Dummy {
String f1
private String f2
def f2Value() { return f2 }
}
</code>```

This way the field value would be accessible, but will be ignored by JsonOutput.

Body:
How to exclude specific fields from being serialized when using the JsonOutput.toJson(..) in groovy?

Given class:

class Dummy {
  String f1
  transient String f2
}

Code:

// synthetic getter and setter should be preserved
Dummy dummy = new Dummy(f1: "hello", f2: "world")
String json = JsonOutput. toJson(dummy )
println json

Will result in:

{"f1":"hello", "f2":"world"}

Should result in:

{"f1":"hello"}

Body:
You can also make the f2 property explicitly private

class Dummy {

String f1
private String f2

}

Update:
I don't believe there is a "clear" way of doing this - correct me if I'm wrong. The only solution I can think of is defining a getter method with an unusual naming, ex:

class Dummy {
String f1
private String f2
def f2Value() { return f2 }
}

This way the field value would be accessible, but will be ignored by JsonOutput.


问:
Dynamically add custom component to loaded DOM (aurelia.js)
Is it possible to add a custom component to the DOM once it has already been loaded?

E.g. When clicking a button

Template

```<code><template>
    <button click.delegate="add_component()"> Press me </button>
</template>
</code>```

Viewmodel

```<code>@inject(Element)

export class App {

  constructor(element) {
      this.element = element;
  }

  function add_component() {
     var component = document.createElement('<customElement></customElement>');
     this.element.appendChild(component);
  }
}
</code>```

答:
There's more than one way to do that, actually. Depending on your actual need, you might get away with using the compose element if your need is to dynamically switch views.

Another approach is to use Aurelia's View Compiler to compile the markup into a view, then create a View Slot (there's some discussion on the topic in this aurelia-templating GitHub issue). With View Slots, it should be possible to dynamically add multiple views one after another.

However, if your actual need is anything close to your example, you can simply get away with something like this:

```<code><template>
    <button click.delegate="add_component()"> Press me </button>
    <custom-element if.bind="hasCustomElement"></custom-element>
</template>
</code>```

in the view and this:

```<code>export class App {
  @observable hasCustomElement = false;

  function add_component() {
      this.hasCustomElement = true;
  }
}
</code>```

in the view model. The custom element will only be appended to the dom when the if.bind condition becomes true and removed if it becomes false.

Body:
Is it possible to add a custom component to the DOM once it has already been loaded?

E.g. When clicking a button

Template

<template>
    <button click.delegate="add_component()"> Press me </button>
</template>

Viewmodel

@inject(Element)

export class App {

  constructor(element) {
      this.element = element;
  }

  function add_component() {
     var component = document.createElement('<customElement></customElement>');
     this.element.appendChild(component);
  }
}

Body:
There's more than one way to do that, actually. Depending on your actual need, you might get away with using the compose element if your need is to dynamically switch views.

Another approach is to use Aurelia's View Compiler to compile the markup into a view, then create a View Slot (there's some discussion on the topic in this aurelia-templating GitHub issue). With View Slots, it should be possible to dynamically add multiple views one after another.

However, if your actual need is anything close to your example, you can simply get away with something like this:

<template>
    <button click.delegate="add_component()"> Press me </button>
    <custom-element if.bind="hasCustomElement"></custom-element>
</template>

in the view and this:

export class App {
  @observable hasCustomElement = false;

  function add_component() {
      this.hasCustomElement = true;
  }
}

in the view model. The custom element will only be appended to the dom when the if.bind condition becomes true and removed if it becomes false.


问:
How to get the callback value of function that is inside an another function?
I have two functions updateSpeaker(),uploadSpeakerImageAdd() I want to upload the image to the webapi and get the filename as callback and i want to post the filename within the  updateSpeaker() .

updateSpeaker()

```<code>   updateSpeaker(menuItem)
        {

          this.uploadSpeakerImageAdd();
          console.log(this.imagename)
        let update_event_speakers_body={
                '_id':this.menuItem.id,
                'name':this.menuItem.name,
                'matter':this.menuItem.matter,
                'image':this.imagename,       //file name getting from the uploadSpeakerImageAdd().
                'session':this.menuItem.session,
                'link':this.menuItem.link,
                'event_id':this.EventId };
        this.getPostMenuService.doUpdateSpeakers(update_event_speakers_body).subscribe(
                    data => {
                    console.log(data);
                   },err => {
                    console.log("error")
                  });

        }
</code>```

uploadSpeakerImageAdd()

```<code> uploadSpeakerImageAdd() {
    let inputEl: HTMLInputElement = this.inputEl.nativeElement;
    let fileCount: number = inputEl.files.length;
    console.log(fileCount);
    let formData = new FormData();
    if (fileCount > 0) { // a file was selected
        for (let i = 0; i < fileCount; i++) {
            formData.append('file[]', inputEl.files.item(i));
        }

        this.getPostMenuService.doPostImage( formData).subscribe(data => {

                        this.imagename=data.file;
                       console.log( this.imagename);

                   },
            err => {
             console.log("error")

          });
     }

  }
</code>```

This code is working but only getting the file name after the execution of updateSpeaker()

答:
You need to pass a function as argument to uploadSpeakerImageAdd()

```<code>updateSpeaker(menuItem){
    this.uploadSpeakerImageAdd(function(imageName){
        // You get file name here so create the body object and do Post call.
    });
}
</code>```

You will be passing the anonymous function as callback to uploadSpeakerImageAdd function.

```<code>uploadSpeakerImageAdd(callback) {
    // perform all the logic before post call

    this.getPostMenuService.doPostImage( formData).subscribe(data => {
            // Pass the image name to callback
            callback(data.file);
        },
        err => {
         console.log("error")
      });
</code>```

Using Reactive Programming

If you like to do the same using reactive programming , it will be like this:

```<code>updateSpeaker(menuItem){
    this.uploadSpeakerImageAdd()
        .subscribe(file => {
             // you get the file object, create the body and do Post call
        });
}
</code>```

Inside uploadSpeakerImageAdd method, instead of subscribing , you just return the observable:

```<code>uploadSpeakerImageAdd() {
    // perform all the logic before post call
    return this.getPostMenuService.doPostImage( formData);
}
</code>```

Body:
I have two functions updateSpeaker(),uploadSpeakerImageAdd() I want to upload the image to the webapi and get the filename as callback and i want to post the filename within the  updateSpeaker() .

updateSpeaker()

   updateSpeaker(menuItem)
        {

          this.uploadSpeakerImageAdd();
          console.log(this.imagename)
        let update_event_speakers_body={
                '_id':this.menuItem.id,
                'name':this.menuItem.name,
                'matter':this.menuItem.matter,
                'image':this.imagename,       //file name getting from the uploadSpeakerImageAdd().
                'session':this.menuItem.session,
                'link':this.menuItem.link,
                'event_id':this.EventId };
        this.getPostMenuService.doUpdateSpeakers(update_event_speakers_body).subscribe(
                    data => {
                    console.log(data);
                   },err => {
                    console.log("error")
                  });

        }

uploadSpeakerImageAdd()

 uploadSpeakerImageAdd() {
    let inputEl: HTMLInputElement = this.inputEl.nativeElement;
    let fileCount: number = inputEl.files.length;
    console.log(fileCount);
    let formData = new FormData();
    if (fileCount > 0) { // a file was selected
        for (let i = 0; i < fileCount; i++) {
            formData.append('file[]', inputEl.files.item(i));
        }

        this.getPostMenuService.doPostImage( formData).subscribe(data => {

                        this.imagename=data.file;
                       console.log( this.imagename);

                   },
            err => {
             console.log("error")

          });
     }

  }

This code is working but only getting the file name after the execution of updateSpeaker()

Body:
You need to pass a function as argument to uploadSpeakerImageAdd()

updateSpeaker(menuItem){
    this.uploadSpeakerImageAdd(function(imageName){
        // You get file name here so create the body object and do Post call.
    });
}

You will be passing the anonymous function as callback to uploadSpeakerImageAdd function.

uploadSpeakerImageAdd(callback) {
    // perform all the logic before post call

    this.getPostMenuService.doPostImage( formData).subscribe(data => {
            // Pass the image name to callback
            callback(data.file);
        },
        err => {
         console.log("error")
      });

Using Reactive Programming

If you like to do the same using reactive programming , it will be like this:

updateSpeaker(menuItem){
    this.uploadSpeakerImageAdd()
        .subscribe(file => {
             // you get the file object, create the body and do Post call
        });
}

Inside uploadSpeakerImageAdd method, instead of subscribing , you just return the observable:

uploadSpeakerImageAdd() {
    // perform all the logic before post call
    return this.getPostMenuService.doPostImage( formData);
}


问:
Toast message not shown on poor internet speed
I am facing some weird issue. I am sign in user in my app but before that i check for internet connection. For that i am Toasting message saying wait while we are verifying your details. This all works fine but when network is poor it does not toast any message and it takes time to sign in.

This is my code

```<code>   @Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.btn_google_signin:
            showToast(getString(R.string.signing_in_wait_text));   // This message is not shown on poor network
            overLay.setVisibility(View.VISIBLE);
            if (AppUtil.isNetAvailable(this)) {
                Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
                startActivityForResult(intent, REQUEST_CODE);
            } else {
                showToast(getString(R.string.internet_connection_down_or_poor));
                overLay.setVisibility(View.GONE);
            }
            break;
    }
}

 private void showToast(String msg) {
    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
</code>```

overlay is my loading view to notify that he is signing in app. And below is my isNetAvailable() method

```<code>public static boolean isNetAvailable(final Context context) {

    boolean isInternetWorking = false;
    try {
        isInternetWorking = (boolean) new InternetConnectionTest(context).execute().get();
    } catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        return isInternetWorking;
    }
}
</code>```

InternetConnectionTest is asyntask which check for internet. This is how i am checking for internet

```<code>    private static class InternetConnectionTest extends AsyncTask {
    Context context;

    InternetConnectionTest(Context context) {
        this.context = context;
    }

    @Override
    protected Boolean doInBackground(Object[] objects) {

        Boolean success = false;
        try {
            URL url = new URL("https://google.com");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(10000);
            connection.connect();
            success = connection.getResponseCode() == 200;
        } catch (Exception e) {
            e.printStackTrace();

        }
        finally {
            return success;
        }
    }
</code>```

Everything works fine when internet is speed is good. And when my device is not connected with internet it shows message for internet is down. But problem comes when my internet speed is very low. It takes some time to login but does not show toast message. Please help

答:
when the net is slow, it means that the connection is more than timeout you set,
so you can just add you your toast method in the catch block of your doInBackground mothod, I think it will work!</p>

Body:
I am facing some weird issue. I am sign in user in my app but before that i check for internet connection. For that i am Toasting message saying wait while we are verifying your details. This all works fine but when network is poor it does not toast any message and it takes time to sign in.

This is my code

   @Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.btn_google_signin:
            showToast(getString(R.string.signing_in_wait_text));   // This message is not shown on poor network
            overLay.setVisibility(View.VISIBLE);
            if (AppUtil.isNetAvailable(this)) {
                Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
                startActivityForResult(intent, REQUEST_CODE);
            } else {
                showToast(getString(R.string.internet_connection_down_or_poor));
                overLay.setVisibility(View.GONE);
            }
            break;
    }
}

 private void showToast(String msg) {
    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}

overlay is my loading view to notify that he is signing in app. And below is my isNetAvailable() method

public static boolean isNetAvailable(final Context context) {

    boolean isInternetWorking = false;
    try {
        isInternetWorking = (boolean) new InternetConnectionTest(context).execute().get();
    } catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        return isInternetWorking;
    }
}

InternetConnectionTest is asyntask which check for internet. This is how i am checking for internet

    private static class InternetConnectionTest extends AsyncTask {
    Context context;

    InternetConnectionTest(Context context) {
        this.context = context;
    }

    @Override
    protected Boolean doInBackground(Object[] objects) {

        Boolean success = false;
        try {
            URL url = new URL("https://google.com");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(10000);
            connection.connect();
            success = connection.getResponseCode() == 200;
        } catch (Exception e) {
            e.printStackTrace();

        }
        finally {
            return success;
        }
    }

Everything works fine when internet is speed is good. And when my device is not connected with internet it shows message for internet is down. But problem comes when my internet speed is very low. It takes some time to login but does not show toast message. Please help