问:
Removing duplicates from a large table with NULL columns that also need to be taken into account
I am interested in removing duplicates from a very large table (40+ million records, 3+ GB in size), that also has to count NULL columns when determining duplicates.   5.5.56-MariaDB, tables are in InnoDB format.

The problem I'm running into is that some of the recommended methods will not work when it comes to NULL field comparison.    For example, I have a table that has about a dozen columns, many of which can contain NULL values, and I want NULLs treated as any other value, in that if a row has the same NULL values in the same columns, it's considered a dupe.

The technique below does NOT work:

```<code>create table tmp like mytable;
alter table tmp ADD UNIQUE INDEX(field1,field2, field3,...);
insert IGNORE into tmp (select * from mytable);
</code>```

At this point, tmp should have all dupes removed, but NULL columns are ignored in the Unique index, so it doesn't work.  If it did work, then I could rename the tables, or truncate the original table and copy over (assuming I wanted to preserve a primary key in the original table).

What is the most efficient way of deleting dupes in large files when dealing with NULL columns that should also be taken into consideration?

Additional notes:   I have a field called "recno" that is Auto Increment that needs to be ignored.

答:
Why not just do this?

```<code>create table tmp as
    select distinct t.*
    from mytable t;
</code>```

EDIT:

If you want all the fields with the minimum of the first:

```<code>create table tmp as
    select min(id), field1, field2, . . .
    from mytable t
    group by field1, field2, . . .
</code>```

Body:
I am interested in removing duplicates from a very large table (40+ million records, 3+ GB in size), that also has to count NULL columns when determining duplicates.   5.5.56-MariaDB, tables are in InnoDB format.

The problem I'm running into is that some of the recommended methods will not work when it comes to NULL field comparison.    For example, I have a table that has about a dozen columns, many of which can contain NULL values, and I want NULLs treated as any other value, in that if a row has the same NULL values in the same columns, it's considered a dupe.

The technique below does NOT work:

create table tmp like mytable;
alter table tmp ADD UNIQUE INDEX(field1,field2, field3,...);
insert IGNORE into tmp (select * from mytable);

At this point, tmp should have all dupes removed, but NULL columns are ignored in the Unique index, so it doesn't work.  If it did work, then I could rename the tables, or truncate the original table and copy over (assuming I wanted to preserve a primary key in the original table).

What is the most efficient way of deleting dupes in large files when dealing with NULL columns that should also be taken into consideration?

Additional notes:   I have a field called "recno" that is Auto Increment that needs to be ignored.

Body:
Why not just do this?

create table tmp as
    select distinct t.*
    from mytable t;

EDIT:

If you want all the fields with the minimum of the first:

create table tmp as
    select min(id), field1, field2, . . .
    from mytable t
    group by field1, field2, . . .


来源: stackexchange

问:
reg expression replace not replacing space-dash-space
I am trying to strip out any non-alphanumeric characters and also replace any whitespace with an underscore.

myString = myString.replace(/[^a-zA-Z 0-9]+/g, '').replace(" ", "_");

This almost it, but it still fails in one case:

```<code>12th Madison - 100
</code>```

Becomes

```<code>12th_Madison  100
</code>```

What I would like is this:

```<code>12th_Madison_100
</code>```

答:
The second replace method only replaces the first occurrence of white space since you passed a string as pattern, see the docs here; If you want to replace globally, you can use regex /\s+/g or /\s/g depending on if you want to collapse consecutive white spaces:

let myString = "12th Madison - 100"

myString = myString.replace(/[^a-zA-Z 0-9]+/g, '').replace(/\s+/g, "_");

console.log(myString)```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to strip out any non-alphanumeric characters and also replace any whitespace with an underscore.

myString = myString.replace(/[^a-zA-Z 0-9]+/g, '').replace(" ", "_");

This almost it, but it still fails in one case:

12th Madison - 100

Becomes

12th_Madison  100

What I would like is this:

12th_Madison_100


问:
Missing Token when creating Twilio Subaccount
How do you get a new Twilio Subaccount Token via PHP REST API?

Twilio Rest Subaccount Docs

I'm moving a Twilio number to a Subaccount vis PHP REST API.

I was able to create the subaccount and move the number to the new subaccount.

But then when I went to test the number, realized that even thru the Twilio documents say to use the Subaccount's Token, nowhere in that section does it should you how to get the token, nor is it returned during the creation of the subaccount.

To verify that my code was ok, I was able to login thru their website and find the token there and verify that it worked. But we need to make this an automated process thru the API.

Does anyone know how to get the subaccount token after you create it?

答:
I have figured out what I was doing wrong.

```<code>$subAccount->auth_token;
</code>```

Should have been:

```<code>$subAccount->authToken
</code>```

Here is the working code:

```<code>$client = new Client($masterSID, $masterToken);
$subAccount = $client->api->accounts->create(array(
        'FriendlyName' => 'NewSubAccount'
));
$subAccountSID   = $subAccount->sid;
$subAccountToken = $subAccount->authToken;
</code>```

Body:
I have figured out what I was doing wrong.

$subAccount->auth_token;

Should have been:

$subAccount->authToken

Here is the working code:

$client = new Client($masterSID, $masterToken);
$subAccount = $client->api->accounts->create(array(
        'FriendlyName' => 'NewSubAccount'
));
$subAccountSID   = $subAccount->sid;
$subAccountToken = $subAccount->authToken;


问:
What is the fastest sorting algorithm for a small number of integers?
I am wondering what the fastest algorithm would be for this.  I have 8 integers between 0 and 3000 and I need to sort them.  Although there are only 8 integers, this operation will be performed millions of times.</p>

答:
A good source for comparing sorting algos is http://www.sorting-algorithms.com/.
Note that even the initial order status affect the results. But anyway for 8 integers even a plain bubble sort should do the job.</p>

ContentLicense: CC BY-SA 2.5


问:
Switch between Create and Edit view
I have a viewcontroller which have the function of creating an object, let s say, a calendar event.

The thing is that I will have another viewController which will havbe the function of editing the calendar object.

They have the exactly same UI, same number of fields, labesl and ect, except the fact that nav bar is different (Edit button vs Create Button)

My usual way of dealing with such situation is that I use this one viewController as both edit and create viewController.

Then, before I call the viewController, I pass a state to tell the viewController if it is supposed to be in Edit or Create Mode.

The problem here is that, I find the viewController to be HUGE and there is too much logic in the viewController to distinguish the create and edit function.

Is tehre a better way in dealing with such situation?

答:
Let's see,

Option 1 Move your UI into a Single UIView

```<code> final class ParentView: UIView {
    @IBOutlet private weak var titleLabel:UILabel?
    var view: UIView! //<-- any object from your UI should be a subview to this view
    var didPressButton:(()-> Void)? = nil
      /*
         use delegates or closure just like didPressButtons,
         to pass actions or input value from your any actions from the user

        Important: think of reference cycle and stay away from them lol
      */

      @IBAction private func didPressButton(sender:UIButton) {
          didPressButton?()
     }

     /*
         if you wish to set UI from data, you can do the following:

     */
     public func setTitleLableWith(string:String) {
        titleLabel?.text = string
     }

     deinit {
         titleLabel = nil
     }
   }
</code>```

Option 2 Think of OOP

Create your BaseViewController with all your UI and methods, then hide or override any methods you'd like from any Derived Class

The choice is yours, but I like the first option. :) Happy Hunting

Title: Switch between Create and Edit view

Body:
Let's see,

Option 1 Move your UI into a Single UIView

 final class ParentView: UIView {
    @IBOutlet private weak var titleLabel:UILabel?
    var view: UIView! //<-- any object from your UI should be a subview to this view
    var didPressButton:(()-> Void)? = nil
      /*
         use delegates or closure just like didPressButtons,
         to pass actions or input value from your any actions from the user

        Important: think of reference cycle and stay away from them lol
      */

      @IBAction private func didPressButton(sender:UIButton) {
          didPressButton?()
     }

     /*
         if you wish to set UI from data, you can do the following:

     */
     public func setTitleLableWith(string:String) {
        titleLabel?.text = string
     }

     deinit {
         titleLabel = nil
     }
   }

Option 2 Think of OOP

Create your BaseViewController with all your UI and methods, then hide or override any methods you'd like from any Derived Class

The choice is yours, but I like the first option. :) Happy Hunting


问:
Find Max Line Count for Unity UI.Text
I'm trying to determine the max line count of a UI.Text with VerticalOverflow set to truncate so that the line count can be used later. So far I came up this code which obviously is rather unpractical and perhaps even dangerous:

```<code>/// <summary>
///     Returns the max visible line count of a UI.Text component. The text's vertical
///     overflow must be set to truncate or this method will return 0.
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static int GetMaxLineCount(Text text)
{
    if (text == null || text.verticalOverflow != VerticalWrapMode.Truncate) return 0;
    var textBackup = text.text;
    var lineCount = 0;
    text.text = "";
    while (true)
    {
        text.text += "\n";
        Canvas.ForceUpdateCanvases();
        var nextLineCount = text.cachedTextGenerator.lineCount;
        if (lineCount == nextLineCount) break;
        lineCount = nextLineCount;
    }
    text.text = textBackup;
    return lineCount;
}
</code>```

Is there any better way to (pre)determine the max line count of a UI.Text component (before text is truncated at the bottom)?

答:
Thanks to @Neven for pointing me in the right direction! TextGenerator can be used to count the max lines in the background. The advantage is that Canvas.ForceUpdateCanvases() doesn't need to be called anymore and the original Text won't be changed. It still needs a loop to figure out the max lines but it's far better than my first approach ...

```<code>public static int GetMaxLineCount(Text text)
{
    var textGenerator = new TextGenerator();
    var generationSettings = text.GetGenerationSettings(text.rectTransform.rect.size);
    var lineCount = 0;
    var s = new StringBuilder();
    while (true)
    {
        s.Append("\n");
        textGenerator.Populate(s.ToString(), generationSettings);
        var nextLineCount = textGenerator.lineCount;
        if (lineCount == nextLineCount) break;
        lineCount = nextLineCount;
    }
    return lineCount;
}
</code>```

Title: Find Max Line Count for Unity UI.Text

Body:
I'm trying to determine the max line count of a UI.Text with VerticalOverflow set to truncate so that the line count can be used later. So far I came up this code which obviously is rather unpractical and perhaps even dangerous:

///
///     Returns the max visible line count of a UI.Text component. The text's vertical
///     overflow must be set to truncate or this method will return 0.
///
/// <param name="text"></param>
/// <returns></returns>
public static int GetMaxLineCount(Text text)
{
    if (text == null || text.verticalOverflow != VerticalWrapMode.Truncate) return 0;
    var textBackup = text.text;
    var lineCount = 0;
    text.text = "";
    while (true)
    {
        text.text += "\n";
        Canvas.ForceUpdateCanvases();
        var nextLineCount = text.cachedTextGenerator.lineCount;
        if (lineCount == nextLineCount) break;
        lineCount = nextLineCount;
    }
    text.text = textBackup;
    return lineCount;
}

Is there any better way to (pre)determine the max line count of a UI.Text component (before text is truncated at the bottom)?

Body:
Thanks to @Neven for pointing me in the right direction! TextGenerator can be used to count the max lines in the background. The advantage is that Canvas.ForceUpdateCanvases() doesn't need to be called anymore and the original Text won't be changed. It still needs a loop to figure out the max lines but it's far better than my first approach ...

public static int GetMaxLineCount(Text text)
{
    var textGenerator = new TextGenerator();
    var generationSettings = text.GetGenerationSettings(text.rectTransform.rect.size);
    var lineCount = 0;
    var s = new StringBuilder();
    while (true)
    {
        s.Append("\n");
        textGenerator.Populate(s.ToString(), generationSettings);
        var nextLineCount = textGenerator.lineCount;
        if (lineCount == nextLineCount) break;
        lineCount = nextLineCount;
    }
    return lineCount;
}


问:
Custom view from NSWindowController Cocoa
I have an application with two windows, the main window opens the second window that is a NSWindowController and in its xib file there is a custom view, is there any way to draw in this custom view from NSWindowController?

thanks

答:
Override - (void) drawRect:(NSRect) dirtyRect in your custom NSView to do the drawing.

If you need to inform this drawRect method from your (custom) NSWindowController, you can use delegate or data source patterns by setting an outlet from the view to the NSWindowController.


问:
Unable to join to domain hosted on Azure VM
So I've created a VM Win Server 2016 on Azure. I've created a VPN connection between Azure VM (Which is AD DC) and a test windows machine. I can ping AD IP (but not domain, only IP), RDP into machine etc.. however when I try to join domain it's not recognized. So it's probably DNS issue on Azure but I've been unable to resolve it? What to do? How to proceed? The idea is to be able to connect remote machines via Point to Site VPN to AD DC on Azure.
Thanks</p>

答:
I've created a VPN connection between Azure VM (Which is AD DC) and a
  test windows machine.

Could you please tell me which kind VPN do you deployed?

If you select S2S VPN, we can change the test windows machine's DNS to Azure VM's private IP address, then try to ping the domain name, if we can ping it, we can join this test vm to the AD DC.

If your VPN is P2S, we should change the test windows machine's DNS to the Azure VM P2S virtual IP address(get from p2s), then try to ping the domain name, and join to it.


问:
Xamarin.Forms: Is it possible to dynamically add rows to a grid without the ViewModel calling into the VIew?
On a page where I am displaying a receipt to a user, I have a section which lists the subtotal, any taxes, and the total. Since the taxes applicable vary by region and based on the products being sold, the number of rows in this section will vary. For example, here are 3 separate orders, one with GST and PST, one with just GST, and one with neither:

I've accomplished this by putting just the SubTotal in the grid in XAML, and adding the rest in the code-behind in a method I call from the ViewModel. However, I'd really like to avoid doing it this way, so I'm wondering if there is an approach to accomplishing this which doesn't require having the ViewModel know about the View.

A ListView is not suitable here for a number of reasons:

These controls are inside of a ScrollView, and having a ListView inside of a ScrollView causes all sorts of weird problems.

I would like to keep the columns as narrow as their widest element. This is possible with a Grid, but a ListView would take up the entire width of its parent no matter what.

I neither need nor want for my rows to be selectable

So is there a way I can do this without the ViewModel knowing about the View and without resorting to using a ListView?

答:
Before:

```<code>public class ReceiptPageModel : PageModelBase
{
    private Receipt _receipt;
    public Receipt Receipt
    {
        get => _receipt;
        private set => Set(ref _receipt, value);
    }

    public override void Init(object initData)
    {
        Receipt = (Receipt) initData;
        ((ReceiptPage) CurrentPage).AddTaxes(Receipt);
    }
}
</code>```

After:

```<code>public class ReceiptPageModel : PageModelBase
{
    private Receipt _receipt;
    public Receipt Receipt
    {
        get => _receipt;
        private set => Set(ref _receipt, value);
    }

    public override void Init(object initData)
    {
        Receipt = (Receipt) initData;
    }
}

public partial class ReceiptPage : FreshBaseContentPage
{
    public ReceiptPage()
    {
        InitializeComponent();
        BindingContextChanged += HandlePageModelAdded;
    }

    private void HandlePageModelAdded(object sender, EventArgs e)
    {
        var pageModel = (ReceiptPageModel)BindingContext;
        if (pageModel.Receipt != null)
        {
            AddTaxes(pageModel.Receipt);
        }
        else
        {
            pageModel.PropertyChanged += (s, args) =>
            {
                if (args.PropertyName == nameof(pageModel.Receipt))
                    AddTaxes(pageModel.Receipt);
            };
        }
    }

    private void AddTaxes(Receipt receipt)
    {
        ...
    }
}
</code>```

Body:
Before:

public class ReceiptPageModel : PageModelBase
{
    private Receipt _receipt;
    public Receipt Receipt
    {
        get => _receipt;
        private set => Set(ref _receipt, value);
    }

    public override void Init(object initData)
    {
        Receipt = (Receipt) initData;
        ((ReceiptPage) CurrentPage).AddTaxes(Receipt);
    }
}

After:

public class ReceiptPageModel : PageModelBase
{
    private Receipt _receipt;
    public Receipt Receipt
    {
        get => _receipt;
        private set => Set(ref _receipt, value);
    }

    public override void Init(object initData)
    {
        Receipt = (Receipt) initData;
    }
}

public partial class ReceiptPage : FreshBaseContentPage
{
    public ReceiptPage()
    {
        InitializeComponent();
        BindingContextChanged += HandlePageModelAdded;
    }

    private void HandlePageModelAdded(object sender, EventArgs e)
    {
        var pageModel = (ReceiptPageModel)BindingContext;
        if (pageModel.Receipt != null)
        {
            AddTaxes(pageModel.Receipt);
        }
        else
        {
            pageModel.PropertyChanged += (s, args) =>
            {
                if (args.PropertyName == nameof(pageModel.Receipt))
                    AddTaxes(pageModel.Receipt);
            };
        }
    }

    private void AddTaxes(Receipt receipt)
    {
        ...
    }
}


问:
Images set with background-image don't show in iOS
I have this simple html that uses a tiny bit of bootstrap:

```<code><div id="A" class="col-4">
    <div class="img" style="background-image: url(/images/image.jpg);">
</div>
<div id="B" class="col-8">
    *some content*
</div>
</code>```

And its corresponding CSS:

```<code>.img { width: 100%; height: 100%; }
</code>```

Everything is in this pen : https://codepen.io/anon/pen/EbBGQw

The image correctly displays on the entire height of the parent div on either Chrome or Firefox, either Windows or Android :

However, on iOS devices (tested on iPhone and iPad recent browsers), the images don't show up :

I've done some digging and cleared some potential culprits :

I'm not using position: fixed;

My images aren't too large

I'm not using the background shorthand

What I have found, however, is that entering any text inside the "img" div will make the background-image appear behind the text. The image still won't cover the entire div, but it does appear.

Why is Safari not showing the image properly ? What is the best way to deal with the issue and have the image properly cover its entire div ?

答:
When you set the height to 100% :
The height will only be as large as what is inside the element.
If there is nothing inside, the height will be 0.
If there is a paragraph (as shown here), the height will be as large as the paragraph. I suggest using either pixels, rems or ems instead.

The way you wrote your image style background did not work in chrome either. I put it in the img class instead and it worked.

If you don't want to add the background image to your img class, you could do this instead:

```<code><div class="img" style="background-image: url('image.jpg')"><p>Testing</p></div>
</code>```

.img {
  width: 100%;
  height: 100%;
  background-image: url("image.jpg");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="img"><p>Testing</p></div></code>```

Body:
I have this simple html that uses a tiny bit of bootstrap:

    *some content*

And its corresponding CSS:

.img { width: 100%; height: 100%; }

Everything is in this pen : https://codepen.io/anon/pen/EbBGQw

The image correctly displays on the entire height of the parent div on either Chrome or Firefox, either Windows or Android :

However, on iOS devices (tested on iPhone and iPad recent browsers), the images don't show up :

I've done some digging and cleared some potential culprits :

I'm not using position: fixed;

My images aren't too large

I'm not using the background shorthand

What I have found, however, is that entering any text inside the "img" div will make the background-image appear behind the text. The image still won't cover the entire div, but it does appear.

Why is Safari not showing the image properly ? What is the best way to deal with the issue and have the image properly cover its entire div ?

Body:
When you set the height to 100% :
The height will only be as large as what is inside the element.
If there is nothing inside, the height will be 0.
If there is a paragraph (as shown here), the height will be as large as the paragraph. I suggest using either pixels, rems or ems instead.

The way you wrote your image style background did not work in chrome either. I put it in the img class instead and it worked.

If you don't want to add the background image to your img class, you could do this instead:

<div class="img" style="background-image: url('image.jpg')"><p>Testing</p></div>

.img {
  width: 100%;
  height: 100%;
  background-image: url("image.jpg");
}

<div class="img"><p>Testing</p></div>


问:
Implementing Local Notifications in Xamarin.Forms using Xam.Plugins.Notifier
i have implemented Local Notifications in Xamarin.Forms using Xam.Plugins.Notifier. I have added the Nuget Package in PCL, iOS and Android.
below code is displaying the notification. i wrote the below chunk of code in my PCL

CrossLocalNotifications.Current.Show("test" + "  " + " New test", "Some Notification", 5,DateTime.Now.AddSeconds(8));

I have added the below code in AppDelegate.CS

```<code>if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
        {
            // iOS 10.0+
            UNUserNotificationCenter.Current.RequestAuthorization(
                UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound,
                (approved, error) => { });

            UNUserNotificationCenter.Current.Delegate = new UserNotificationCenterDelegate();
        }
</code>```

I am able to get the notification in iOS but am not getting the notification in Android. Do i need add any code in MainActivity.cs
can someone help me to fix this?

FYI: https://github.com/edsnider/LocalNotificationsPlugin

答:
As the document said, your code :

```<code>CrossLocalNotifications.Current.Show("test" + " " + " New test", "Some Notification", 5, DateTime.Now.AddSeconds(8));
</code>```

It will display a local notification at a scheduled date/time,  your notification will display after 8s delay.

If you want display a local notification immediately, you could try using :

```<code>CrossLocalNotifications.Current.Show("title", "body");
</code>```

It works fine on my side.

Update :

You were missing something to display a notification  .

As per the official documentation:
 a Notification object must contain the following:

A small icon, set by SetSmallIcon()

A title, set by SetContentTitle()

Detail text, set by SetContentText()

See http://developer.android.com/guide/topics/ui/notifiers/notifications.html

Body:
i have implemented Local Notifications in Xamarin.Forms using Xam.Plugins.Notifier. I have added the Nuget Package in PCL, iOS and Android.
below code is displaying the notification. i wrote the below chunk of code in my PCL

CrossLocalNotifications.Current.Show("test" + "  " + " New test", "Some Notification", 5,DateTime.Now.AddSeconds(8));

I have added the below code in AppDelegate.CS

if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
        {
            // iOS 10.0+
            UNUserNotificationCenter.Current.RequestAuthorization(
                UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound,
                (approved, error) => { });

            UNUserNotificationCenter.Current.Delegate = new UserNotificationCenterDelegate();
        }

I am able to get the notification in iOS but am not getting the notification in Android. Do i need add any code in MainActivity.cs
can someone help me to fix this?

FYI: https://github.com/edsnider/LocalNotificationsPlugin

Body:
As the document said, your code :

CrossLocalNotifications.Current.Show("test" + " " + " New test", "Some Notification", 5, DateTime.Now.AddSeconds(8));

It will display a local notification at a scheduled date/time,  your notification will display after 8s delay.

If you want display a local notification immediately, you could try using :

CrossLocalNotifications.Current.Show("title", "body");

It works fine on my side.

Update :

You were missing something to display a notification  .

As per the official documentation:
 a Notification object must contain the following:

A small icon, set by SetSmallIcon()

A title, set by SetContentTitle()

Detail text, set by SetContentText()

See http://developer.android.com/guide/topics/ui/notifiers/notifications.html


问:
Automapper and complex object
I have a complex object that I need to translate on a List of simple DTO object.

My map is this:

```<code>CreateMap<ObjASource, IEnumerable<MyDto>>()
            .ConvertUsing(source => source.ObjB?.ObjC?.Select(p => new MyDto
            {
                field1 = source.field1,
                field2 = source.field2,
                field3 = source.field3,
                field4 = p.fieldX,
                field5 = p.fieldY
            }).ToList()
            );
</code>```

This map works good when I'm working with singol ObjA
 like thismapper.Map<IList<MyDto>>(my_singol_objA); but doesn't work when I'm working with a list of ObjA mapper.Map<IList<MyDto>>(my_list_of_objA);

I don't know which other kind of map I have to add to correct this.

Thanks guys

EDITED because I didn't solve

I want to explain better and in more simple way my problems, maybe someone can help me.
I have a complex object with inside a Collection.

An object like this:

```<code>public class Product {
    int product_id {get; set;};
    string name {get; set;};
    List<CompaniesProvideProduct> company  {get; }
}
</code>```

The CompaniesProvideProduct contains the relation with a company that sell the product and have more details.

```<code>public class CompaniesProvideProduct {
    int product_id {get; set;};
    int company_id {get; set;};
    decimal price {get; set;};

}
</code>```

Then the destination object of my translation is:

```<code>public class ProductDto {
    int product_id {get; set;};
    string name {get; set;};
    int company_id {get; set;};
    decimal price {get; set;};

}
</code>```

In my program I get from db a List and I want to translate this object in a List. For 1 record of Product I'll have more record of ProductDto.

I tried with:

```<code>CreateMap<Product, ProductDto>(); //to get product_id and name
CreateMap<CompaniesProvideProduct, ProductDto>(); //to get company_id and price

CreateMap<Product, IEnumerable<ProductDto>>()
.ConvertUsing<ProductConverter>();

public class ProductConverter : ITypeConverter<Product, IEnumerable<ProductDto>>
{

    IEnumerable<ProductDto> ITypeConverter<Product, IEnumerable<ProductDto>>.Convert(Product source, IEnumerable<ProductDto> destination, ResolutionContext context)
    {
        Product prod = source;
        foreach (var dto in prod.company.Select(e => context.Mapper.Map<ProductDto>(e)))
        {
            context.Mapper.Map(prod, dto);
            yield return dto;
        }
    }
}
</code>```

But this doesn't work for me. If someone can help me I'll be very happy.

Thanks.

答:
@Lucian is correct. Collections are handled by default. So if your original mapping is setup correctly object => list<object> then list<object> => list<list<object>> would work as well.

```<code>           expression.CreateMap<ObjASource, List<MyDto>>()
                .ConvertUsing(source =>
                    {
                        return source.ObjB?.ObjC?.Select(p => new MyDto
                        {
                            field1 = source.field1,
                            field2 = source.field2,
                            field3 = source.field3,
                            field4 = p.fieldX,
                            field5 = p.fieldY
                        })
                        .ToList();
                    }
            );
</code>```

Here's the working sample:

```<code>        var test = new List<ObjASource>
        {
            new ObjASource
            {
                field1 = "1",
                field2 = "2",
                field3 = "3",
                ObjB = new ObjB
                {
                    ObjC = new List<ObjC>
                    {
                        new ObjC
                        {
                            fieldX = "X",
                            fieldY = "Y"
                        }
                    }
                }
            }
        };

        var result = Mapper.Map<List<List<MyDto>>>(test);
</code>```

UPDATE

So based on your updated question I think I better understand your issue.  Basically you need 2 explicit mappings - object => List<object> AND List<object> => List<object> - because as explained earlier AutoMapper gives List of List of the object which you do not want:

```<code>        var mapper = new MapperConfiguration(exp =>
        {
            exp.CreateMap<List<Product>, List<ProductDto>>()
                .ConstructUsing(products => products.SelectMany(product => product.company,
                    (product, companiesProvideProduct) => new ProductDto
                    {
                        product_id = product.product_id,
                        name = product.name,
                        company_id = companiesProvideProduct.company_id,
                        price = companiesProvideProduct.price
                    }).ToList());

            exp.CreateMap<Product, List<ProductDto>>()
                .ConvertUsing(product => product.company.Select(provideProduct => new ProductDto
                {
                    product_id = product.product_id,
                    name = product.name,
                    company_id = provideProduct.company_id,
                    price = provideProduct.price
                }).ToList());
        }).CreateMapper();
</code>```

So then if your object initialization looked like the following:

```<code>        var productList = new List<Product>
        {
            new Product
            {
                product_id = 1,
                name = "test1",
                company = new List<CompaniesProvideProduct>
                {
                    new CompaniesProvideProduct
                    {
                        company_id = 1,
                        price = 1.99m,
                        product_id = 1
                    }
                }
            },
            new Product
            {
                product_id = 2,
                name = "test2",
                company = new List<CompaniesProvideProduct>
                {
                    new CompaniesProvideProduct
                    {
                        company_id = 2,
                        price = 1.99m,
                        product_id = 2
                    }
                }
            }
        };
</code>```

The mapped objects would be:

```<code>var result1 = mapper.Map<List<ProductDto>>(productList);
var result2 = mapper.Map<List<ProductDto>>(productList.First());
</code>```

Title: Automapper and complex object

Body:
I have a complex object that I need to translate on a List of simple DTO object.

My map is this:

CreateMap<ObjASource, IEnumerable<MyDto>>()
            .ConvertUsing(source => source.ObjB?.ObjC?.Select(p => new MyDto
            {
                field1 = source.field1,
                field2 = source.field2,
                field3 = source.field3,
                field4 = p.fieldX,
                field5 = p.fieldY
            }).ToList()
            );

This map works good when I'm working with singol ObjA
 like thismapper.Map<IList<MyDto>>(my_singol_objA); but doesn't work when I'm working with a list of ObjA mapper.Map<IList<MyDto>>(my_list_of_objA);

I don't know which other kind of map I have to add to correct this.

Thanks guys

EDITED because I didn't solve

I want to explain better and in more simple way my problems, maybe someone can help me.
I have a complex object with inside a Collection.

An object like this:

public class Product {
    int product_id {get; set;};
    string name {get; set;};
    List<CompaniesProvideProduct> company  {get; }
}

The CompaniesProvideProduct contains the relation with a company that sell the product and have more details.

public class CompaniesProvideProduct {
    int product_id {get; set;};
    int company_id {get; set;};
    decimal price {get; set;};

}

Then the destination object of my translation is:

public class ProductDto {
    int product_id {get; set;};
    string name {get; set;};
    int company_id {get; set;};
    decimal price {get; set;};

}

In my program I get from db a List and I want to translate this object in a List. For 1 record of Product I'll have more record of ProductDto.

I tried with:

CreateMap<Product, ProductDto>(); //to get product_id and name
CreateMap<CompaniesProvideProduct, ProductDto>(); //to get company_id and price

CreateMap<Product, IEnumerable<ProductDto>>()
.ConvertUsing<ProductConverter>();

public class ProductConverter : ITypeConverter<Product, IEnumerable<ProductDto>>
{

    IEnumerable<ProductDto> ITypeConverter<Product, IEnumerable<ProductDto>>.Convert(Product source, IEnumerable<ProductDto> destination, ResolutionContext context)
    {
        Product prod = source;
        foreach (var dto in prod.company.Select(e => context.Mapper.Map<ProductDto>(e)))
        {
            context.Mapper.Map(prod, dto);
            yield return dto;
        }
    }
}

But this doesn't work for me. If someone can help me I'll be very happy.

Thanks.

Body:
@Lucian is correct. Collections are handled by default. So if your original mapping is setup correctly object => list<object> then list<object> => list<list<object>> would work as well.

           expression.CreateMap<ObjASource, List<MyDto>>()
                .ConvertUsing(source =>
                    {
                        return source.ObjB?.ObjC?.Select(p => new MyDto
                        {
                            field1 = source.field1,
                            field2 = source.field2,
                            field3 = source.field3,
                            field4 = p.fieldX,
                            field5 = p.fieldY
                        })
                        .ToList();
                    }
            );

Here's the working sample:

        var test = new List<ObjASource>
        {
            new ObjASource
            {
                field1 = "1",
                field2 = "2",
                field3 = "3",
                ObjB = new ObjB
                {
                    ObjC = new List<ObjC>
                    {
                        new ObjC
                        {
                            fieldX = "X",
                            fieldY = "Y"
                        }
                    }
                }
            }
        };

        var result = Mapper.Map<List<List<MyDto>>>(test);

UPDATE

So based on your updated question I think I better understand your issue.  Basically you need 2 explicit mappings - object => List<object> AND List<object> => List<object> - because as explained earlier AutoMapper gives List of List of the object which you do not want:

        var mapper = new MapperConfiguration(exp =>
        {
            exp.CreateMap<List<Product>, List<ProductDto>>()
                .ConstructUsing(products => products.SelectMany(product => product.company,
                    (product, companiesProvideProduct) => new ProductDto
                    {
                        product_id = product.product_id,
                        name = product.name,
                        company_id = companiesProvideProduct.company_id,
                        price = companiesProvideProduct.price
                    }).ToList());

            exp.CreateMap<Product, List<ProductDto>>()
                .ConvertUsing(product => product.company.Select(provideProduct => new ProductDto
                {
                    product_id = product.product_id,
                    name = product.name,
                    company_id = provideProduct.company_id,
                    price = provideProduct.price
                }).ToList());
        }).CreateMapper();

So then if your object initialization looked like the following:

        var productList = new List<Product>
        {
            new Product
            {
                product_id = 1,
                name = "test1",
                company = new List<CompaniesProvideProduct>
                {
                    new CompaniesProvideProduct
                    {
                        company_id = 1,
                        price = 1.99m,
                        product_id = 1
                    }
                }
            },
            new Product
            {
                product_id = 2,
                name = "test2",
                company = new List<CompaniesProvideProduct>
                {
                    new CompaniesProvideProduct
                    {
                        company_id = 2,
                        price = 1.99m,
                        product_id = 2
                    }
                }
            }
        };

The mapped objects would be:

var result1 = mapper.Map<List<ProductDto>>(productList);
var result2 = mapper.Map<List<ProductDto>>(productList.First());


问:
Access ro.serialno from native in Android 8?
I need some help. I have an app that is mostly written in native C code. I use the __system_property_get(const char * name, char * value) method to read the serial nr. of the device at various points in my native code. With Android 8 I always get a "Access denied" message now.

libc: Access denied finding property "ro.serialno"

Is there a way for me to still be able to read the serial nr. in Android 8? I tried switching to targetSDKversion < 26 but it still gives me a "Access denied" message. I do get the correct values if I use Java with Build.SERIAL (regardless of SDK version) and Build.getSerial() in SDK version 26 if I grant the READ_PHONE_STATE permission. But I cannot read these values in Java and pass them to the native code without a huge rewrite of the native code.

Any help?

答:
I met this problem too. Finally I find the root cause of the problem. In Android O, SELinux sets a lot of limitations in system property. In this case, There is a neverallow to limit read serial number except some domain in whitelist.

For more specific information, you can read code in system/sepolicy/public/domain.te:

```<code>neverallow {
  domain
  -adbd
  -dumpstate
  -hal_drm
  -init
  -mediadrmserver
  -recovery
  -shell
  -system_server
} serialno_prop:file r_file_perms;
</code>```

Body:
I met this problem too. Finally I find the root cause of the problem. In Android O, SELinux sets a lot of limitations in system property. In this case, There is a neverallow to limit read serial number except some domain in whitelist.

For more specific information, you can read code in system/sepolicy/public/domain.te:

neverallow {
  domain
  -adbd
  -dumpstate
  -hal_drm
  -init
  -mediadrmserver
  -recovery
  -shell
  -system_server
} serialno_prop:file r_file_perms;


问:
Using addEventListener() in a for loop with various listeners
I'm trying to add listeners to a number of buttons using a for loop. The appropriate listener for each button is indicated by the ID attribute of the button. Button IDs follow the form "button-[listenerName]". I get the list of all my button elements using querySelectorAll(), and then I iterate through that list, slicing out the name of each listener from the name of each button element. Then, I use the name of the listener with addEventListener() in an attempt to associate that button with its listener.

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

<button id="button-listener1">Try 1</button>
<button id="button-listener2">Try 2</button>
<button id="button-listener3">Try 3</button>
<button id="button-listener4">Try 4</button>

<p id="demo"></p>

<script>

var selector = "[id^=button]";
var allButtons = document.querySelectorAll(selector);
for (var button of allButtons) {
  var listenerName = button.id.slice(button.id.lastIndexOf("-")+1);
  button.addEventListener("click", listenerName);
}

var listener1 = function() {
  document.getElementById('demo').innerHtml = "1";
}

var listener2 = function() {
  document.getElementById('demo').innerHtml = "2";
}

var listener3 = function() {
  document.getElementById('demo').innerHtml = "3";
}

var listener4 = function() {
  document.getElementById('demo').innerHtml = "4";
}

</script>

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

Unfortunately, it doesn't work. What's up with that? Thank you.

答:
Or, you can change your loop like this and your code will work</p>

```<code>allButtons.forEach(function (button, i) {
    var listenerName = button.id.slice(button.id.lastIndexOf("-") + 1);
    button.addEventListener("click", function () {
    document.getElementById('demo').innerHTML = i + 1;
  });
});
</code>```

Body:
I'm trying to add listeners to a number of buttons using a for loop. The appropriate listener for each button is indicated by the ID attribute of the button. Button IDs follow the form "button-[listenerName]". I get the list of all my button elements using querySelectorAll(), and then I iterate through that list, slicing out the name of each listener from the name of each button element. Then, I use the name of the listener with addEventListener() in an attempt to associate that button with its listener.

<!DOCTYPE html>

<button id="button-listener1">Try 1</button>
<button id="button-listener2">Try 2</button>
<button id="button-listener3">Try 3</button>
<button id="button-listener4">Try 4</button>

Unfortunately, it doesn't work. What's up with that? Thank you.

Body:
Or, you can change your loop like this and your code will work

allButtons.forEach(function (button, i) {
    var listenerName = button.id.slice(button.id.lastIndexOf("-") + 1);
    button.addEventListener("click", function () {
    document.getElementById('demo').innerHTML = i + 1;
  });
});


问:
Read-Only properties without getters
I was reading this link about using getters in Python, quote:

The Pythonic way is to not use them. If you must have them then hide
  them behind a property.

That same page includes various examples, but my question is, if getters are not the Python way, how would I indicate to someone reading my code that a variable should be read-only after construction.

Suppose I have the following class:

```<code>class Car:
    def __init__(self, ID, name, tire, engine):
        self.ID = ID
        self.name = name
        self.tire = tire
        self.engine = engine

    def __str__(self):
        return "ID: {0} Name:{1} Tire: {2} Engine: {3}".format(self.ID, self.name, self.tire, self.engine)
</code>```

If I wanted to indicate to another developer that self.engine is read-only after being set in the constructor, how would I do so? In orders words, if clients violate the rule, and attempt to set it, it's there problem if the implementation of self.engine changes(for example, from object of the class Engine to Dictionary).

答:
You can use the @property decorator and not define a setter to communicate that engine should not be modified:

```<code>class Car(object):
    def __init__(self, ID, name, tire, engine):
        self.ID = ID
        self.name = name
        self.tire = tire
        self._engine = engine

    def __str__(self):
        return "ID: {0} Name:{1} Tire: {2} Engine: {3}".format(self.ID, self.name, self.tire, self.engine)

    @property
    def engine(self):
        return self._engine
</code>```

Note that the user can still go around the property and set _engine directly.

Note that the @property decorator only works with new style classes.

Title: Read-Only properties without getters

Body:
I was reading this link about using getters in Python, quote:

The Pythonic way is to not use them. If you must have them then hide
  them behind a property.

That same page includes various examples, but my question is, if getters are not the Python way, how would I indicate to someone reading my code that a variable should be read-only after construction.

Suppose I have the following class:

class Car:
    def __init__(self, ID, name, tire, engine):
        self.ID = ID
        self.name = name
        self.tire = tire
        self.engine = engine

    def __str__(self):
        return "ID: {0} Name:{1} Tire: {2} Engine: {3}".format(self.ID, self.name, self.tire, self.engine)

If I wanted to indicate to another developer that self.engine is read-only after being set in the constructor, how would I do so? In orders words, if clients violate the rule, and attempt to set it, it's there problem if the implementation of self.engine changes(for example, from object of the class Engine to Dictionary).

Body:
You can use the @property decorator and not define a setter to communicate that engine should not be modified:

class Car(object):
    def __init__(self, ID, name, tire, engine):
        self.ID = ID
        self.name = name
        self.tire = tire
        self._engine = engine

    def __str__(self):
        return "ID: {0} Name:{1} Tire: {2} Engine: {3}".format(self.ID, self.name, self.tire, self.engine)

    @property
    def engine(self):
        return self._engine

Note that the user can still go around the property and set _engine directly.

Note that the @property decorator only works with new style classes.


问:
Dynamic routing in angular2
I am trying to create dynamic routes with the index names I have in my elastic index. I was able to create dynamic routing by adding manually some names but when I try to insert the routes with my elastic index names it skips that part,

app.routing.ts

```<code>constructor(http: Http, router: Router) {
        http.get('http://localhost:9200/_stats').subscribe(data => {

            for (let entry of Object.keys(data.json().indices)) {
                router.config.push({path: entry, component: SearchComponent});
            }

        });
        router.config.push({path: 'test', component: SearchComponent});
        console.log('Routes: ', JSON.stringify(router.config, undefined, 1));
    }
</code>```

I printed out my routes got results as below,

```<code>Routes:  [
 {
  "path": "home"
 },
 {
  "path": "404/pagenotfound"
 },
 {
  "path": "test"
 }
]
</code>```

I couldn't find out why this code snippet skips the part where I insert my elastic index names. But when I printed out as below it shows the index names I trying to add is added.

```<code>http.get('http://localhost:9200/_stats').subscribe(data => {

            for (let entry of Object.keys(data.json().indices)) {
                router.config.push({path: entry, component: SearchComponent});
            }

            console.log('Routes: ', JSON.stringify(router.config, undefined, 1));
        });
</code>```

Results I got when I print as above.

```<code>Routes:  [
 {
  "path": "home"
 },
 {
  "path": "404/pagenotfound"
 },
 {
  "path": "test"
 },
 {
  "path": "pokemon"
 },
 {
  "path": "cars"
 },
 {
  "path": "tweets"
 },
 {
  "path": "bikes"
 },
 {
  "path": "apple"
 }
]
</code>```

When I tried to access the URL it throws an error as below.

```<code>ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'tweets'
</code>```

Could you please describe to me what I am doing wrong?

EDIT

```<code>import {APP_INITIALIZER, NgModule, OnInit} from '@angular/core';
import {CommonModule,} from '@angular/common';
import {BrowserModule} from '@angular/platform-browser';
import {Routes, RouterModule, Router, Resolve} from '@angular/router';
import {SearchComponent} from './search/search.component';
import {NotFoundComponent} from "./notfoundcomponent/notfoundcomponent.component";
import {HomeComponent} from "./home/home.component";
import {Http} from "@angular/http";
import {init} from "protractor/built/launcher";

export function loadRoutes(http: Http, router: Router) {
    return () => {
        router.resetConfig([
            {path: 'fd', component: HomeComponent}
        ]);
    };
}

let routes: Routes = [
    {path: '', redirectTo: 'home', pathMatch: 'full'},
    {path: 'home', component: HomeComponent},
    {path: '404/pagenotfound', component: NotFoundComponent}
];

@NgModule({
    imports: [
        CommonModule,
        BrowserModule,
        RouterModule.forRoot(routes)
    ],
    providers: [{
        'provide': APP_INITIALIZER,
        'useFactory': init,
        'deps': [Http, Router],
        'multi': true
    }],
    entryComponents: [SearchComponent]
})

export class AppRoutingModule {

    constructor(private http: Http, private router: Router) {

        http.get('http://localhost:9200/_stats').subscribe(data => {

            for (let entry of Object.keys(data.json().indices)) {
                router.config.push({path: entry, component: SearchComponent});
            }
            console.log('Routes: ', JSON.stringify(router.config, undefined, 1));
        });

        console.log('Routes: ', JSON.stringify(router.config, undefined, 1));
    }

}
</code>```

答:
It seems that you need to use resetConfig

```<code>router.resetConfig([
 { path: 'team/:id', component: TeamCmp, children: [
   { path: 'simple', component: SimpleCmp },
   { path: 'user/:name', component: UserCmp }
 ]}
]);
</code>```

Other thing which i think should help is APP_INITIALIZER

```<code>Add to providers

 {
      'provide': APP_INITIALIZER,
      'useFactory': loadRoutes,
      'deps': [Http, Router],
      'multi': true
    },
</code>```

Then add loader

```<code>export function loadRoutes(http: Http, router: Router) {
   return () => {
  //DO your job here
  };
</code>```

}

As a result it will wait to load routes and only after that it will continue

Title: Dynamic routing in angular2

Body:
I am trying to create dynamic routes with the index names I have in my elastic index. I was able to create dynamic routing by adding manually some names but when I try to insert the routes with my elastic index names it skips that part,

app.routing.ts

constructor(http: Http, router: Router) {
        http.get('http://localhost:9200/_stats').subscribe(data => {

            for (let entry of Object.keys(data.json().indices)) {
                router.config.push({path: entry, component: SearchComponent});
            }

        });
        router.config.push({path: 'test', component: SearchComponent});
        console.log('Routes: ', JSON.stringify(router.config, undefined, 1));
    }

I printed out my routes got results as below,

Routes:  [
 {
  "path": "home"
 },
 {
  "path": "404/pagenotfound"
 },
 {
  "path": "test"
 }
]

I couldn't find out why this code snippet skips the part where I insert my elastic index names. But when I printed out as below it shows the index names I trying to add is added.

http.get('http://localhost:9200/_stats').subscribe(data => {

            for (let entry of Object.keys(data.json().indices)) {
                router.config.push({path: entry, component: SearchComponent});
            }

            console.log('Routes: ', JSON.stringify(router.config, undefined, 1));
        });

Results I got when I print as above.

Routes:  [
 {
  "path": "home"
 },
 {
  "path": "404/pagenotfound"
 },
 {
  "path": "test"
 },
 {
  "path": "pokemon"
 },
 {
  "path": "cars"
 },
 {
  "path": "tweets"
 },
 {
  "path": "bikes"
 },
 {
  "path": "apple"
 }
]

When I tried to access the URL it throws an error as below.

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'tweets'

Could you please describe to me what I am doing wrong?

EDIT

import {APP_INITIALIZER, NgModule, OnInit} from '@angular/core';
import {CommonModule,} from '@angular/common';
import {BrowserModule} from '@angular/platform-browser';
import {Routes, RouterModule, Router, Resolve} from '@angular/router';
import {SearchComponent} from './search/search.component';
import {NotFoundComponent} from "./notfoundcomponent/notfoundcomponent.component";
import {HomeComponent} from "./home/home.component";
import {Http} from "@angular/http";
import {init} from "protractor/built/launcher";

export function loadRoutes(http: Http, router: Router) {
    return () => {
        router.resetConfig([
            {path: 'fd', component: HomeComponent}
        ]);
    };
}

let routes: Routes = [
    {path: '', redirectTo: 'home', pathMatch: 'full'},
    {path: 'home', component: HomeComponent},
    {path: '404/pagenotfound', component: NotFoundComponent}
];

@NgModule({
    imports: [
        CommonModule,
        BrowserModule,
        RouterModule.forRoot(routes)
    ],
    providers: [{
        'provide': APP_INITIALIZER,
        'useFactory': init,
        'deps': [Http, Router],
        'multi': true
    }],
    entryComponents: [SearchComponent]
})

export class AppRoutingModule {

    constructor(private http: Http, private router: Router) {

        http.get('http://localhost:9200/_stats').subscribe(data => {

            for (let entry of Object.keys(data.json().indices)) {
                router.config.push({path: entry, component: SearchComponent});
            }
            console.log('Routes: ', JSON.stringify(router.config, undefined, 1));
        });

        console.log('Routes: ', JSON.stringify(router.config, undefined, 1));
    }

}

Body:
It seems that you need to use resetConfig

router.resetConfig([
 { path: 'team/:id', component: TeamCmp, children: [
   { path: 'simple', component: SimpleCmp },
   { path: 'user/:name', component: UserCmp }
 ]}
]);

Other thing which i think should help is APP_INITIALIZER

Add to providers

 {
      'provide': APP_INITIALIZER,
      'useFactory': loadRoutes,
      'deps': [Http, Router],
      'multi': true
    },

Then add loader

export function loadRoutes(http: Http, router: Router) {
   return () => {
  //DO your job here
  };

}

As a result it will wait to load routes and only after that it will continue


问:
setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

componentDidMount(prevProps, prevState, prevContext) {
    let [audioNode, songLen] = [this.refs.audio, List.length-1];

    audioNode.addEventListener('ended', () => {
        this._endedPlay(songLen, () => {
            this._currSong(this.state.songIndex);
            this._Play(audioNode);
        });
    });

    audioNode.addEventListener('timeupdate', () => {
        let [remainTime, remainTimeMin, remainTimeSec, remainTimeInfo] = [];

        if(!isNaN(audioNode.duration)) {
            remainTime = audioNode.duration - audioNode.currentTime;
            remainTimeMin = parseInt(remainTime/60);  // 剩余分
            remainTimeSec = parseInt(remainTime%60);  // 剩余秒

            if(remainTimeSec < 10) {
                remainTimeSec = '0'+remainTimeSec;
            }
            remainTimeInfo = remainTimeMin + ':' + remainTimeSec;
            this.setState({'time': remainTimeInfo});
        }
    });
}

componentWillUnmount () {
    let audio = this.refs.audio;
    audio.removeEventListener('timeupdate');
    audio.removeEventListener('ended');
}
```

Error:

Warning: setState(...): Can only update a mounted or mounting
  component. This usually means you called setState() on an unmounted
  component. This is a no-op. Please check the code for the undefined
  component.

I removeEventListener 'ended' in componentWillUnmount, but it is not working. because I add this.setState({'time': remainTimeInfo}); in componentDidMount.

答: addEventListener and removeEventListener，the Callback must not be Anonymous inner class,and they should have the same params</p>

Body:
componentDidMount(prevProps, prevState, prevContext) {
    let [audioNode, songLen] = [this.refs.audio, List.length-1];

    audioNode.addEventListener('ended', () => {
        this._endedPlay(songLen, () => {
            this._currSong(this.state.songIndex);
            this._Play(audioNode);
        });
    });

    audioNode.addEventListener('timeupdate', () => {
        let [remainTime, remainTimeMin, remainTimeSec, remainTimeInfo] = [];

        if(!isNaN(audioNode.duration)) {
            remainTime = audioNode.duration - audioNode.currentTime;
            remainTimeMin = parseInt(remainTime/60);  // 剩余分
            remainTimeSec = parseInt(remainTime%60);  // 剩余秒

            if(remainTimeSec < 10) {
                remainTimeSec = '0'+remainTimeSec;
            }
            remainTimeInfo = remainTimeMin + ':' + remainTimeSec;
            this.setState({'time': remainTimeInfo});
        }
    });
}

componentWillUnmount () {
    let audio = this.refs.audio;
    audio.removeEventListener('timeupdate');
    audio.removeEventListener('ended');
}

Error:

Warning: setState(...): Can only update a mounted or mounting
  component. This usually means you called setState() on an unmounted
  component. This is a no-op. Please check the code for the undefined
  component.

I removeEventListener 'ended' in componentWillUnmount, but it is not working. because I add this.setState({'time': remainTimeInfo}); in componentDidMount.


问:
Convert UTC datetime string to local datetime
I've never had to convert time to and from UTC. Recently had a request to have my app be timezone aware, and I've been running myself in circles. Lots of information on converting local time to UTC, which I found fairly elementary (maybe I'm doing that wrong as well), but I can not find any information on easily converting the UTC time to the end-users timezone.

In a nutshell, and android app sends me (appengine app) data and within that data is a timestamp. To store that timestamp to utc time I am using:

```<code>datetime.utcfromtimestamp(timestamp)
</code>```

That seems to be working. When my app stores the data, it is being store as 5 hours ahead (I am EST -5)

The data is being stored on appengine's BigTable, and when retrieved it comes out as a string like so:

```<code>"2011-01-21 02:37:21"
</code>```

How do I convert this string to a DateTime in the users correct time zone?

Also, what is the recommended storage for a users timezone information?  (How do you typically store tz info ie: "-5:00" or "EST" etc etc ?) I'm sure the answer to my first question might contain a parameter the answers the second.

答:
See the datetime documentation on tzinfo objects.  You have to implement the timezones you want to support yourself.  The are examples at the bottom of the documentation.

Here's a simple example:

```<code>from datetime import datetime,tzinfo,timedelta

class Zone(tzinfo):
    def __init__(self,offset,isdst,name):
        self.offset = offset
        self.isdst = isdst
        self.name = name
    def utcoffset(self, dt):
        return timedelta(hours=self.offset) + self.dst(dt)
    def dst(self, dt):
            return timedelta(hours=1) if self.isdst else timedelta(0)
    def tzname(self,dt):
         return self.name

GMT = Zone(0,False,'GMT')
EST = Zone(-5,False,'EST')

print datetime.utcnow().strftime('%m/%d/%Y %H:%M:%S %Z')
print datetime.now(GMT).strftime('%m/%d/%Y %H:%M:%S %Z')
print datetime.now(EST).strftime('%m/%d/%Y %H:%M:%S %Z')

t = datetime.strptime('2011-01-21 02:37:21','%Y-%m-%d %H:%M:%S')
t = t.replace(tzinfo=GMT)
print t
print t.astimezone(EST)
</code>```

Output

```<code>01/22/2011 21:52:09
01/22/2011 21:52:09 GMT
01/22/2011 16:52:09 EST
2011-01-21 02:37:21+00:00
2011-01-20 21:37:21-05:00a
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've never had to convert time to and from UTC. Recently had a request to have my app be timezone aware, and I've been running myself in circles. Lots of information on converting local time to UTC, which I found fairly elementary (maybe I'm doing that wrong as well), but I can not find any information on easily converting the UTC time to the end-users timezone.

In a nutshell, and android app sends me (appengine app) data and within that data is a timestamp. To store that timestamp to utc time I am using:

datetime.utcfromtimestamp(timestamp)

That seems to be working. When my app stores the data, it is being store as 5 hours ahead (I am EST -5)

The data is being stored on appengine's BigTable, and when retrieved it comes out as a string like so:

"2011-01-21 02:37:21"

How do I convert this string to a DateTime in the users correct time zone?

Also, what is the recommended storage for a users timezone information?  (How do you typically store tz info ie: "-5:00" or "EST" etc etc ?) I'm sure the answer to my first question might contain a parameter the answers the second.

Body:
See the datetime documentation on tzinfo objects.  You have to implement the timezones you want to support yourself.  The are examples at the bottom of the documentation.

Here's a simple example:

from datetime import datetime,tzinfo,timedelta

class Zone(tzinfo):
    def __init__(self,offset,isdst,name):
        self.offset = offset
        self.isdst = isdst
        self.name = name
    def utcoffset(self, dt):
        return timedelta(hours=self.offset) + self.dst(dt)
    def dst(self, dt):
            return timedelta(hours=1) if self.isdst else timedelta(0)
    def tzname(self,dt):
         return self.name

GMT = Zone(0,False,'GMT')
EST = Zone(-5,False,'EST')

print datetime.utcnow().strftime('%m/%d/%Y %H:%M:%S %Z')
print datetime.now(GMT).strftime('%m/%d/%Y %H:%M:%S %Z')
print datetime.now(EST).strftime('%m/%d/%Y %H:%M:%S %Z')

t = datetime.strptime('2011-01-21 02:37:21','%Y-%m-%d %H:%M:%S')
t = t.replace(tzinfo=GMT)
print t
print t.astimezone(EST)

Output

01/22/2011 21:52:09
01/22/2011 21:52:09 GMT
01/22/2011 16:52:09 EST
2011-01-21 02:37:21+00:00
2011-01-20 21:37:21-05:00a


问:
Difference between execution policies and when to use them
I noticed that a majority (if not all) functions in <algorithm> are getting one or more extra overloads. All of these extra overloads add a specific new parameter, for example, std::for_each goes from:

```<code>template< class InputIt, class UnaryFunction >
UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f );
</code>```

to:

```<code>template< class ExecutionPolicy, class InputIt, class UnaryFunction2 >
void for_each( ExecutionPolicy&& policy, InputIt first, InputIt last, UnaryFunction2 f );
</code>```

What effect does this extra ExecutionPolicy have on these functions?

What are the differences between:

std::execution::seq

std::execution::par

std::execution::par_unseq

And when to use one or the other?

答:
What is the difference between seq and par/par_unseq?

```<code>std::for_each(std::execution::seq, std::begin(v), std::end(v), function_call);
</code>```

std::execution::seq stands for sequential execution. It is the default if you do not specify the execution policy at all. It will force the implementation to execute all function calls in sequence. It is also guaranteed that everything is executed by the calling thread.

In contrast, std::execution::par and std::execution::par_unseq implies parallel execution. That means you promise that all invocations of the given function can be safely executed in parallel without violating any data dependencies. The implementation is allowed to use a parallel implementation, though it is not forced to do so.

What is the difference between par and par_unseq?

par_unseq requires stronger guarantees than par, but allows additional optimizations. Specifically, par_unseq requires the option to interleave the execution of multiple function calls in the same thread.

Let us illustrate the difference with an example. Suppose you want to parallelize this loop:

```<code>std::vector<int> v = { 1, 2, 3 };
int sum = 0;
std::for_each(std::execution::seq, std::begin(v), std::end(v), [&](int i) {
  sum += i*i;
});
</code>```

You cannot directly parallelize the code above, as it would introduce a data dependency for the sum variable. To avoid that, you can introduce a lock:

```<code>int sum = 0;
std::mutex m;
std::for_each(std::execution::par, std::begin(v), std::end(v), [&](int i) {
  std::lock_guard<std::mutex> lock{m};
  sum += i*i;
});
</code>```

Now all function calls can be safely executed in parallel, and the code will not break when you switch to par. But what would happen if you use par_unseq instead, where one thread could potentially execute multiple function calls not in sequence but concurrently?

It can result in a deadlock, for instance, if the code is reordered like this:

```<code> m.lock();    // iteration 1 (constructor of std::lock_guard)
 m.lock();    // iteration 2
 sum += ...;  // iteration 1
 sum += ...;  // iteration 2
 m.unlock();  // iteration 1 (destructor of std::lock_guard)
 m.unlock();  // iteration 2
</code>```

In the standard, the term is vectorization-unsafe. To quote from P0024R2:

A standard library function is vectorization-unsafe if it is specified to synchronize with another function invocation, or another function invocation is specified to synchronize with it, and if it is not a memory allocation or deallocation function. Vectorization-unsafe standard library functions may not be invoked by user code called from parallel_vector_execution_policy algorithms.

One way to make the code above vectorization-safe, is to replace the mutex by an atomic:

```<code>std::atomic<int> sum{0};
std::for_each(std::execution::par_unseq, std::begin(v), std::end(v), [&](int i) {
  sum.fetch_add(i*i, std::memory_order_relaxed);
});
</code>```

What are the advantages of using par_unseq over par?

The additional optimizations that an implementation can use in par_unseq mode include vectorized execution and migrations of work across threads (the latter is relevant if task parallelism is used with a parent-stealing scheduler).

If vectorization is allowed, implementations can internally use SIMD parallelism (Single-Instruction, Multiple-Data). For example, OpenMP supports it via #pragma omp simd annotations, which can help compilers to generate better code.

When should I prefer std::execution::seq?

correctness (avoiding data races)

avoiding parallel overhead (startup costs and synchronization)

simplicity (debugging)

It is not uncommon that data dependencies will enforce sequential execution. In other words, use sequential execution if parallel execution would add data races.

Rewriting and tuning the code for parallel execution is not always trivial. Unless it is a critical part of your application, you can start with a sequential version and optimize later. You also might want to avoid parallel execution if you are executing the code in a shared environment where you need to be conservative in resource usage.

Parallelism also does not come for free. If the expected total execution time of the loop is very low, sequential execution will most likely be the best even from a pure performance perspective. The bigger the data and the more costly each computation step is, the less important the synchronization overhead will be.

For instance, using parallelism in the example above would not make sense, as the vector only contains three elements and the operations are very cheap. Also note that the original version - before the introduction of mutexes or atomics - contained no synchronization overhead. A common mistake in measuring speedup of a parallel algorithm is to use a parallel version running on one CPU as the baseline. Instead, you should always compare against an optimized sequential implementation without the synchronization overhead.

When should I prefer std::execution::par_unseq?

First, make sure that it does not sacrifice correctness:

If there are data races when executing steps in parallel by different threads, par_unseq is not an option.

If the code is vectorization-unsafe, for instance, because it acquires a lock, par_unseq is not an option (but par might be).

Otherwise, use par_unseq if it is a performance critical part and par_unseq improves the performance over seq.

When should I prefer std::execution::par?

If the steps can be executed safely in parallel, but you cannot use par_unseq because it is vectorization-unsafe, it is a candidate for par.

Like par_unseq, verify that it is a performance critical part and par is a performance improvement over seq.

Sources:

cppreference.com (execution policy)

P0024R2: The Parallelism TS Should be Standardized

Body:
I noticed that a majority (if not all) functions in <algorithm> are getting one or more extra overloads. All of these extra overloads add a specific new parameter, for example, std::for_each goes from:

template< class InputIt, class UnaryFunction >
UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f );

to:

template< class ExecutionPolicy, class InputIt, class UnaryFunction2 >
void for_each( ExecutionPolicy&& policy, InputIt first, InputIt last, UnaryFunction2 f );

What effect does this extra ExecutionPolicy have on these functions?

What are the differences between:

std::execution::seq

std::execution::par

std::execution::par_unseq

And when to use one or the other?

Body:
What is the difference between seq and par/par_unseq?

std::for_each(std::execution::seq, std::begin(v), std::end(v), function_call);

std::execution::seq stands for sequential execution. It is the default if you do not specify the execution policy at all. It will force the implementation to execute all function calls in sequence. It is also guaranteed that everything is executed by the calling thread.

In contrast, std::execution::par and std::execution::par_unseq implies parallel execution. That means you promise that all invocations of the given function can be safely executed in parallel without violating any data dependencies. The implementation is allowed to use a parallel implementation, though it is not forced to do so.

What is the difference between par and par_unseq?

par_unseq requires stronger guarantees than par, but allows additional optimizations. Specifically, par_unseq requires the option to interleave the execution of multiple function calls in the same thread.

Let us illustrate the difference with an example. Suppose you want to parallelize this loop:

std::vector<int> v = { 1, 2, 3 };
int sum = 0;
std::for_each(std::execution::seq, std::begin(v), std::end(v), [&](int i) {
  sum += i*i;
});

You cannot directly parallelize the code above, as it would introduce a data dependency for the sum variable. To avoid that, you can introduce a lock:

int sum = 0;
std::mutex m;
std::for_each(std::execution::par, std::begin(v), std::end(v), [&](int i) {
  std::lock_guard<std::mutex> lock{m};
  sum += i*i;
});

Now all function calls can be safely executed in parallel, and the code will not break when you switch to par. But what would happen if you use par_unseq instead, where one thread could potentially execute multiple function calls not in sequence but concurrently?

It can result in a deadlock, for instance, if the code is reordered like this:

 m.lock();    // iteration 1 (constructor of std::lock_guard)
 m.lock();    // iteration 2
 sum += ...;  // iteration 1
 sum += ...;  // iteration 2
 m.unlock();  // iteration 1 (destructor of std::lock_guard)
 m.unlock();  // iteration 2

In the standard, the term is vectorization-unsafe. To quote from P0024R2:

A standard library function is vectorization-unsafe if it is specified to synchronize with another function invocation, or another function invocation is specified to synchronize with it, and if it is not a memory allocation or deallocation function. Vectorization-unsafe standard library functions may not be invoked by user code called from parallel_vector_execution_policy algorithms.

One way to make the code above vectorization-safe, is to replace the mutex by an atomic:

std::atomic<int> sum{0};
std::for_each(std::execution::par_unseq, std::begin(v), std::end(v), [&](int i) {
  sum.fetch_add(i*i, std::memory_order_relaxed);
});

What are the advantages of using par_unseq over par?

The additional optimizations that an implementation can use in par_unseq mode include vectorized execution and migrations of work across threads (the latter is relevant if task parallelism is used with a parent-stealing scheduler).

If vectorization is allowed, implementations can internally use SIMD parallelism (Single-Instruction, Multiple-Data). For example, OpenMP supports it via #pragma omp simd annotations, which can help compilers to generate better code.

When should I prefer std::execution::seq?

correctness (avoiding data races)

avoiding parallel overhead (startup costs and synchronization)

simplicity (debugging)

It is not uncommon that data dependencies will enforce sequential execution. In other words, use sequential execution if parallel execution would add data races.

Rewriting and tuning the code for parallel execution is not always trivial. Unless it is a critical part of your application, you can start with a sequential version and optimize later. You also might want to avoid parallel execution if you are executing the code in a shared environment where you need to be conservative in resource usage.

Parallelism also does not come for free. If the expected total execution time of the loop is very low, sequential execution will most likely be the best even from a pure performance perspective. The bigger the data and the more costly each computation step is, the less important the synchronization overhead will be.

For instance, using parallelism in the example above would not make sense, as the vector only contains three elements and the operations are very cheap. Also note that the original version - before the introduction of mutexes or atomics - contained no synchronization overhead. A common mistake in measuring speedup of a parallel algorithm is to use a parallel version running on one CPU as the baseline. Instead, you should always compare against an optimized sequential implementation without the synchronization overhead.

When should I prefer std::execution::par_unseq?

First, make sure that it does not sacrifice correctness:

If there are data races when executing steps in parallel by different threads, par_unseq is not an option.

If the code is vectorization-unsafe, for instance, because it acquires a lock, par_unseq is not an option (but par might be).

Otherwise, use par_unseq if it is a performance critical part and par_unseq improves the performance over seq.

When should I prefer std::execution::par?

If the steps can be executed safely in parallel, but you cannot use par_unseq because it is vectorization-unsafe, it is a candidate for par.

Like par_unseq, verify that it is a performance critical part and par is a performance improvement over seq.

Sources:

cppreference.com (execution policy)

P0024R2: The Parallelism TS Should be Standardized


问:
Removing duplicates from a large table with NULL columns that also need to be taken into account
I am interested in removing duplicates from a very large table (40+ million records, 3+ GB in size), that also has to count NULL columns when determining duplicates.   5.5.56-MariaDB, tables are in InnoDB format.

The problem I'm running into is that some of the recommended methods will not work when it comes to NULL field comparison.    For example, I have a table that has about a dozen columns, many of which can contain NULL values, and I want NULLs treated as any other value, in that if a row has the same NULL values in the same columns, it's considered a dupe.

The technique below does NOT work:

```<code>create table tmp like mytable;
alter table tmp ADD UNIQUE INDEX(field1,field2, field3,...);
insert IGNORE into tmp (select * from mytable);
</code>```

At this point, tmp should have all dupes removed, but NULL columns are ignored in the Unique index, so it doesn't work.  If it did work, then I could rename the tables, or truncate the original table and copy over (assuming I wanted to preserve a primary key in the original table).

What is the most efficient way of deleting dupes in large files when dealing with NULL columns that should also be taken into consideration?

Additional notes:   I have a field called "recno" that is Auto Increment that needs to be ignored.

答:
You can select them with a query like:

```<code>  SELECT field1, field2, field3, count(1)
    FROM t
GROUP BY field1, field2, field3
  HAVING count(1) > 1
</code>```

And then delete them with code or use some kind of control logic, whatever is available in in mysql.  I'm sure there are other ways to do it.

Body:
I am interested in removing duplicates from a very large table (40+ million records, 3+ GB in size), that also has to count NULL columns when determining duplicates.   5.5.56-MariaDB, tables are in InnoDB format.

The problem I'm running into is that some of the recommended methods will not work when it comes to NULL field comparison.    For example, I have a table that has about a dozen columns, many of which can contain NULL values, and I want NULLs treated as any other value, in that if a row has the same NULL values in the same columns, it's considered a dupe.

The technique below does NOT work:

create table tmp like mytable;
alter table tmp ADD UNIQUE INDEX(field1,field2, field3,...);
insert IGNORE into tmp (select * from mytable);

At this point, tmp should have all dupes removed, but NULL columns are ignored in the Unique index, so it doesn't work.  If it did work, then I could rename the tables, or truncate the original table and copy over (assuming I wanted to preserve a primary key in the original table).

What is the most efficient way of deleting dupes in large files when dealing with NULL columns that should also be taken into consideration?

Additional notes:   I have a field called "recno" that is Auto Increment that needs to be ignored.

Body:
You can select them with a query like:

  SELECT field1, field2, field3, count(1)
    FROM t
GROUP BY field1, field2, field3
  HAVING count(1) > 1

And then delete them with code or use some kind of control logic, whatever is available in in mysql.  I'm sure there are other ways to do it.


问:
MVC3 - HiddenFor Dictionary Values
I have a dictionary property called Week:

```<code>public IDictionary<DayOfWeek, Day> Week { get; private set; }
</code>```

And I'm trying to pass its values off to HiddenFor (Days)

```<code>@Html.HiddenFor(x => x.Week.Values)
</code>```

It has to be a property of the Model so I can't do x.Week.Values.ToList();

How would I go about passing the Dictionary Values to the Html.HiddenFor?

答:
I would use:

```<code>@foreach (var key in Model.Week.Keys)
{
    @Html.HiddenFor(model=>model.Week[key]);
}
</code>```

The '@' before the Html seems necessary for razor to output the hidden fields.

It outputs something like this for each key:

```<code><input data-val="true" data-val-number="The field Int32 must be a number."
   data-val-required="The Int32 field is required." id="Week_5_" name="Week[5]"
   type="hidden" value="3">
</code>```

Title: MVC3 - HiddenFor Dictionary Values

Body:
I have a dictionary property called Week:

public IDictionary<DayOfWeek, Day> Week { get; private set; }

And I'm trying to pass its values off to HiddenFor (Days)

@Html.HiddenFor(x => x.Week.Values)

It has to be a property of the Model so I can't do x.Week.Values.ToList();

How would I go about passing the Dictionary Values to the Html.HiddenFor?

Body:
I would use:

@foreach (var key in Model.Week.Keys)
{
    @Html.HiddenFor(model=>model.Week[key]);
}

The '@' before the Html seems necessary for razor to output the hidden fields.

It outputs something like this for each key:

<input data-val="true" data-val-number="The field Int32 must be a number."
   data-val-required="The Int32 field is required." id="Week_5_" name="Week[5]"
   type="hidden" value="3">


问:
Where does EMR store Spark stdout?
I am running my Spark application on EMR, and have several println() statements. Other than the console, where do these statements get logged?

My S3 aws-logs directory structure for my cluster looks like:

node
├── i-0031cd7a536a42g1e
│   ├── applications
│   ├── bootstrap-actions
│   ├── daemons
│   ├── provision-node
│   └── setup-devices
containers/
├── application_12341331455631_0001
│   ├── container_12341331455631_0001_01_000001

答:
There is a very important thing that you need to consider when printing from Spark: are you running code that gets executed in the driver or is it code that runs in the executor?

For example, if you do the following, it will output in the console as you are bringing data back to the driver:

```<code>for i in your_rdd.collect():
    print i
</code>```

But the following will run within an executor and thus it will be written in the Spark logs:

```<code>def run_in_executor(value):
    print value

your_rdd.map(lambda x: value(x))
</code>```

Now going to your original question, the second case will write to the log location. Logs are usually written to the master node which is located in /mnt/var/log/hadoop/steps, but it might be better to configure logs to an s3 bucket with --log-uri. That way it will be easier to find.

Title: Where does EMR store Spark stdout?

Body:
There is a very important thing that you need to consider when printing from Spark: are you running code that gets executed in the driver or is it code that runs in the executor?

For example, if you do the following, it will output in the console as you are bringing data back to the driver:

for i in your_rdd.collect():
    print i

But the following will run within an executor and thus it will be written in the Spark logs:

def run_in_executor(value):
    print value

your_rdd.map(lambda x: value(x))

Now going to your original question, the second case will write to the log location. Logs are usually written to the master node which is located in /mnt/var/log/hadoop/steps, but it might be better to configure logs to an s3 bucket with --log-uri. That way it will be easier to find.


问:
ColdFusion Dynamic SQL with cfif
I'm trying to write a query which would accept 1 of 4 possible parameters passed from another page.  The user would select one of these parameters to search on and then the query would evaluate which of those was selected based on the passed parameter.  I'm trying to use a cfif to accomplish this but I must be missing something.  Maybe a cfelse, and OR, or maybe I'm way off.  Would this be better as cffunction? I get an error "variable DivisionCode" is undefined.  Thank you.</p>

```<code><cfquery name="Summary" datasource="dsn">
    SELECT
        *
    FROM
        disposal
    WHERE 1=1

    <cfif DivisionCode NEQ "false">
    AND DivisionCode = <cfqueryparam value="#url.DivisionCode#"
   cfsqltype="cf_sql_varchar">
   </cfif>
   <cfif DistrictCode NEQ "false">
    AND DistrictCode = <cfqueryparam value="#url.DistrictCode#"
   cfsqltype="cf_sql_varchar">
   </cfif>
   <cfif SiteCode NEQ "false">
    AND SiteCode = <cfqueryparam value="#url.SiteCode#"
   cfsqltype="cf_sql_varchar">
  </cfif>
  <cfif RegionCode NEQ "false">
    AND RegionCode = <cfqueryparam value="#url.RegionCode#"
  cfsqltype="cf_sql_varchar">
  </cfif>
  ORDER By
    CYear DESC
  </cfquery>
</code>```

答:
Two options come to my mind: You can either make it work like an include or call it as a function.

Isolated Include (less common)

your_query.cfm

```<code><!--- declaring possible incoming parameters --->
<cfparam name="attributes.datasource"   type="string" default="dsn">
<cfparam name="attributes.divisionCode" type="string" default="">
<cfparam name="attributes.districtCode" type="string" default="">
<cfparam name="attributes.siteCode"     type="string" default="">
<cfparam name="attributes.regionCode"   type="string" default="">

<!--- declaring outgoing variable --->
<cfparam name="attributes.variable"     type="string" default="your_query">

<!--- retrieve result --->
<cfquery name="Summary" datasource="#attributes.datasource#">
    SELECT
        *
    FROM
        disposal
    WHERE 1=1

    <cfif len(attributes.divisionCode) gt 0>
        AND DivisionCode = <cfqueryparam value="#attributes.divisionCode#" cfsqltype="cf_sql_varchar">
    </cfif>
    <cfif len(attributes.districtCode) gt 0>
        AND DistrictCode = <cfqueryparam value="#attributes.districtCode#" cfsqltype="cf_sql_varchar">
    </cfif>
    <cfif len(attributes.siteCode) gt 0>
        AND SiteCode = <cfqueryparam value="#attributes.siteCode#" cfsqltype="cf_sql_varchar">
    </cfif>
    <cfif len(attributes.regionCode) gt 0>
        AND RegionCode = <cfqueryparam value="#attributes.regionCode#" cfsqltype="cf_sql_varchar">
    </cfif>

    ORDER BY
        CYear DESC
</cfquery>

<!--- set outgoing variable --->
<cfset caller[attributes.variable] = Summary>
</code>```

invoking.cfm

```<code><cfmodule divisionCode="foo" regionCode="bar" variable="my_query" template="your_query.cfm">
<cfdump var="#my_query#">

<!--- or --->

<cfset params = {}>
<cfset params.siteCode = "bla">
<cfif structKeyExists(url, "regionCode")>
    <cfset params.regionCode = url.regionCode>
</cfif>

<cfmodule attributeCollection="#params#" template="your_query.cfm">
<cfdump var="#your_query#">

<!--- etc. --->
</code>```

The <cfmodule> tag isolates its content, meaning that no variables (except the ones assigned to the caller scope) within the your_query.cfm are visible to the calling template (invoking.cfm). This approach is basically what native CF tags like <cfhttp> and <cffile> do.

Function (more common)

```<code><cffunction name="yourQuery" access="public" output="false" returnType="query">

    <!--- declaring possible incoming parameters --->
    <cfargument name="datasource"   type="string" default="dsn">
    <cfargument name="divisionCode" type="string" default="">
    <cfargument name="districtCode" type="string" default="">
    <cfargument name="siteCode"     type="string" default="">
    <cfargument name="regionCode"   type="string" default="">

    <!--- retrieve result (the local. scope makes the variable exist in this function only) --->
    <cfquery name="local.Summary" datasource="#arguments.datasource#">
        SELECT
            *
        FROM
            disposal
        WHERE 1=1

        <cfif len(arguments.divisionCode) gt 0>
            AND DivisionCode = <cfqueryparam value="#arguments.divisionCode#" cfsqltype="cf_sql_varchar">
        </cfif>
        <cfif len(arguments.districtCode) gt 0>
            AND DistrictCode = <cfqueryparam value="#arguments.districtCode#" cfsqltype="cf_sql_varchar">
        </cfif>
        <cfif len(arguments.siteCode) gt 0>
            AND SiteCode = <cfqueryparam value="#arguments.siteCode#" cfsqltype="cf_sql_varchar">
        </cfif>
        <cfif len(arguments.regionCode) gt 0>
            AND RegionCode = <cfqueryparam value="#arguments.regionCode#" cfsqltype="cf_sql_varchar">
        </cfif>

        ORDER BY
            CYear DESC
    </cfquery>

    <!--- return result --->
    <cfreturn local.Summary>
</cffunction>
</code>```

invoking.cfm

```<code><cfset my_query = yourQuery("dsn", "foo", "", "bar")>
<cfdump var="#my_query#">

<!--- or --->

<cfset your_query = yourQuery(
    datasource: "dsn",
    siteCode: "bla"
    regionCode: ( structKeyExists(url, "regionCode") ? url.regionCode : "" )
)>
<cfdump var="#your_query#">

<!--- etc. --->
</code>```

That should give you an idea about what you can achieve.

Title: ColdFusion Dynamic SQL with cfif

Body:
I'm trying to write a query which would accept 1 of 4 possible parameters passed from another page.  The user would select one of these parameters to search on and then the query would evaluate which of those was selected based on the passed parameter.  I'm trying to use a cfif to accomplish this but I must be missing something.  Maybe a cfelse, and OR, or maybe I'm way off.  Would this be better as cffunction? I get an error "variable DivisionCode" is undefined.  Thank you.

<cfquery name="Summary" datasource="dsn">
    SELECT
        *
    FROM
        disposal
    WHERE 1=1

    <cfif DivisionCode NEQ "false">
    AND DivisionCode = <cfqueryparam value="#url.DivisionCode#"
   cfsqltype="cf_sql_varchar">
   </cfif>
   <cfif DistrictCode NEQ "false">
    AND DistrictCode = <cfqueryparam value="#url.DistrictCode#"
   cfsqltype="cf_sql_varchar">
   </cfif>
   <cfif SiteCode NEQ "false">
    AND SiteCode = <cfqueryparam value="#url.SiteCode#"
   cfsqltype="cf_sql_varchar">
  </cfif>
  <cfif RegionCode NEQ "false">
    AND RegionCode = <cfqueryparam value="#url.RegionCode#"
  cfsqltype="cf_sql_varchar">
  </cfif>
  ORDER By
    CYear DESC
  </cfquery>

Body:
Two options come to my mind: You can either make it work like an include or call it as a function.

Isolated Include (less common)

your_query.cfm

<!--- declaring possible incoming parameters --->
<cfparam name="attributes.datasource"   type="string" default="dsn">
<cfparam name="attributes.divisionCode" type="string" default="">
<cfparam name="attributes.districtCode" type="string" default="">
<cfparam name="attributes.siteCode"     type="string" default="">
<cfparam name="attributes.regionCode"   type="string" default="">

<!--- declaring outgoing variable --->
<cfparam name="attributes.variable"     type="string" default="your_query">

<!--- retrieve result --->
<cfquery name="Summary" datasource="#attributes.datasource#">
    SELECT
        *
    FROM
        disposal
    WHERE 1=1

    <cfif len(attributes.divisionCode) gt 0>
        AND DivisionCode = <cfqueryparam value="#attributes.divisionCode#" cfsqltype="cf_sql_varchar">
    </cfif>
    <cfif len(attributes.districtCode) gt 0>
        AND DistrictCode = <cfqueryparam value="#attributes.districtCode#" cfsqltype="cf_sql_varchar">
    </cfif>
    <cfif len(attributes.siteCode) gt 0>
        AND SiteCode = <cfqueryparam value="#attributes.siteCode#" cfsqltype="cf_sql_varchar">
    </cfif>
    <cfif len(attributes.regionCode) gt 0>
        AND RegionCode = <cfqueryparam value="#attributes.regionCode#" cfsqltype="cf_sql_varchar">
    </cfif>

    ORDER BY
        CYear DESC
</cfquery>

<!--- set outgoing variable --->
<cfset caller[attributes.variable] = Summary>

invoking.cfm

<cfmodule divisionCode="foo" regionCode="bar" variable="my_query" template="your_query.cfm">
<cfdump var="#my_query#">

<!--- or --->

<cfset params = {}>
<cfset params.siteCode = "bla">
<cfif structKeyExists(url, "regionCode")>
    <cfset params.regionCode = url.regionCode>
</cfif>

<cfmodule attributeCollection="#params#" template="your_query.cfm">
<cfdump var="#your_query#">

<!--- etc. --->

The <cfmodule> tag isolates its content, meaning that no variables (except the ones assigned to the caller scope) within the your_query.cfm are visible to the calling template (invoking.cfm). This approach is basically what native CF tags like <cfhttp> and <cffile> do.

Function (more common)

<cffunction name="yourQuery" access="public" output="false" returnType="query">

    <!--- declaring possible incoming parameters --->
    <cfargument name="datasource"   type="string" default="dsn">
    <cfargument name="divisionCode" type="string" default="">
    <cfargument name="districtCode" type="string" default="">
    <cfargument name="siteCode"     type="string" default="">
    <cfargument name="regionCode"   type="string" default="">

    <!--- retrieve result (the local. scope makes the variable exist in this function only) --->
    <cfquery name="local.Summary" datasource="#arguments.datasource#">
        SELECT
            *
        FROM
            disposal
        WHERE 1=1

        <cfif len(arguments.divisionCode) gt 0>
            AND DivisionCode = <cfqueryparam value="#arguments.divisionCode#" cfsqltype="cf_sql_varchar">
        </cfif>
        <cfif len(arguments.districtCode) gt 0>
            AND DistrictCode = <cfqueryparam value="#arguments.districtCode#" cfsqltype="cf_sql_varchar">
        </cfif>
        <cfif len(arguments.siteCode) gt 0>
            AND SiteCode = <cfqueryparam value="#arguments.siteCode#" cfsqltype="cf_sql_varchar">
        </cfif>
        <cfif len(arguments.regionCode) gt 0>
            AND RegionCode = <cfqueryparam value="#arguments.regionCode#" cfsqltype="cf_sql_varchar">
        </cfif>

        ORDER BY
            CYear DESC
    </cfquery>

    <!--- return result --->
    <cfreturn local.Summary>
</cffunction>

invoking.cfm

<cfset my_query = yourQuery("dsn", "foo", "", "bar")>
<cfdump var="#my_query#">

<!--- or --->

<cfset your_query = yourQuery(
    datasource: "dsn",
    siteCode: "bla"
    regionCode: ( structKeyExists(url, "regionCode") ? url.regionCode : "" )
)>
<cfdump var="#your_query#">

<!--- etc. --->

That should give you an idea about what you can achieve.


问:
Is there a Java interface that only have `get` `set` methods?
The get, set methods refer to array-like APIs, not getters or setters.

I've googled "java interface get set" and didn't get useful results -- it gives me information like getters or setters.

I've implemented a boolean array using bit compression, and I want know if there's an interface that only have get(int) and set(int, boolean).

答:
No there probably isn't.

My implementation is exactly the same as java.util.BitSet, which only implements Serializable and Cloneable.

This means there isn't such interface in the standard library.