问:
Convert Java Math.random to Swift 4
I was wondering how I can convert the below java code to Swift 4.

```<code>int randomNoteIndex = myArray[0] + (int) (Math.random() * (myArray[1] - myArray[0] + 1));
</code>```

Here is what i tried but I always get the same number myArray[0] everytime

```<code> let randomNoteIndex = myArray[0] +  Int(arc4random_uniform(1) * (UInt32(myArray[1]) - UInt32(myArray[0]) + UInt32(1)))
</code>```

答:
lowerBound + (int) (Math.random() * (upperBound - lowerBound + 1)) returns a uniformly distributed random number in range [lowerBound, upperBound].

arc4random_uniform(upperBound) returns a uniformly distributed random number less than upperBound. Thus what you're asking should be:

```<code>lowerBound + arc4random_uniform(upperBound - lowerBound + 1)
</code>```

As Jacob stated, arc4random_uniform(myArray.count) returns a random "index", not number in range. Probably he deduced this from the naming of your variable.

Title: Convert Java Math.random to Swift 4

Body:
I was wondering how I can convert the below java code to Swift 4.

int randomNoteIndex = myArray[0] + (int) (Math.random() * (myArray[1] - myArray[0] + 1));

Here is what i tried but I always get the same number myArray[0] everytime

 let randomNoteIndex = myArray[0] +  Int(arc4random_uniform(1) * (UInt32(myArray[1]) - UInt32(myArray[0]) + UInt32(1)))

Body:
lowerBound + (int) (Math.random() * (upperBound - lowerBound + 1)) returns a uniformly distributed random number in range [lowerBound, upperBound].

arc4random_uniform(upperBound) returns a uniformly distributed random number less than upperBound. Thus what you're asking should be:

lowerBound + arc4random_uniform(upperBound - lowerBound + 1)

As Jacob stated, arc4random_uniform(myArray.count) returns a random "index", not number in range. Probably he deduced this from the naming of your variable.


来源: stackexchange

问:
Is it possible to extract inline CSS from HTML?
Using http://simplehtmldom.sourceforge.net/manual.htm, is it possible to extract the inline CSS of a HTML file?

This parser if pure html, assuming (just correct me if I'm wrong) it can't parse CSS tags.Is there any other way to extract inline CSS in the html file?

答:
If you really need to use simplehtmldom to extract this :

For

```<code><style>
...
</style>
</code>```

Use :

```<code>$css = $html->find('style')->innertext;
</code>```

For

```<code><div style="background:blue; color:white;"></div>
</code>```

Use :

```<code>$css = $html->find('div[style]')->style;
</code>```

If there's more than one div with style atribute or more than one

ContentLicense: CC BY-SA 2.5

Body:
If you really need to use simplehtmldom to extract this :

For

<style>
...
</style>

Use :

$css = $html->find('style')->innertext;

For

<div style="background:blue; color:white;"></div>

Use :

$css = $html->find('div[style]')->style;

If there's more than one div with style atribute or more than one <style>, you can use a foreach to loop between them.

To parse styles :

in PHP :

$s = 'background:blue; color:white;';

$results = [];
$styles = explode(';', $s);

foreach ($styles as $style) {
    $properties = explode(':', $style);
    if (2 === count($properties)) {
        $results[trim($properties[0])] = trim($properties[1]);
    }
}

var_dump($results);

in JS

let s = 'background:blue; color:white;';

let results = {};
let styles = s.split(";");

for (let style in styles) {
    let properties = styles[style].split(":");
  if (properties.length === 2) {
    results[properties[0].trim()] = properties[1].trim();
  }
}

console.log(results);

https://jsfiddle.net/zyfhtwj2/

ContentLicense: CC BY-SA 4.0


问:
Swipe Delete in UItableviewCell
in my iPad app swipe deleting not working properly. after swipe deleting it shows the delete button on cell and this not disappearing.

答:
have you write canEditRowAt method?

```<code>func tableView(_ tableView: UITableView, canEditRowAt indexPath:
 IndexPath) -> Bool {
    // Return YES if you want the specified item to be editable.
    return true
}
</code>```

and then actual code to delete in this function

```<code>func tableView(_ tableView: UITableView, commit editingStyle:
  UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
       //add code here for delete action
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Swipe Delete in UItableviewCell

Body:
have you write canEditRowAt method?

func tableView(_ tableView: UITableView, canEditRowAt indexPath:
 IndexPath) -> Bool {
    // Return YES if you want the specified item to be editable.
    return true
}

and then actual code to delete in this function

func tableView(_ tableView: UITableView, commit editingStyle:
  UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
       //add code here for delete action
    }
}


问:
Join and count number of values in each subcategory
Lets say a have a data frame that looks like this:

```<code> V290   V311
0   GOOD    TOP QUARTER
1   NK-UNASCERTAIN  MIDDLE HALF
2   AVERAGE TOP QUARTER
3   POOR    NK-UNASCERTAIN
4   POOR    MIDDLE HALF
5   GOOD    MIDDLE HALF
6   POOR    TOP QUARTER
7   AVERAGE MIDDLE HALF
8   POOR    MIDDLE HALF
9   AVERAGE MIDDLE HALF
10  POOR    MIDDLE HALF
11  POOR    MIDDLE HALF
12  AVERAGE MIDDLE HALF
13  AVERAGE TOP QUARTER
</code>```

And i want to group this data by ['V311'] and see how many GOOD or POOR would be in Every ['V311'] Subcategory.
I want to make something like this:

```<code>  Top Quarter:GOOD:12
              POOR:30
              Average:15
  Middle half:GOOD:5
              POOR:19
              Average:3
</code>```

And so on...

答:
Using only pandas:

```<code>import pandas as pd
dataframe = pd.DataFrame()
dataframe['V311'] = ['MIDDLE','TOP','MIDDLE','TOP','MIDDLE','TOP','TOP']
print(dataframe['V311'].value_counts())
</code>```

output:

```<code>TOP       4
MIDDLE    3
Name: V311, dtype: int64
</code>```

Body:
Lets say a have a data frame that looks like this:

 V290   V311
0   GOOD    TOP QUARTER
1   NK-UNASCERTAIN  MIDDLE HALF
2   AVERAGE TOP QUARTER
3   POOR    NK-UNASCERTAIN
4   POOR    MIDDLE HALF
5   GOOD    MIDDLE HALF
6   POOR    TOP QUARTER
7   AVERAGE MIDDLE HALF
8   POOR    MIDDLE HALF
9   AVERAGE MIDDLE HALF
10  POOR    MIDDLE HALF
11  POOR    MIDDLE HALF
12  AVERAGE MIDDLE HALF
13  AVERAGE TOP QUARTER

And i want to group this data by ['V311'] and see how many GOOD or POOR would be in Every ['V311'] Subcategory.
I want to make something like this:

  Top Quarter:GOOD:12
              POOR:30
              Average:15
  Middle half:GOOD:5
              POOR:19
              Average:3

And so on...

Body:
Using only pandas:

import pandas as pd
dataframe = pd.DataFrame()
dataframe['V311'] = ['MIDDLE','TOP','MIDDLE','TOP','MIDDLE','TOP','TOP']
print(dataframe['V311'].value_counts())

output:

TOP       4
MIDDLE    3
Name: V311, dtype: int64


问:
app.EnterText() doesn`t enter text to entry in Android 7 and higher in XamarinUiTest
I successfully ran my test on:

physical Android 5.1;

Android 6.0.1 emulator;

testCloud devices 5.1, 5.1.1, 6.0.1

But when I try to run my UITest on Android emulator 7.0 and in testCloud on android devices 7 and higher, it ignores app.EnterText() method
It taps into Username entry then it must enter text into it but it doesn`t do it and taps into Password entry without any text entering. How can I solve this issue with Android 7?

```<code>[Test]
public void Android_7()
{
    app.WaitForElement(c => c.Marked("UsernameId"));
    app.Tap(c => c.Marked("UsernameId"));
    app.EnterText(c => c.Marked("UsernameId"), "www");
    app.Tap(c => c.Marked("PasswordId"));
    app.EnterText(c => c.Marked("PasswordId"), "testpsswd");
    app.Screenshot("Logining");
    app.Tap(c => c.Marked("SIGN IN"));
    app.WaitForElement(c => c.Marked("Exigo"));
    app.Screenshot("Dashboard");
}
</code>```

答:
Try this:
app.Tap (c => c.Marked ("UsernameId"));
app.EnterText ("www");

It is better not to specify for EnterText field in which you enter text, sometimes it is buggy and not called

Body:
I successfully ran my test on:

physical Android 5.1;

Android 6.0.1 emulator;

testCloud devices 5.1, 5.1.1, 6.0.1

But when I try to run my UITest on Android emulator 7.0 and in testCloud on android devices 7 and higher, it ignores app.EnterText() method
It taps into Username entry then it must enter text into it but it doesn`t do it and taps into Password entry without any text entering. How can I solve this issue with Android 7?

[Test]
public void Android_7()
{
    app.WaitForElement(c => c.Marked("UsernameId"));
    app.Tap(c => c.Marked("UsernameId"));
    app.EnterText(c => c.Marked("UsernameId"), "www");
    app.Tap(c => c.Marked("PasswordId"));
    app.EnterText(c => c.Marked("PasswordId"), "testpsswd");
    app.Screenshot("Logining");
    app.Tap(c => c.Marked("SIGN IN"));
    app.WaitForElement(c => c.Marked("Exigo"));
    app.Screenshot("Dashboard");
}


问:
How can I appen integer to url script inline thymeleaf?
I'm using Thymeleaf and Spring Boot.
I have a table create using these scripts: http://bootstrap-table.wenzhixin.net.cn/

Then I added a javascript:

```<code><script th:inline="javascript">
    /*<![CDATA[*/
    $(function() {
        $("#list").on('click-row.bs.table',
        function(e, row, $element, field) {
            window.location = /*[[@{/url/}]]*/+row.id;
        });
    });
    /*]]>*/
</script>
</code>```

As you can see I added the /*[[@{/url/}]]*/ to genereate the correct url, but I have to concatenate it with the id.

The problem is that it never append the id to the url.. why?
How can I fix it?

答:
You can put Thymeleaf Java object in some javascript variable first and then use it like you would normally do in javascript.

```<code>var url = /*[[@{/url/}]]*/
window.location = url + row.id;
</code>```

From 12.2 Script inlining (JavaScript and Dart) documentation:

Thymeleaf will execute the expression and insert the result, but it
  will also remove all the code in the line after the inline expression
  itself (the part that is executed when displayed statically).

Body:
I'm using Thymeleaf and Spring Boot.
I have a table create using these scripts: http://bootstrap-table.wenzhixin.net.cn/

Then I added a javascript:

As you can see I added the /*[[@{/url/}]]*/ to genereate the correct url, but I have to concatenate it with the id.

The problem is that it never append the id to the url.. why?
How can I fix it?

Body:
You can put Thymeleaf Java object in some javascript variable first and then use it like you would normally do in javascript.

var url = /*[[@{/url/}]]*/
window.location = url + row.id;

From 12.2 Script inlining (JavaScript and Dart) documentation:

Thymeleaf will execute the expression and insert the result, but it
  will also remove all the code in the line after the inline expression
  itself (the part that is executed when displayed statically).


问:
How to override appsettings.json for different OS?
My project is simple WebApi server, based on netcoreapp2.0.

I have simple appsettings.json

```<code>{
  "logPath":"C:\logs\myLog.log"
}
</code>```

And it's logPath ok, if app will work on Windows platform, but i want also run it on linux. I know, that i can use console args or enviroment variables for override this setting, but i want to get OS specific override for appsettings.json. Something like appsettings.linux.json (may be appsettings file, that depends on RID) with content

```<code>{
  "logPath":"\var\tmp\myLog.log"
}
</code>```

Ideally if this theoretical appsettings.linux.json will only included in build output, if i will build my app for specific RID.

How can i do that if it available?

答:
You can create multiple appsettings files.

appsettings.windows.json

  appsettings.linux.json

then use an EnvironmentName variable to swap between them.

Startup

```<code>var builder = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
</code>```

the default appsettings.json file is loaded first if there is an {env.EnvironmentName} set then it will load that one.  I use this for swapping between Dev, test and production environments.

Body:
My project is simple WebApi server, based on netcoreapp2.0.

I have simple appsettings.json

{
  "logPath":"C:\logs\myLog.log"
}

And it's logPath ok, if app will work on Windows platform, but i want also run it on linux. I know, that i can use console args or enviroment variables for override this setting, but i want to get OS specific override for appsettings.json. Something like appsettings.linux.json (may be appsettings file, that depends on RID) with content

{
  "logPath":"\var\tmp\myLog.log"
}

Ideally if this theoretical appsettings.linux.json will only included in build output, if i will build my app for specific RID.

How can i do that if it available?

Body:
You can create multiple appsettings files.

appsettings.windows.json

  appsettings.linux.json

then use an EnvironmentName variable to swap between them.

Startup

var builder = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

the default appsettings.json file is loaded first if there is an {env.EnvironmentName} set then it will load that one.  I use this for swapping between Dev, test and production environments.


问:
C# Unit Test to test attributes of properties of Dto
I have following Dto with some attributes to validate the properties. When I am passing some invalid values of properties, my unit test allows those values without validating as per the given condition of attributes. I am doing this first time so I have zero ideas to achieve it.</p>

```<code>public class UserDto : IModelWithId
{
    public int Id { get; set; }
    [MinLength(1, ErrorMessageResourceName = "Error_User_UsernameMinLength", ErrorMessageResourceType = typeof(Properties.Resources))]
    [MaxLength(255, ErrorMessageResourceName = "Error_User_UsernameMaxLength", ErrorMessageResourceType = typeof(Properties.Resources))]
    [RegularExpression(@"^[A-Za-z0-9äöüÄÖÜß]+(?:[._-][A-Za-z0-9äöüÄÖÜß]+)*$", ErrorMessageResourceName = "Error_User_UsernameFormat", ErrorMessageResourceType = typeof(Properties.Resources))]
    public string UserName { get; set; }

    [MinLength(1, ErrorMessageResourceName = "Error_User_NameMinLength", ErrorMessageResourceType = typeof(Properties.Resources))]
    [MaxLength(255, ErrorMessageResourceName = "Error_User_NameMaxLength", ErrorMessageResourceType = typeof(Properties.Resources))]
    public string Name { get; set; }

    [MinLength(1, ErrorMessageResourceName = "Error_User_EmailMinLength", ErrorMessageResourceType = typeof(Properties.Resources))]
    [MaxLength(255, ErrorMessageResourceName = "Error_User_EmailMaxLength", ErrorMessageResourceType = typeof(Properties.Resources))]
    [EmailAddress(ErrorMessageResourceName = "Error_User_EmailAddress", ErrorMessageResourceType = typeof(Properties.Resources))]
    public string Email { get; set; }
}
</code>```

答:
You can use validator class to validate your dto:

```<code>var dto = new UserDto();
dto.Email = "not an email";
var ctx = new System.ComponentModel.DataAnnotations.ValidationContext(dto);
// will throw an exception if invalid
System.ComponentModel.DataAnnotations.Validator.ValidateObject(dto, ctx, true);
</code>```

or without exception like this:

```<code>var result = new List<ValidationResult>();
if (!Validator.TryValidateObject(dto, ctx, result)) {
    // inspect `result` list for specific validation errors
}
</code>```

Body:
I have following Dto with some attributes to validate the properties. When I am passing some invalid values of properties, my unit test allows those values without validating as per the given condition of attributes. I am doing this first time so I have zero ideas to achieve it.

public class UserDto : IModelWithId
{
    public int Id { get; set; }
    [MinLength(1, ErrorMessageResourceName = "Error_User_UsernameMinLength", ErrorMessageResourceType = typeof(Properties.Resources))]
    [MaxLength(255, ErrorMessageResourceName = "Error_User_UsernameMaxLength", ErrorMessageResourceType = typeof(Properties.Resources))]
    [RegularExpression(@"^[A-Za-z0-9äöüÄÖÜß]+(?:[._-][A-Za-z0-9äöüÄÖÜß]+)*$", ErrorMessageResourceName = "Error_User_UsernameFormat", ErrorMessageResourceType = typeof(Properties.Resources))]
    public string UserName { get; set; }

    [MinLength(1, ErrorMessageResourceName = "Error_User_NameMinLength", ErrorMessageResourceType = typeof(Properties.Resources))]
    [MaxLength(255, ErrorMessageResourceName = "Error_User_NameMaxLength", ErrorMessageResourceType = typeof(Properties.Resources))]
    public string Name { get; set; }

    [MinLength(1, ErrorMessageResourceName = "Error_User_EmailMinLength", ErrorMessageResourceType = typeof(Properties.Resources))]
    [MaxLength(255, ErrorMessageResourceName = "Error_User_EmailMaxLength", ErrorMessageResourceType = typeof(Properties.Resources))]
    [EmailAddress(ErrorMessageResourceName = "Error_User_EmailAddress", ErrorMessageResourceType = typeof(Properties.Resources))]
    public string Email { get; set; }
}

Body:
You can use validator class to validate your dto:

var dto = new UserDto();
dto.Email = "not an email";
var ctx = new System.ComponentModel.DataAnnotations.ValidationContext(dto);
// will throw an exception if invalid
System.ComponentModel.DataAnnotations.Validator.ValidateObject(dto, ctx, true);

or without exception like this:

var result = new List<ValidationResult>();
if (!Validator.TryValidateObject(dto, ctx, result)) {
    // inspect `result` list for specific validation errors
}


问:
Missing System.Net.Http after upgrading Visual Studio to 15.5
We've got an existing solution consisting of an ASP.NET MVC project and a bunch of libraries, all of the projects are targeting .NET 4.6.1.

After upgrading Visual Studio from 15.3 to 15.5 I get a few compile errors stating that it can't find the System.Net.Http assembly.

The type 'HttpResponseMessage' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

I read the release notes but I could not find anything that would cause this issue. Why would upgrading Visual Studio from 15.3 to 15.5 result in these errors?

答: Try updating the System.Net.Http nuget to make sure that you have the latest version</p>


问:
Loading a large amount of images to be displayed in a WrapPanel
I am using Entity Framework Code First

I have a Movie like so:

```<code>public class Movie
{
        public byte[] Thumbnail { get; set; }
        public int MovieId { get; set; }
}
</code>```

And a Collection of Movies like so:

```<code>public class NorthwindContext : DbContext
{
    public DbSet<Movie> Movies { get; set; }
}
</code>```

I have a MovieViewModel like so:

```<code>public class MovieViewModel
{
        private readonly Movie _movie;

        public MovieViewModel(Movie movie)
        {
            _movieModel = movieModel;
        }

        public byte[] Thumbnail { get { return _movie.Thumbnail; } }
}
</code>```

When my App starts:

```<code>public ObservableCollection<MovieViewModel> MovieVms =
                      new ObservableCollection<MovieViewModel>();

foreach (var movie in MyDbContext.Movies)
     MovieVms.Add(new MovieViewModel(movie));
</code>```

I have 4000 movies. This process takes 25 seconds.  Is there a better/faster way to do this?

My main page uses the thumbnails like so, but to be clear this loading time happens before anything UI related:

```<code>MyView = new ListCollectionView(MovieVms);

<ListBox ItemsSource="{Binding MyView}" />
</code>```

Also my memory usage goes through the roof.  How should I be loading these images?  I need a full collection of view models off the bat to enable sorting, filtering, searching, but I only need the thumbnails of the items visible in my wrap panel.

EDIT---

Thanks Dave for a great answer. Can you elaborate on "make it an association (aka navigation property)"

```<code>var thumbnail = new Thumbnail();
thumbnail.Data = movie.GetThumbnail();
Globals.DbContext.Thumbnails.Add(thumbnail);
Globals.DbContext.SaveChanges();
movie.ThumbnailId = thumbnail.ThumbnailId;
Globals.DbContext.SaveChanges();
</code>```

I can run that code with no errors, but my property in my MovieViewModel

```<code>public new byte[] Thumbnail { get { return _movie.Thumbnail.Data; } }
</code>```

always has a null Thumbnail and errors as soon as my UI accesses it. A breakpoint on movie.ThumbnailId is never hit. Do I have to load the association manually?

答:
I was having issues with the answer when applied to a ListBox whose ItemsSource is dynamic. In that case, when the source is modified, the ScrollViewer is not necessarily, the trigger is not fired and the images are not loaded.

My main issue concerns the lazy loading lots of highres images in a UniformGrid (which is not virtualized).

To overcome this, I applied a Behavior on ListBoxItem. I find it is a good solution too because you do not have to subclass the ScrollViewer and change the ListBox's Template but only ListBoxItem's.

Add a behavior to your project :

```<code>namespace behaviors
{
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Interactivity;
    using System.Windows.Media;

    public class ListBoxItemIsVisibleBehavior : Behavior<ListBoxItem>
    {
        public static readonly DependencyProperty IsInViewportProperty = DependencyProperty.RegisterAttached("IsInViewport", typeof(bool), typeof(ListBoxItemIsVisibleBehavior));

        public static bool GetIsInViewport(UIElement element)
        {
            return (bool)element.GetValue(IsInViewportProperty);
        }

        public static void SetIsInViewport(UIElement element, bool value)
        {
            element.SetValue(IsInViewportProperty, value);
        }

        protected override void OnAttached()
        {
            base.OnAttached();

            try
            {
                this.AssociatedObject.LayoutUpdated += this.AssociatedObject_LayoutUpdated;
            }
            catch { }
        }

        protected override void OnDetaching()
        {
            try
            {
                this.AssociatedObject.LayoutUpdated -= this.AssociatedObject_LayoutUpdated;
            }
            catch { }

            base.OnDetaching();
        }

        private void AssociatedObject_LayoutUpdated(object sender, System.EventArgs e)
        {
            if (this.AssociatedObject.IsVisible == false)
            {
                SetIsInViewport(this.AssociatedObject, false);
                return;
            }

            var container = WpfExtensions.FindParent<ListBox>(this.AssociatedObject);
            if (container == null)
            {
                return;
            }

            var visible = this.IsVisibleToUser(this.AssociatedObject, container) == true;
            SetIsInViewport(this.AssociatedObject, visible);
        }

        private bool IsVisibleToUser(FrameworkElement element, FrameworkElement container)
        {
            if (element.IsVisible == false)
            {
                return false;
            }

            GeneralTransform transform = element.TransformToAncestor(container);
            Rect bounds = transform.TransformBounds(new Rect(0.0, 0.0, element.ActualWidth, element.ActualHeight));
            Rect viewport = new Rect(0.0, 0.0, container.ActualWidth, container.ActualHeight);
            return viewport.IntersectsWith(bounds);
        }
    }
}
</code>```

Then you would have to use this answer in order to add a behavior to your ListBoxItem style : How to add a Blend Behavior in a Style Setter

This leads to add a helper in your project :

```<code>public class Behaviors : List<Behavior>
{
}

public static class SupplementaryInteraction
{
    public static Behaviors GetBehaviors(DependencyObject obj)
    {
        return (Behaviors)obj.GetValue(BehaviorsProperty);
    }

    public static void SetBehaviors(DependencyObject obj, Behaviors value)
    {
        obj.SetValue(BehaviorsProperty, value);
    }

    public static readonly DependencyProperty BehaviorsProperty =
        DependencyProperty.RegisterAttached("Behaviors", typeof(Behaviors), typeof(SupplementaryInteraction), new UIPropertyMetadata(null, OnPropertyBehaviorsChanged));

    private static void OnPropertyBehaviorsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var behaviors = Interaction.GetBehaviors(d);
        foreach (var behavior in e.NewValue as Behaviors) behaviors.Add(behavior);
    }
}
</code>```

Then add the behavior in a resource somewhere in your control :

```<code><UserControl.Resources>
    <behaviors:Behaviors x:Key="behaviors" x:Shared="False">
        <behaviors:ListBoxItemIsVisibleBehavior />
    </behaviors:Behaviors>
</UserControl.Resources>
</code>```

And a reference of this resource and a trigger to the style of your ListBoxItem :

```<code><Style x:Key="_ListBoxItemStyle" TargetType="ListBoxItem">
    <Setter Property="behaviors:SupplementaryInteraction.Behaviors" Value="{StaticResource behaviors}"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ListBoxItem">
                <StackPanel d:DataContext="{d:DesignInstance my:MovieViewModel}">
                    <Image x:Name="Thumbnail" Stretch="Fill" Width="100" Height="100" />
                    <TextBlock Text="{Binding Name}" />
                </StackPanel>

                <ControlTemplate.Triggers>
                    <DataTrigger Binding="{Binding Path=(behaviors:ListBoxItemIsVisibleBehavior.IsInViewport), RelativeSource={RelativeSource Self}}"
                                 Value="True">
                        <Setter TargetName="Thumbnail"
                                Property="Source"
                                Value="{Binding Thumbnail}" />
                    </DataTrigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

And reference the style in your ListBox :

```<code><ListBox ItemsSource="{Binding Movies}"
         Style="{StaticResource _ListBoxItemStyle}">
</ListBox>
</code>```

In the case of a UniformGrid :

```<code><ListBox ItemsSource="{Binding Movies}"
         Style="{StaticResource _ListBoxItemStyle}">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns="5" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>
</code>```

Body:
I am using Entity Framework Code First

I have a Movie like so:

public class Movie
{
        public byte[] Thumbnail { get; set; }
        public int MovieId { get; set; }
}

And a Collection of Movies like so:

public class NorthwindContext : DbContext
{
    public DbSet<Movie> Movies { get; set; }
}

I have a MovieViewModel like so:

public class MovieViewModel
{
        private readonly Movie _movie;

        public MovieViewModel(Movie movie)
        {
            _movieModel = movieModel;
        }

        public byte[] Thumbnail { get { return _movie.Thumbnail; } }
}

When my App starts:

public ObservableCollection<MovieViewModel> MovieVms =
                      new ObservableCollection<MovieViewModel>();

foreach (var movie in MyDbContext.Movies)
     MovieVms.Add(new MovieViewModel(movie));

I have 4000 movies. This process takes 25 seconds.  Is there a better/faster way to do this?

My main page uses the thumbnails like so, but to be clear this loading time happens before anything UI related:

MyView = new ListCollectionView(MovieVms);

<ListBox ItemsSource="{Binding MyView}" />

Also my memory usage goes through the roof.  How should I be loading these images?  I need a full collection of view models off the bat to enable sorting, filtering, searching, but I only need the thumbnails of the items visible in my wrap panel.

EDIT---

Thanks Dave for a great answer. Can you elaborate on "make it an association (aka navigation property)"

var thumbnail = new Thumbnail();
thumbnail.Data = movie.GetThumbnail();
Globals.DbContext.Thumbnails.Add(thumbnail);
Globals.DbContext.SaveChanges();
movie.ThumbnailId = thumbnail.ThumbnailId;
Globals.DbContext.SaveChanges();

I can run that code with no errors, but my property in my MovieViewModel

public new byte[] Thumbnail { get { return _movie.Thumbnail.Data; } }

always has a null Thumbnail and errors as soon as my UI accesses it. A breakpoint on movie.ThumbnailId is never hit. Do I have to load the association manually?

Body:
I was having issues with the answer when applied to a ListBox whose ItemsSource is dynamic. In that case, when the source is modified, the ScrollViewer is not necessarily, the trigger is not fired and the images are not loaded.

My main issue concerns the lazy loading lots of highres images in a UniformGrid (which is not virtualized).

To overcome this, I applied a Behavior on ListBoxItem. I find it is a good solution too because you do not have to subclass the ScrollViewer and change the ListBox's Template but only ListBoxItem's.

Add a behavior to your project :

namespace behaviors
{
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Interactivity;
    using System.Windows.Media;

    public class ListBoxItemIsVisibleBehavior : Behavior<ListBoxItem>
    {
        public static readonly DependencyProperty IsInViewportProperty = DependencyProperty.RegisterAttached("IsInViewport", typeof(bool), typeof(ListBoxItemIsVisibleBehavior));

        public static bool GetIsInViewport(UIElement element)
        {
            return (bool)element.GetValue(IsInViewportProperty);
        }

        public static void SetIsInViewport(UIElement element, bool value)
        {
            element.SetValue(IsInViewportProperty, value);
        }

        protected override void OnAttached()
        {
            base.OnAttached();

            try
            {
                this.AssociatedObject.LayoutUpdated += this.AssociatedObject_LayoutUpdated;
            }
            catch { }
        }

        protected override void OnDetaching()
        {
            try
            {
                this.AssociatedObject.LayoutUpdated -= this.AssociatedObject_LayoutUpdated;
            }
            catch { }

            base.OnDetaching();
        }

        private void AssociatedObject_LayoutUpdated(object sender, System.EventArgs e)
        {
            if (this.AssociatedObject.IsVisible == false)
            {
                SetIsInViewport(this.AssociatedObject, false);
                return;
            }

            var container = WpfExtensions.FindParent<ListBox>(this.AssociatedObject);
            if (container == null)
            {
                return;
            }

            var visible = this.IsVisibleToUser(this.AssociatedObject, container) == true;
            SetIsInViewport(this.AssociatedObject, visible);
        }

        private bool IsVisibleToUser(FrameworkElement element, FrameworkElement container)
        {
            if (element.IsVisible == false)
            {
                return false;
            }

            GeneralTransform transform = element.TransformToAncestor(container);
            Rect bounds = transform.TransformBounds(new Rect(0.0, 0.0, element.ActualWidth, element.ActualHeight));
            Rect viewport = new Rect(0.0, 0.0, container.ActualWidth, container.ActualHeight);
            return viewport.IntersectsWith(bounds);
        }
    }
}

Then you would have to use this answer in order to add a behavior to your ListBoxItem style : How to add a Blend Behavior in a Style Setter

This leads to add a helper in your project :

public class Behaviors : List<Behavior>
{
}

public static class SupplementaryInteraction
{
    public static Behaviors GetBehaviors(DependencyObject obj)
    {
        return (Behaviors)obj.GetValue(BehaviorsProperty);
    }

    public static void SetBehaviors(DependencyObject obj, Behaviors value)
    {
        obj.SetValue(BehaviorsProperty, value);
    }

    public static readonly DependencyProperty BehaviorsProperty =
        DependencyProperty.RegisterAttached("Behaviors", typeof(Behaviors), typeof(SupplementaryInteraction), new UIPropertyMetadata(null, OnPropertyBehaviorsChanged));

    private static void OnPropertyBehaviorsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var behaviors = Interaction.GetBehaviors(d);
        foreach (var behavior in e.NewValue as Behaviors) behaviors.Add(behavior);
    }
}

Then add the behavior in a resource somewhere in your control :

<UserControl.Resources>
    <behaviors:Behaviors x:Key="behaviors" x:Shared="False">
        <behaviors:ListBoxItemIsVisibleBehavior />
    </behaviors:Behaviors>
</UserControl.Resources>

And a reference of this resource and a trigger to the style of your ListBoxItem :

<Style x:Key="_ListBoxItemStyle" TargetType="ListBoxItem">
    <Setter Property="behaviors:SupplementaryInteraction.Behaviors" Value="{StaticResource behaviors}"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ListBoxItem">
                <StackPanel d:DataContext="{d:DesignInstance my:MovieViewModel}">
                    <Image x:Name="Thumbnail" Stretch="Fill" Width="100" Height="100" />
                    <TextBlock Text="{Binding Name}" />
                </StackPanel>

                <ControlTemplate.Triggers>
                    <DataTrigger Binding="{Binding Path=(behaviors:ListBoxItemIsVisibleBehavior.IsInViewport), RelativeSource={RelativeSource Self}}"
                                 Value="True">
                        <Setter TargetName="Thumbnail"
                                Property="Source"
                                Value="{Binding Thumbnail}" />
                    </DataTrigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

And reference the style in your ListBox :

<ListBox ItemsSource="{Binding Movies}"
         Style="{StaticResource _ListBoxItemStyle}">
</ListBox>

In the case of a UniformGrid :

<ListBox ItemsSource="{Binding Movies}"
         Style="{StaticResource _ListBoxItemStyle}">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns="5" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>


问:
MySQL: bigint Vs int
I have been using int(10) and just noticed that Wordpress uses bigint(20) - What is different to use bigint(20) and int(10) for id auto increment? Which one should I use for id column?

```<code>`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
</code>```

Vs

```<code>`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
</code>```

Thanks.

答:
The only difference is the range of the type. INT is a 32-bit long while BIGINT is 64-bit long, therefore it can store much larger numbers like 123456789123456789 (which cannot be stored as INT).

Here's a full list of MySQL integer types: http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html

Title: MySQL: bigint Vs int

Body:
I have been using int(10) and just noticed that Wordpress uses bigint(20) - What is different to use bigint(20) and int(10) for id auto increment? Which one should I use for id column?

`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,

Vs

`id` int(10) unsigned NOT NULL AUTO_INCREMENT,

Thanks.


问:
How to use chromecast without using extension
google cast provides sample github links, which uses default cast extension to cast the data by registering from developer console, but how to use this sender/receiver application without using chrome extension by auto detecting the device and cast the data, is there any specific tutorials to follow up?</p>

答:
I've been working on a project that uses a similar approach like the one you're asking about and I came across a couple of repo's on github that helped me along the way but there isn't so much on the internet about it.

Basically you can communicate with the Google cast device without relying on the google extension by applying two steps.

Discover the device on the local network by using a service discovery service such as Bonjure or MDNS, here's a sample repo on github that uses a pure JavaScript implementation.

Communicate with the Google cast device over the network by using google's CASTV2 protocol over TLS and here's one of the most popular implementations can be found here on this github repo and also here's a high level implementation of the same library these libraries are also in written in JavaScript.


问:
Is it safe to compare DOM nodes with "==="?
My prerequisite is, that I work with just one DOM and use just the DOM API like getElementById or querySelector or event references. Is it in this case safe to use the following condition

```<code>if (document.body === event.currentTarget) { }
</code>```

to check if the event has been bubbled to the body of the document?

I know that this will not work with cloned objects. But I do not clone any objects by myself. Does the the DOM API clone objects anywhere?

答:
Yes, this is safe. DOM objects aren't replaced by the browser, they're fairly stable objects.

I myself frequently use WeakMaps to bind data to elements without problems (example).

Body:
My prerequisite is, that I work with just one DOM and use just the DOM API like getElementById or querySelector or event references. Is it in this case safe to use the following condition

if (document.body === event.currentTarget) { }

to check if the event has been bubbled to the body of the document?

I know that this will not work with cloned objects. But I do not clone any objects by myself. Does the the DOM API clone objects anywhere?


问:
Emacs: `C-h k` is undefined
I am new to EMACS. I want to know the command bound with C-x f, so I type C-h k. But it won't work ,and shows me C-h k is undefined.

And my EMACS version is 26.0.90.

答:
As shown in the following figure: enter image description here

You can see a key sequence C-h k

Otherwise, Look at what you are。

Title: Emacs: `C-h k` is undefined


问:
new Function() with variable parameters
I need to create a function with variable number of parameters using new Function() constructor. Something like this:

```<code>args = ['a', 'b'];
body = 'return(a + b);';

myFunc = new Function(args, body);
</code>```

Is it possible to do it without eval()?

Thank you very much, guys! Actually, a+b was not my primary concern. I'm working on a code which would process and expand templates and I needed to pass unknown (and variable) number of arguments into the function so that they would be introduced as local variables.

For example, if a template contains:

```<code><span> =a </span>
</code>```

I need to output the value of parameter a. That is, if user declared expanding function as

```<code>var expand = tplCompile('template', a, b, c)
</code>```

and then calls

```<code>expand(4, 2, 1)
</code>```

I need to substitute =a with 4. And yes, I'm well aware than Function is similar to eval() and runs very slow but I don't have any other choice.

答:
In this sample i used lodash:</p>

```<code>function _evalExp(exp, scope) {
  const k = [null].concat(_.keys(scope));
  k.push('return '+exp);
  const args = _.map(_.keys(scope), function(a) {return scope[a];});
  const func = new (Function.prototype.bind.apply(Function, k));
  return func.apply(func, args);
}

_evalExp('a+b+c', {a:10, b:20, c:30});
</code>```

Title: new Function() with variable parameters

Body:
I need to create a function with variable number of parameters using new Function() constructor. Something like this:

args = ['a', 'b'];
body = 'return(a + b);';

myFunc = new Function(args, body);

Is it possible to do it without eval()?

Thank you very much, guys! Actually, a+b was not my primary concern. I'm working on a code which would process and expand templates and I needed to pass unknown (and variable) number of arguments into the function so that they would be introduced as local variables.

For example, if a template contains:

 =a

I need to output the value of parameter a. That is, if user declared expanding function as

var expand = tplCompile('template', a, b, c)

and then calls

expand(4, 2, 1)

I need to substitute =a with 4. And yes, I'm well aware than Function is similar to eval() and runs very slow but I don't have any other choice.

Body:
In this sample i used lodash:

function _evalExp(exp, scope) {
  const k = [null].concat(_.keys(scope));
  k.push('return '+exp);
  const args = _.map(_.keys(scope), function(a) {return scope[a];});
  const func = new (Function.prototype.bind.apply(Function, k));
  return func.apply(func, args);
}

_evalExp('a+b+c', {a:10, b:20, c:30});


问:
YII2 - how to render a view inside active-form
i'm trying to render view from another controller in active form when creating new data. my purpose is only for reference when render the view. how to achieve this in yii2?
ilustration like this : active form in controller-B/create and there is a button to view the modal (controller-A/list) and select data what user want and then render a view beside active form (controller-A/view?id=xx).

答:
Controller

```<code>$view = $this->render('view', [
    'model' => $this->findModel($id),
]);

return json_encode($view);
</code>```

HTML

```<code><div class="row">
    <div class="col-sm-4">
        // ActiveForm code here
    </div>
    <div class="col-sm-8" id="whatever" style="display:none"> // initially hidden
       // render another view here
   </div>
</code>```

Jquery

```<code>$(document).on('click', '.select-row', function(){
   var id = $(this).attr('data-id');
   $.get('../pengiriman-produksi/get-data', {id : id}, function(data){
       var data = $.parseJSON(data);
       $('#whatever').show();
       $('#whatever').html(data);
   });
   $('#modalPengiriman').modal('hide');
});
</code>```

Body:
Controller

$view = $this->render('view', [
    'model' => $this->findModel($id),
]);

return json_encode($view);

HTML

<div class="row">
    <div class="col-sm-4">
        // ActiveForm code here
    </div>
    <div class="col-sm-8" id="whatever" style="display:none"> // initially hidden
       // render another view here
   </div>

Jquery

$(document).on('click', '.select-row', function(){
   var id = $(this).attr('data-id');
   $.get('../pengiriman-produksi/get-data', {id : id}, function(data){
       var data = $.parseJSON(data);
       $('#whatever').show();
       $('#whatever').html(data);
   });
   $('#modalPengiriman').modal('hide');
});


问:
how to make a checkbox category bar in codeigniter
I made a function in CodeIgniter so someone clicks on a category in the category side bar it will link to a new page with that category id and show all the products that have the same category id.

Now what I want is that you can select multiple categories with checkboxes at the same time on the same page but I don't know how to do it.

Here I'm linking the category sidebar on the view page:

```<code><div class="categorieen">
      <?php foreach (get_categories_h() as $category) : ?>
  <input id="box1" type="checkbox" />
  <label for="box1"><a class="listcat" href="<?php echo base_url().'Product/category/' . $category->id; ?>"> <?php echo $category->name; ?></a></label>
  <?php endforeach; ?>
</div>
</code>```

With db_helper.php file I'm getting categories from database:

```<code><?php if (!function_exists('get_categories_h')) {
    function get_categories_h(){
        $CI = get_instance();
        $categories = $CI->Product_model->get_categories();
        return $categories;
    } } ?>
</code>```

Category_model find function :

```<code><?php

class Category_model extends CI_Model {

    public function find($id)
          {
              $this->db->where('id',$id );
              return $this->db->get('categories')->row();
          }

}

?>
</code>```

functions in Product_model:

```<code>/** Zoek alle products in table products met deze functie (word gebruikt voor categorieen) **/
    public function findAll(){
        return $this->db->get('products')->result();
    }

     /** Zoek category_id in table products  **/
       public function findByCategory($category_id)
       {
            $this->db->where('category_id', $category_id);
            return $this->db->get('products')->result();
          }
</code>```

So yeah how can I change my code so instead of linking it to another page the user must be able to select multiple categories and show the products on the same page?

答:
You can bind the ajax call (call to the controller/action) to the change event of checkbox.

1) You can then fetch the products related to the checked categories and then return the required product details, build the HTML (client side) and replace the new HTML of products.

2) You can also build the HTML from the server side, you can return the HTML from the server side.

```<code>$this->load->view('product_html_file', $products,TRUE);
</code>```

The above will return the HTML of the section you want to replace.Send it to the ajax response and replace the section

Hope this helps.

Body:
I made a function in CodeIgniter so someone clicks on a category in the category side bar it will link to a new page with that category id and show all the products that have the same category id.

Now what I want is that you can select multiple categories with checkboxes at the same time on the same page but I don't know how to do it.

Here I'm linking the category sidebar on the view page:

      <?php foreach (get_categories_h() as $category) : ?>
  <input id="box1" type="checkbox" />
  <a class="listcat" href="<?php echo base_url().'Product/category/' . $category->id; ?>"> <?php echo $category->name; ?>
  <?php endforeach; ?>

With db_helper.php file I'm getting categories from database:

<?php if (!function_exists('get_categories_h')) {
    function get_categories_h(){
        $CI = get_instance();
        $categories = $CI->Product_model->get_categories();
        return $categories;
    } } ?>

Category_model find function :

<?php

class Category_model extends CI_Model {

    public function find($id)
          {
              $this->db->where('id',$id );
              return $this->db->get('categories')->row();
          }

}

?>

functions in Product_model:

/** Zoek alle products in table products met deze functie (word gebruikt voor categorieen) **/
    public function findAll(){
        return $this->db->get('products')->result();
    }

     /** Zoek category_id in table products  **/
       public function findByCategory($category_id)
       {
            $this->db->where('category_id', $category_id);
            return $this->db->get('products')->result();
          }

So yeah how can I change my code so instead of linking it to another page the user must be able to select multiple categories and show the products on the same page?

Body:
You can bind the ajax call (call to the controller/action) to the change event of checkbox.

1) You can then fetch the products related to the checked categories and then return the required product details, build the HTML (client side) and replace the new HTML of products.

2) You can also build the HTML from the server side, you can return the HTML from the server side.

$this->load->view('product_html_file', $products,TRUE);

The above will return the HTML of the section you want to replace.Send it to the ajax response and replace the section

Hope this helps.


问:
app:transformDexArchiveWithExternalLibsDexMergerForDebug
hi guys i get this error when i try to run my app

Error:Execution failed for task
':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

i don't know why!

I tried also to clean and rebuild project but i get always the same error!

Now i post my gradle:

```<code>android {
    compileSdkVersion 23
    buildToolsVersion '26.0.2'

    defaultConfig {
        applicationId "com.compscitutorials.basigarcia.navigationdrawervideotutorial"
        minSdkVersion 19
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'    }
}

dependencies {
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    //noinspection GradleCompatible
    compile 'com.android.support:appcompat-v7:23.1.0'
    compile 'com.android.support:design:23.1.1'
    compile 'de.hdodenhof:circleimageview:1.3.0'
    //noinspection GradleCompatible
    compile 'com.android.support:recyclerview-v7:26.1.0'
    //noinspection GradleCompatible
    compile 'com.android.support:cardview-v7:26.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.github.bumptech.glide:glide:3.8.0'
    //compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.android.exoplayer:exoplayer:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-core:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-dash:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-hls:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-smoothstreaming:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-ui:r2.4.0'
    compile 'com.facebook.android:facebook-android-sdk:3.21.1'
    //noinspection DuplicatePlatformClasses
    implementation 'org.apache.httpcomponents:httpclient:4.5.3'
}
</code>```

答:
You should Upgrade old versions

```<code>compile 'com.android.support:appcompat-v7:26.1.0'
compile 'com.android.support:design:26.1.1'
compile 'com.facebook.android:facebook-android-sdk:4.16.0'
compile 'de.hdodenhof:circleimageview:2.2.0'
</code>```

And set

compileSdkVersion 26

After that, Clean-Rebuild-Run.

Body:
hi guys i get this error when i try to run my app

Error:Execution failed for task
':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

i don't know why!

I tried also to clean and rebuild project but i get always the same error!

Now i post my gradle:

android {
    compileSdkVersion 23
    buildToolsVersion '26.0.2'

    defaultConfig {
        applicationId "com.compscitutorials.basigarcia.navigationdrawervideotutorial"
        minSdkVersion 19
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'    }
}

dependencies {
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    //noinspection GradleCompatible
    compile 'com.android.support:appcompat-v7:23.1.0'
    compile 'com.android.support:design:23.1.1'
    compile 'de.hdodenhof:circleimageview:1.3.0'
    //noinspection GradleCompatible
    compile 'com.android.support:recyclerview-v7:26.1.0'
    //noinspection GradleCompatible
    compile 'com.android.support:cardview-v7:26.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.github.bumptech.glide:glide:3.8.0'
    //compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.android.exoplayer:exoplayer:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-core:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-dash:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-hls:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-smoothstreaming:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-ui:r2.4.0'
    compile 'com.facebook.android:facebook-android-sdk:3.21.1'
    //noinspection DuplicatePlatformClasses
    implementation 'org.apache.httpcomponents:httpclient:4.5.3'
}

Body:
You should Upgrade old versions

compile 'com.android.support:appcompat-v7:26.1.0'
compile 'com.android.support:design:26.1.1'
compile 'com.facebook.android:facebook-android-sdk:4.16.0'
compile 'de.hdodenhof:circleimageview:2.2.0'

And set

compileSdkVersion 26

After that, Clean-Rebuild-Run.


问:
Guarantee Multiple Instances of an Object
I really don't know how to proper name this question. I have a certain scenario where I have an object that should be disposed of whenever used. The reasons for this are twofold:

I must guarantee that every member variable (field) is initialized before any new use.

I must guarantee that there aren't two methods of this object being called at the same time, since it's not thread-safe.

Both reasons could be covered in the object, having every public method lock the same mutex and initializing every variable on a private method, which is also called on every public method.

This solution is error prone and has a side effect of serializing the access on a multi-thread scenario, since I'll be locking the object before use. Of course, the call site could then create a new instance before calling a method (removing the side effect), but it's also error prone.

So I came up with a solution that I find both clean and very weird:

My object expose static methods, that have as parameters the variables necessary to both create a new instance of the object and execute the method. This static method create a instance of the object and then call the necessary method.

Of course, the constructor is private.

The first thing that I noticed when looking at this solution is that my object is looking a lot like a procedural method, of course, since every new method call requires a new object. But the responsibilities of the object fits nicely this scheme.

My questions (finally!, I know) are:

Is there a pattern that would adhere to my requirements (always using a new instance of an object)?

Is there a pattern describing my approach? Or is it a anti-pattern?

Besides the fact that the object seems like a collection of procedural functions, is there any other reason for me not having this approach?

Thanks for any comments.

答:
As with your explanation it is just a class syntax wrapping of old procedural functions. this is actually not a class of Objects. I don't think there exist any OOP pattern involving non-OOP programming like this (except the Singleton?).

What's the point of the design like this with added memory/performance overhead of creating and destroying the one-time use object inside the functions?

By the way, you could split up the class in two classes. One for resource holding the other for operation on the resources. Let clients decide the most appropriate resource management scheme and pass the resource holding object to the methods of the operation class.


问:
JAVA - SCANNER to get user input
I have the following block code:

```<code>    boolean run = true;
    while (run) {
        Scanner scanner = new Scanner(System.in);
        // do something

        System.out.println("Another action? [Y/N]");
        while (!scanner.hasNext("[YyNn]")) {
            System.out.println("Incorrect input");
            scanner.next();
        }
        String choice = scanner.next();
        if (choice.toLowerCase().equals("f"))
            run = false;

        scanner.close();
    }
</code>```

I want to perform something until the user types 'N'.
Currently, I'm able to run the while loop only one time.
The second time I'm not able to type my choice and I have the following error:

```<code>Another action? [Y/N]     <--- here no chance to type choice
Incorrect input
java.util.NoSuchElementException
    at java.util.Scanner.throwFor
    at java.util.Scanner.next
</code>```

What is wrong?
Thanks

EDIT: I think my problem is in "do something". It is in turn a sequence of user input where i close the scanner.

答:
If you call the scanner.close() method ,System.in will be closed.
So Use this. Close the scanner outside the loop.

```<code>public static void main(String[] args) {
        boolean run = true;
        Scanner scanner = new Scanner(System.in);;
        while(run){
                    // do something

                    System.out.println("Another action? [Y/N]");
                    while (!scanner.hasNext("[YyNn]")) {
                        System.out.println("Incorrect input");
                        scanner.next();
                    }
                    String choice = scanner.next();
                    if(choice.toLowerCase().equals("f"))
                        run = false;

    //

        }
          scanner.close();
    }
</code>```

Output

```<code>Another action? [Y/N]
Y
Another action? [Y/N]
Y
Another action? [Y/N]
N
Another action? [Y/N]
N
Another action? [Y/N]
test
Incorrect input
</code>```

Title: JAVA - SCANNER to get user input

Body:
I have the following block code:

    boolean run = true;
    while (run) {
        Scanner scanner = new Scanner(System.in);
        // do something

        System.out.println("Another action? [Y/N]");
        while (!scanner.hasNext("[YyNn]")) {
            System.out.println("Incorrect input");
            scanner.next();
        }
        String choice = scanner.next();
        if (choice.toLowerCase().equals("f"))
            run = false;

        scanner.close();
    }

I want to perform something until the user types 'N'.
Currently, I'm able to run the while loop only one time.
The second time I'm not able to type my choice and I have the following error:

Another action? [Y/N]     <--- here no chance to type choice
Incorrect input
java.util.NoSuchElementException
    at java.util.Scanner.throwFor
    at java.util.Scanner.next

What is wrong?
Thanks

EDIT: I think my problem is in "do something". It is in turn a sequence of user input where i close the scanner.

Body:
If you call the scanner.close() method ,System.in will be closed.
So Use this. Close the scanner outside the loop.

public static void main(String[] args) {
        boolean run = true;
        Scanner scanner = new Scanner(System.in);;
        while(run){
                    // do something

                    System.out.println("Another action? [Y/N]");
                    while (!scanner.hasNext("[YyNn]")) {
                        System.out.println("Incorrect input");
                        scanner.next();
                    }
                    String choice = scanner.next();
                    if(choice.toLowerCase().equals("f"))
                        run = false;

    //

        }
          scanner.close();
    }

Output

Another action? [Y/N]
Y
Another action? [Y/N]
Y
Another action? [Y/N]
N
Another action? [Y/N]
N
Another action? [Y/N]
test
Incorrect input


问:
SQL right join between tables
I have three tables where I want to perform a join between them.

1st table looks like (named users)

```<code>id      column1
1       1
2       2
3       3
</code>```

2nd table looks like (named transactions) here we have some transactions of users

```<code>user_id      transaction_date      transaction_expire
1            2017-03-31            2017-05-16
1            2017-02-28            2017-04-16
</code>```

3rd table looks like (named user_logs) we have logs of the users based on days

```<code>user_id      date          some_log_data
1            2017-03-07    1505
1            2017-03-03    1201
1            2017-03-22    942
1            2017-03-31    1490
1            2017-04-05    1490
</code>```

I want to know the sum of every user based on transactions something like:

```<code>user_id     transaction_date    transaction_expire    log
1           2017-03-31          2017-05-16            2980
1           2017-02-28          2017-04-16            6628
</code>```

So this is the result which I want to achieve for every use get the SUM of their log in all transactions.

By doing this query between transaction_date and transaction_expire I get some result but when I try to do the summation the result are for all of them:

```<code>SELECT t.transaction_date, t.transaction_expire, ul.log
FROM user_logs as ul
    RIGHT JOIN transactions as t ON ul.user_id= t.user_id
WHERE ul.date BETWEEN t.transaction_date AND t.transaction_expire
</code>```

This query gives me 7 rows which is correct but now I want to find only the sum of the logs in these two different transactions.

答:
Your query is basically correct, but you need aggregation:

```<code>SELECT t.transaction_date, t.transaction_expire, SUM(ul.log)
FROM transactions t LEFT JOIN
     user_logs ul
     ON ul.user_id = t.user_id AND
        ul.date BETWEEN t.transaction_date AND t.transaction_expire
GROUP BY t.transaction_date, t.transaction_expire;
</code>```

Also note that the condition in the WHERE clause is moved to the ON clause. I switched the JOIN to a LEFT JOIN.  I find LEFT JOIN much more intuitive than RIGHT JOIN, because it keeps all rows in the first table.

Title: SQL right join between tables

Body:
I have three tables where I want to perform a join between them.

1st table looks like (named users)

id      column1
1       1
2       2
3       3

2nd table looks like (named transactions) here we have some transactions of users

user_id      transaction_date      transaction_expire
1            2017-03-31            2017-05-16
1            2017-02-28            2017-04-16

3rd table looks like (named user_logs) we have logs of the users based on days

user_id      date          some_log_data
1            2017-03-07    1505
1            2017-03-03    1201
1            2017-03-22    942
1            2017-03-31    1490
1            2017-04-05    1490

I want to know the sum of every user based on transactions something like:

user_id     transaction_date    transaction_expire    log
1           2017-03-31          2017-05-16            2980
1           2017-02-28          2017-04-16            6628

So this is the result which I want to achieve for every use get the SUM of their log in all transactions.

By doing this query between transaction_date and transaction_expire I get some result but when I try to do the summation the result are for all of them:

SELECT t.transaction_date, t.transaction_expire, ul.log
FROM user_logs as ul
    RIGHT JOIN transactions as t ON ul.user_id= t.user_id
WHERE ul.date BETWEEN t.transaction_date AND t.transaction_expire

This query gives me 7 rows which is correct but now I want to find only the sum of the logs in these two different transactions.

Body:
Your query is basically correct, but you need aggregation:

SELECT t.transaction_date, t.transaction_expire, SUM(ul.log)
FROM transactions t LEFT JOIN
     user_logs ul
     ON ul.user_id = t.user_id AND
        ul.date BETWEEN t.transaction_date AND t.transaction_expire
GROUP BY t.transaction_date, t.transaction_expire;

Also note that the condition in the WHERE clause is moved to the ON clause. I switched the JOIN to a LEFT JOIN.  I find LEFT JOIN much more intuitive than RIGHT JOIN, because it keeps all rows in the first table.


问:
Intellij Idea - can't run a simple java class even though the main method is declared
I'm a self-taught coder who is new to both Java & Intellij Idea. I wanted to run a simple Java class called payroll in Intellij Idea Ultimate 2017.3

```<code>public class payroll {
  public static void main(String[] args) {
    int hours = 50;
    double grossPay, payRate = 25.0;

    grossPay = hours * payRate;
    System.out.println("your gross pay is $" + grossPay);}
  }
</code>```

Unfortunately IDEA detects some errors indicating that it can't resolve symbols "String" and "System". And when I tried Run/Edit Configuration, the IDE stated that the main method isn't found in the class, but obviously it is declared already

I've used Eclipse & Netbeans before and things just went smoothly then. Can anyone please point out the main cause of this nuisance for me and how to work it out?

答:
If core Java lang (java.lang.*) classes cannot be resolved you may need to define the JDK you want to use with IDEA. Here is a link to how to define the JDK (Java Development Kit) you want to use for your project(s): LINK.

You may also need to confirm the JDK path is correct by navigating to the folder and ensuring the JDK version you are using is indeed located there.

Hope this helps!

Body:
I'm a self-taught coder who is new to both Java & Intellij Idea. I wanted to run a simple Java class called payroll in Intellij Idea Ultimate 2017.3

public class payroll {
  public static void main(String[] args) {
    int hours = 50;
    double grossPay, payRate = 25.0;

    grossPay = hours * payRate;
    System.out.println("your gross pay is $" + grossPay);}
  }

Unfortunately IDEA detects some errors indicating that it can't resolve symbols "String" and "System". And when I tried Run/Edit Configuration, the IDE stated that the main method isn't found in the class, but obviously it is declared already

I've used Eclipse & Netbeans before and things just went smoothly then. Can anyone please point out the main cause of this nuisance for me and how to work it out?


答:
I think you should change some lines of code like this </p>

```<code>        Scanner scanner = new Scanner(System.in);

        char choice = 'Y'

        while(choice!='n'){

          // do something

          System.out.print("Another action? [Y/N]");

          choice = scanner.nextLine().toLowerCase().charAt(0);

          if(choice!='y' || choice!='n'){

              continue;

          }

        }

        scanner.close();
</code>```

Title: JAVA - SCANNER to get user input

Body:
I think you should change some lines of code like this

        Scanner scanner = new Scanner(System.in);

        char choice = 'Y'

        while(choice!='n'){

          // do something

          System.out.print("Another action? [Y/N]");

          choice = scanner.nextLine().toLowerCase().charAt(0);

          if(choice!='y' || choice!='n'){

              continue;

          }

        }

        scanner.close();


问:
Running jest in a monorepo with create-react-app packages
Here is a question.

I'm trying to merge some of my packages into a monorepo. I'm using yarn and it's workspaces-experimental feature. So the repository folder structure looks like:

```<code>.
node_modules
packages
  myapp1
  myapp2
  myreactapp1
</code>```

Now, one of the goals is to simplify testing. I want to run jest in the root dir so that it runs unit tests for all the packages. And it works for myapp1 and myapp2 above which are node.js apps. However, myreactapp1 is build with create-react-app (no eject) and uses ES6 features (like import) and also jsdom rendering. The tests work fine if I run them from myreactapp1 dir with yarn test which pipes the code through babel (if I understand well). But the root jest failes on the first import statement.

How can I do it ?

P.S. I tried to install babel-jest but seems that it cannot be lauched directly from the console (windows).

答:
It seems that CRA does not yet work properly with Yarn Workspaces. A workaround is suggested in the comments.

Anyway, to make jest work, you need to have babel-jest (as you said) and also a .babelrc file in the root folder:

```<code>{
  "presets": ["es2015", "react"]
}
</code>```

Body:
Here is a question.

I'm trying to merge some of my packages into a monorepo. I'm using yarn and it's workspaces-experimental feature. So the repository folder structure looks like:

.
node_modules
packages
  myapp1
  myapp2
  myreactapp1

Now, one of the goals is to simplify testing. I want to run jest in the root dir so that it runs unit tests for all the packages. And it works for myapp1 and myapp2 above which are node.js apps. However, myreactapp1 is build with create-react-app (no eject) and uses ES6 features (like import) and also jsdom rendering. The tests work fine if I run them from myreactapp1 dir with yarn test which pipes the code through babel (if I understand well). But the root jest failes on the first import statement.

How can I do it ?

P.S. I tried to install babel-jest but seems that it cannot be lauched directly from the console (windows).

Body:
It seems that CRA does not yet work properly with Yarn Workspaces. A workaround is suggested in the comments.

Anyway, to make jest work, you need to have babel-jest (as you said) and also a .babelrc file in the root folder:

{
  "presets": ["es2015", "react"]
}


问:
Plot one stacked bar from more different dataframes in python Pandas
I need to plot data like this:

```<code>df1
id  value
ba1  4
ba2  5
ba3  5

df2
   id     value
ba1, ba3  4
ba2       3
ba2, ba3  2
ba3       5

df3
     id       value
ba1, ba3       3
ba1, ba3, ba4  1
ba2            3
ba2, ba3       2
ba3            4
ba3, ba4       1
</code>```

Every df has the same sum of value, 14. I think that would be a stacked bar plot good solution, with one bar per df, where values would be presented in percent.
But I have no idea how to do from three different data frames. Everything I found there it was for the more numeric-value column from one df.
Any help is welcomed. Thanks in advance.

The desired output would be something like this:
example but in X would be name of dataframe

答:
Something like this should work:</p>

```<code>import pandas as pd
import matplotlib.pyplot as plt

df1 = {'id': ['ba1', 'ba2', 'ba3'], 'value': [4,5,5]}
df1 = pd.DataFrame(data=df1)
df1.set_index('id', inplace=True)

df2 = {'id': ['ba1, ba3', 'ba2', 'ba2, ba3', 'ba3'], 'value': [4,3,2,5]}
df2 = pd.DataFrame(data=df2)
df2.set_index('id', inplace=True)

df3 = {'id': ['ba1, ba3', 'ba1, ba3, ba4', 'ba2', 'ba2, ba3', 'ba3', 'ba3,\
ba4'], 'value': [3,1,3,2,4,1]}
df3 = pd.DataFrame(data=df3)
df3.set_index('id', inplace=True)

ax = plt.gca()
df1.T.plot(kind='bar', stacked=True, ax=ax, width=0.05, position=0)
df2.T.plot(kind='bar', stacked=True, ax=ax, width=0.05, position=1)
df3.T.plot(kind='bar', stacked=True, ax=ax, width=0.05, position=2)
plt.show()
</code>```

Body:
I need to plot data like this:

df1
id  value
ba1  4
ba2  5
ba3  5

df2
   id     value
ba1, ba3  4
ba2       3
ba2, ba3  2
ba3       5

df3
     id       value
ba1, ba3       3
ba1, ba3, ba4  1
ba2            3
ba2, ba3       2
ba3            4
ba3, ba4       1

Every df has the same sum of value, 14. I think that would be a stacked bar plot good solution, with one bar per df, where values would be presented in percent.
But I have no idea how to do from three different data frames. Everything I found there it was for the more numeric-value column from one df.
Any help is welcomed. Thanks in advance.

The desired output would be something like this:
example but in X would be name of dataframe

Body:
Something like this should work:

import pandas as pd
import matplotlib.pyplot as plt

df1 = {'id': ['ba1', 'ba2', 'ba3'], 'value': [4,5,5]}
df1 = pd.DataFrame(data=df1)
df1.set_index('id', inplace=True)

df2 = {'id': ['ba1, ba3', 'ba2', 'ba2, ba3', 'ba3'], 'value': [4,3,2,5]}
df2 = pd.DataFrame(data=df2)
df2.set_index('id', inplace=True)

df3 = {'id': ['ba1, ba3', 'ba1, ba3, ba4', 'ba2', 'ba2, ba3', 'ba3', 'ba3,\
ba4'], 'value': [3,1,3,2,4,1]}
df3 = pd.DataFrame(data=df3)
df3.set_index('id', inplace=True)

ax = plt.gca()
df1.T.plot(kind='bar', stacked=True, ax=ax, width=0.05, position=0)
df2.T.plot(kind='bar', stacked=True, ax=ax, width=0.05, position=1)
df3.T.plot(kind='bar', stacked=True, ax=ax, width=0.05, position=2)
plt.show()


问:
Extract strings from HTML
I have following  element:

```<code><div class="column4">
        Unlimited Subscription<br/> Discount for Monthly <br/> Total Amount
    </div>
</code>```

How can I extract three strings as three different elements with using Beautiful Soup only. String conversion and regexps can not be used:

Expected output:

```<code>Unlimited Subscription
Discount for Monthly
Total Amount
</code>```

答:
```<code>from bs4 import BeautifulSoup
html_doc = """<div class="column4">
        Unlimited Subscription<br/> Discount for Monthly <br/> Total Amount
    </div>
"""
soup = BeautifulSoup(html_doc, 'html.parser')
soup.find("div").text.strip()
</code>```

Title: Extract strings from HTML

Body:
I have following  element:

        Unlimited Subscription
 Discount for Monthly
 Total Amount

How can I extract three strings as three different elements with using Beautiful Soup only. String conversion and regexps can not be used:

Expected output:

Unlimited Subscription
Discount for Monthly
Total Amount


问:
MVC 3 - AntiForgeryConfig - Namespace Missing
I am getting error message 'The type or namespace name

'AntiForgeryConfig' does not exist in the namespace
  'System.Web.WebPages' (are you missing an assembly reference?)'

This happens when I try to add below code in Global.asax.cs file.

I have already included namespaces System.Web.Helpers and System.Web.WebPages.

```<code>AntiForgeryConfig.SuppressIdentityHeuristicChecks = true;
</code>```

Do I need to include any other namespace here?

答: What version of System.Web.WebPages are you using? AntiForgeryConfig isn't included in v1, so you might need to upgrade to v2 to be able to use it.</p>

Body:
I am getting error message 'The type or namespace name

'AntiForgeryConfig' does not exist in the namespace
  'System.Web.WebPages' (are you missing an assembly reference?)'

This happens when I try to add below code in Global.asax.cs file.

I have already included namespaces System.Web.Helpers and System.Web.WebPages.

AntiForgeryConfig.SuppressIdentityHeuristicChecks = true;

Do I need to include any other namespace here?


问:
MagicalRecord always faults - unable to read data
No matter what I try when I attempt to access a record returned from mr_findAll, data is always unable to be read.

Please understand I have to redact a bunch of information here so the code looks something like

```<code>var results: [Unit] = []

let predicate: NSPredicate? = NSPredicate(format: "abc == %@ AND def == %@", abc, def)

results = Unit.mr_findAll(with: predicate, in:NSManagedObjectContext.mr_default()) as! [Unit]
</code>```

Three results are returned which is what I expect; If I examine them in the console they look like:

po results

▿ 3 elements

0 : app.Unit: 0x6080002959a0> (entity: Unit; id: 0xd00000000004000a x-coredata://08DA3A42-AFDA-4280-A5B5-4E1267509CFC/Unit/p1> ; data: fault)

1 : app.Unit: 0x608000295b30> (entity: Unit; id: 0xd00000000008000a x-coredata://08DA3A42-AFDA-4280-A5B5-4E1267509CFC/Unit/p2> ; data: fault)

2 : app.Unit: 0x608000295d10> (entity: Unit; id: 0xd0000000000c000a x-coredata://08DA3A42-AFDA-4280-A5B5-4E1267509CFC/Unit/p3> ; data: fault)

I then try and access the results:

```<code>for result in results {
        let ghi = result.ghi
        let jkl = result.jkl
</code>```

At the first possible access to a member of results I get an EXC_BAD_INSTRUCTION and in the inspector I see unable to read data.

I tried numerous ways of 'offsetting' the access to a result as I've read that as soon as you access a member of a faulted record core data will fetch it but to no avail.

If I was using fetch requests I could stipulate

```<code>returnsObjectsAsFaults = false
</code>```

I can't see anything in the MagicalRecord interface which allows the above or something similar.

I'm looking really for

a technique that will ensure I don't get faults
OR

a technique that will absolutely resolve the fault.

Any help much appreciated.

答:
Using NSManagedObjectContext.mr_default() is not thread-safe. It is better to use local context, e.g.:</p>

```<code>var results: [Unit] = []
MagicalRecord.save(blockAndWait: { (localContext) in

    let predicate: NSPredicate? = NSPredicate(format: "abc == %@ AND def == %@", abc, def)
    results = Unit.mr_findAll(with: predicate, in:localContext) as! [Unit]
})
</code>```

Body:
No matter what I try when I attempt to access a record returned from mr_findAll, data is always unable to be read.

Please understand I have to redact a bunch of information here so the code looks something like

var results: [Unit] = []

let predicate: NSPredicate? = NSPredicate(format: "abc == %@ AND def == %@", abc, def)

results = Unit.mr_findAll(with: predicate, in:NSManagedObjectContext.mr_default()) as! [Unit]

Three results are returned which is what I expect; If I examine them in the console they look like:

po results

▿ 3 elements

0 : app.Unit: 0x6080002959a0> (entity: Unit; id: 0xd00000000004000a x-coredata://08DA3A42-AFDA-4280-A5B5-4E1267509CFC/Unit/p1> ; data: fault)

1 : app.Unit: 0x608000295b30> (entity: Unit; id: 0xd00000000008000a x-coredata://08DA3A42-AFDA-4280-A5B5-4E1267509CFC/Unit/p2> ; data: fault)

2 : app.Unit: 0x608000295d10> (entity: Unit; id: 0xd0000000000c000a x-coredata://08DA3A42-AFDA-4280-A5B5-4E1267509CFC/Unit/p3> ; data: fault)

I then try and access the results:

for result in results {
        let ghi = result.ghi
        let jkl = result.jkl

At the first possible access to a member of results I get an EXC_BAD_INSTRUCTION and in the inspector I see unable to read data.

I tried numerous ways of 'offsetting' the access to a result as I've read that as soon as you access a member of a faulted record core data will fetch it but to no avail.

If I was using fetch requests I could stipulate

returnsObjectsAsFaults = false

I can't see anything in the MagicalRecord interface which allows the above or something similar.

I'm looking really for

a technique that will ensure I don't get faults
OR

a technique that will absolutely resolve the fault.

Any help much appreciated.

Body:
Using NSManagedObjectContext.mr_default() is not thread-safe. It is better to use local context, e.g.:

var results: [Unit] = []
MagicalRecord.save(blockAndWait: { (localContext) in

    let predicate: NSPredicate? = NSPredicate(format: "abc == %@ AND def == %@", abc, def)
    results = Unit.mr_findAll(with: predicate, in:localContext) as! [Unit]
})


问:
MySQL: bigint Vs int
I have been using int(10) and just noticed that Wordpress uses bigint(20) - What is different to use bigint(20) and int(10) for id auto increment? Which one should I use for id column?

```<code>`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
</code>```

Vs

```<code>`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
</code>```

Thanks.

答:
The difference is purely in the maximum value which can be stored (18,446,744,073,709,551,615 for the bigint(20) and 4,294,967,295 for the int(10), I believe), as per the details on the MySQL Numeric Types manual page.

Incidentally, the use of (20) and (10) is largely irrelevant unless you're using ZEROFILL. (i.e.: It doesn't actually change the size of the number stored - that's all down to the type.)

However, in practical terms it should be noted that you're not likely to hit either of these limits any time soon, unless you're a really active blogger.

Title: MySQL: bigint Vs int

Body:
I have been using int(10) and just noticed that Wordpress uses bigint(20) - What is different to use bigint(20) and int(10) for id auto increment? Which one should I use for id column?

`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,

Vs

`id` int(10) unsigned NOT NULL AUTO_INCREMENT,

Thanks.


问:
HikariCP and maxLifetime
I moved my project to HikariCP. Everything is going fine so far, but with one setting I'm having trouble.

It's the .setMaxLifetime(30*1000) setting in HikariConfig object. I get this warning

```<code>WARN com.zaxxer.hikari.HikariConfig - maxLifetime is less than 120000ms, using default 1800000ms.
</code>```

I know that they recommend not setting is that low as I am trying to. But Unfortunately due to circumstances that I can not change, every TCP connection that is open longer than 50 secods will be terminated in our production environment.

答:
i don't know your HikariCP Version, but in the version 2.2.4 you will find the reason why it will throw the above warning.
HikariConfig.class (in the com.zaxxer.hikari.HikariConfig):

```<code> private void More ...validateNumerics()
  {
     Logger logger = LoggerFactory.getLogger(getClass());

     if (connectionTimeout == Integer.MAX_VALUE) {
        logger.warn("No connection wait timeout is set, this might cause an infinite wait.");
     }

     if (minIdle < 0 || minIdle > maxPoolSize) {
        minIdle = maxPoolSize;
     }

     if (maxLifetime < 0) {
        logger.error("maxLifetime cannot be negative.");
        throw new IllegalArgumentException("maxLifetime cannot be negative.");
     }
     else if (maxLifetime > 0 && maxLifetime < TimeUnit.SECONDS.toMillis(120)) {
        logger.warn("maxLifetime is less than 120000ms, using default {}ms.", MAX_LIFETIME);
        maxLifetime = MAX_LIFETIME;
     }

     if (idleTimeout != 0 && idleTimeout < TimeUnit.SECONDS.toMillis(30)) {
        logger.warn("idleTimeout is less than 30000ms, using default {}ms.", IDLE_TIMEOUT);
        idleTimeout = IDLE_TIMEOUT;
     }
     else if (idleTimeout > maxLifetime && maxLifetime > 0) {
        logger.warn("idleTimeout is greater than maxLifetime, setting to maxLifetime.");
        idleTimeout = maxLifetime;
     }
</code>```

from this code, the maxLifeTime is at least 120000ms, using default 1800000ms. so you can't set the maxLifeTime to 30000ms(30*1000). I guess your HikariCP version is at least older than 2.2.4.

But when you find the latest HikariCP version 2.7.4. it said "We strongly recommend setting this value, and it should be at least 30 seconds less than any database or infrastructure imposed connection time limit."

the same class HikariConfig.class:

```<code>private void validateNumerics() {
    if(this.maxLifetime != 0L && this.maxLifetime < TimeUnit.SECONDS.toMillis(30L)) {
        LOGGER.warn("{} - maxLifetime is less than 30000ms, setting to default {}ms.", this.poolName, Long.valueOf(MAX_LIFETIME));
        this.maxLifetime = MAX_LIFETIME;
    }

    if(this.idleTimeout + TimeUnit.SECONDS.toMillis(1L) > this.maxLifetime && this.maxLifetime > 0L) {
        LOGGER.warn("{} - idleTimeout is close to or more than maxLifetime, disabling it.", this.poolName);
        this.idleTimeout = 0L;
    }

    if(this.idleTimeout != 0L && this.idleTimeout < TimeUnit.SECONDS.toMillis(10L)) {
        LOGGER.warn("{} - idleTimeout is less than 10000ms, setting to default {}ms.", this.poolName, Long.valueOf(IDLE_TIMEOUT));
        this.idleTimeout = IDLE_TIMEOUT;
    }

    if(this.leakDetectionThreshold > 0L && !unitTest && (this.leakDetectionThreshold < TimeUnit.SECONDS.toMillis(2L) || this.leakDetectionThreshold > this.maxLifetime && this.maxLifetime > 0L)) {
        LOGGER.warn("{} - leakDetectionThreshold is less than 2000ms or more than maxLifetime, disabling it.", this.poolName);
        this.leakDetectionThreshold = 0L;
    }

    if(this.connectionTimeout < 250L) {
        LOGGER.warn("{} - connectionTimeout is less than 250ms, setting to {}ms.", this.poolName, Long.valueOf(CONNECTION_TIMEOUT));
        this.connectionTimeout = CONNECTION_TIMEOUT;
    }

    if(this.validationTimeout < 250L) {
        LOGGER.warn("{} - validationTimeout is less than 250ms, setting to {}ms.", this.poolName, Long.valueOf(VALIDATION_TIMEOUT));
        this.validationTimeout = VALIDATION_TIMEOUT;
    }

    if(this.maxPoolSize < 1) {
        this.maxPoolSize = this.minIdle <= 0?10:this.minIdle;
    }

    if(this.minIdle < 0 || this.minIdle > this.maxPoolSize) {
        this.minIdle = this.maxPoolSize;
    }

}
</code>```

from this code, the maxLifeTime has been updated to 30000ms at least in this version.

So now please update your HikariCP version to the latest version 2.7.4 if you want to set maxLifeTime to 30000ms.

But if you update your HikariCP version to 2.7.4 with JDK 8, i also recommend you two points:

1. to set maxLifeTime value to be at least 30000ms.

2. to set maxLifeTime value few minute less than mysql's wait_timeout(show variables like "%timeout%") to avoid broken connection exception.

Title: HikariCP and maxLifetime

Body:
I moved my project to HikariCP. Everything is going fine so far, but with one setting I'm having trouble.

It's the .setMaxLifetime(30*1000) setting in HikariConfig object. I get this warning

WARN com.zaxxer.hikari.HikariConfig - maxLifetime is less than 120000ms, using default 1800000ms.

I know that they recommend not setting is that low as I am trying to. But Unfortunately due to circumstances that I can not change, every TCP connection that is open longer than 50 secods will be terminated in our production environment.

Body:
i don't know your HikariCP Version, but in the version 2.2.4 you will find the reason why it will throw the above warning.
HikariConfig.class (in the com.zaxxer.hikari.HikariConfig):

 private void More ...validateNumerics()
  {
     Logger logger = LoggerFactory.getLogger(getClass());

     if (connectionTimeout == Integer.MAX_VALUE) {
        logger.warn("No connection wait timeout is set, this might cause an infinite wait.");
     }

     if (minIdle < 0 || minIdle > maxPoolSize) {
        minIdle = maxPoolSize;
     }

     if (maxLifetime < 0) {
        logger.error("maxLifetime cannot be negative.");
        throw new IllegalArgumentException("maxLifetime cannot be negative.");
     }
     else if (maxLifetime > 0 && maxLifetime < TimeUnit.SECONDS.toMillis(120)) {
        logger.warn("maxLifetime is less than 120000ms, using default {}ms.", MAX_LIFETIME);
        maxLifetime = MAX_LIFETIME;
     }

     if (idleTimeout != 0 && idleTimeout < TimeUnit.SECONDS.toMillis(30)) {
        logger.warn("idleTimeout is less than 30000ms, using default {}ms.", IDLE_TIMEOUT);
        idleTimeout = IDLE_TIMEOUT;
     }
     else if (idleTimeout > maxLifetime && maxLifetime > 0) {
        logger.warn("idleTimeout is greater than maxLifetime, setting to maxLifetime.");
        idleTimeout = maxLifetime;
     }

from this code, the maxLifeTime is at least 120000ms, using default 1800000ms. so you can't set the maxLifeTime to 30000ms(30*1000). I guess your HikariCP version is at least older than 2.2.4.

But when you find the latest HikariCP version 2.7.4. it said "We strongly recommend setting this value, and it should be at least 30 seconds less than any database or infrastructure imposed connection time limit."

the same class HikariConfig.class:

private void validateNumerics() {
    if(this.maxLifetime != 0L && this.maxLifetime < TimeUnit.SECONDS.toMillis(30L)) {
        LOGGER.warn("{} - maxLifetime is less than 30000ms, setting to default {}ms.", this.poolName, Long.valueOf(MAX_LIFETIME));
        this.maxLifetime = MAX_LIFETIME;
    }

    if(this.idleTimeout + TimeUnit.SECONDS.toMillis(1L) > this.maxLifetime && this.maxLifetime > 0L) {
        LOGGER.warn("{} - idleTimeout is close to or more than maxLifetime, disabling it.", this.poolName);
        this.idleTimeout = 0L;
    }

    if(this.idleTimeout != 0L && this.idleTimeout < TimeUnit.SECONDS.toMillis(10L)) {
        LOGGER.warn("{} - idleTimeout is less than 10000ms, setting to default {}ms.", this.poolName, Long.valueOf(IDLE_TIMEOUT));
        this.idleTimeout = IDLE_TIMEOUT;
    }

    if(this.leakDetectionThreshold > 0L && !unitTest && (this.leakDetectionThreshold < TimeUnit.SECONDS.toMillis(2L) || this.leakDetectionThreshold > this.maxLifetime && this.maxLifetime > 0L)) {
        LOGGER.warn("{} - leakDetectionThreshold is less than 2000ms or more than maxLifetime, disabling it.", this.poolName);
        this.leakDetectionThreshold = 0L;
    }

    if(this.connectionTimeout < 250L) {
        LOGGER.warn("{} - connectionTimeout is less than 250ms, setting to {}ms.", this.poolName, Long.valueOf(CONNECTION_TIMEOUT));
        this.connectionTimeout = CONNECTION_TIMEOUT;
    }

    if(this.validationTimeout < 250L) {
        LOGGER.warn("{} - validationTimeout is less than 250ms, setting to {}ms.", this.poolName, Long.valueOf(VALIDATION_TIMEOUT));
        this.validationTimeout = VALIDATION_TIMEOUT;
    }

    if(this.maxPoolSize < 1) {
        this.maxPoolSize = this.minIdle <= 0?10:this.minIdle;
    }

    if(this.minIdle < 0 || this.minIdle > this.maxPoolSize) {
        this.minIdle = this.maxPoolSize;
    }

}

from this code, the maxLifeTime has been updated to 30000ms at least in this version.

So now please update your HikariCP version to the latest version 2.7.4 if you want to set maxLifeTime to 30000ms.

But if you update your HikariCP version to 2.7.4 with JDK 8, i also recommend you two points:

1. to set maxLifeTime value to be at least 30000ms.

2. to set maxLifeTime value few minute less than mysql's wait_timeout(show variables like "%timeout%") to avoid broken connection exception.


问:
Get only properties count for java class
Ok, so i have tried to get count of properties for class. I have seen two related questions, but they are not quite answering this.

question one

question two

problem with those two is, that

```<code>SomeClass.class.getDeclaredFields().length
</code>```

and

```<code>SomeClass.class.getDeclaredMethods().length
</code>```

are not quite return what i would expect them to. I got sample class:

```<code>SomeClass {
    public static final int ONE = 1, TWO = 2, THREE = 3;

    public static int someMethodOne(){}
    public static int someMethodTwo(){}
}
</code>```

Declared fields return 5 which according to this is wrong, and should be 3. Declared methods does not help either, because it returns 3, while there are only 2 declared methods. What is wrong with this?

Edit:
trying to do this with Java 8 & Android Studio

答:
I get 3 and 2 as expected when I run the code below. If you get other values, you could also print the names of the fields and the methods (see below).

```<code>public class SomeClassChecker {

    public static void main(String[] args) {
        System.out.println(SomeClass.class.getDeclaredFields().length);
        System.out.println(SomeClass.class.getDeclaredMethods().length);

        for (Field field : SomeClass.class.getDeclaredFields()) {
            System.out.println("field: " + field.getName());
        }

        for (Method method : SomeClass.class.getDeclaredMethods()) {
            System.out.println("method: " + method.getName());
        }

    }

}
</code>```

Java 8 & Eclipse. I get this (expected) output:

```<code>3
2
field: ONE
field: TWO
field: THREE
method: someMethodOne
method: someMethodTwo
</code>```

Body:
Ok, so i have tried to get count of properties for class. I have seen two related questions, but they are not quite answering this.

question one

question two

problem with those two is, that

SomeClass.class.getDeclaredFields().length

and

SomeClass.class.getDeclaredMethods().length

are not quite return what i would expect them to. I got sample class:

SomeClass {
    public static final int ONE = 1, TWO = 2, THREE = 3;

    public static int someMethodOne(){}
    public static int someMethodTwo(){}
}

Declared fields return 5 which according to this is wrong, and should be 3. Declared methods does not help either, because it returns 3, while there are only 2 declared methods. What is wrong with this?

Edit:
trying to do this with Java 8 & Android Studio

Body:
I get 3 and 2 as expected when I run the code below. If you get other values, you could also print the names of the fields and the methods (see below).

public class SomeClassChecker {

    public static void main(String[] args) {
        System.out.println(SomeClass.class.getDeclaredFields().length);
        System.out.println(SomeClass.class.getDeclaredMethods().length);

        for (Field field : SomeClass.class.getDeclaredFields()) {
            System.out.println("field: " + field.getName());
        }

        for (Method method : SomeClass.class.getDeclaredMethods()) {
            System.out.println("method: " + method.getName());
        }

    }

}

Java 8 & Eclipse. I get this (expected) output:

3
2
field: ONE
field: TWO
field: THREE
method: someMethodOne
method: someMethodTwo


问:
Read url to string in few lines of java code
I'm trying to find Java's equivalent to Groovy's:

```<code>String content = "http://www.google.com".toURL().getText();
</code>```

I want to read content from a URL into string.  I don't want to pollute my code with buffered streams and loops for such a simple task.  I looked into apache's HttpClient but I also don't see a one or two line implementation.

答:
There's an even better way as of Java 9:

```<code>URL u = new URL("http://www.example.com/");
try (InputStream in = u.openStream()) {
    return new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
</code>```

Like the original groovy example, this assumes that the content is UTF-8 encoded. (If you need something more clever than that, you need to create a URLConnection and use it to figure out the encoding.)

Body:
I'm trying to find Java's equivalent to Groovy's:

String content = "http://www.google.com".toURL().getText();

I want to read content from a URL into string.  I don't want to pollute my code with buffered streams and loops for such a simple task.  I looked into apache's HttpClient but I also don't see a one or two line implementation.

Body:
There's an even better way as of Java 9:

URL u = new URL("http://www.example.com/");
try (InputStream in = u.openStream()) {
    return new String(in.readAllBytes(), StandardCharsets.UTF_8);
}

Like the original groovy example, this assumes that the content is UTF-8 encoded. (If you need something more clever than that, you need to create a URLConnection and use it to figure out the encoding.)


答:
I took off the scanner.close(); and added "fF" to the pattern, it runs until I input f or F:

```<code> boolean run = true;
    while(run){
      System.out.println("Another action? [Y/N]");
        while (!scanner.hasNext("[YyNnfF]")) {
          System.out.println("Incorrehct input");
           scanner.next();
      }
        String choice = scanner.next();
         if(choice.toLowerCase().equals("f"))
            run = false;

      //  scanner.close();
    }
</code>```

Title: JAVA - SCANNER to get user input

Body:
I have the following block code:

    boolean run = true;
    while (run) {
        Scanner scanner = new Scanner(System.in);
        // do something

        System.out.println("Another action? [Y/N]");
        while (!scanner.hasNext("[YyNn]")) {
            System.out.println("Incorrect input");
            scanner.next();
        }
        String choice = scanner.next();
        if (choice.toLowerCase().equals("f"))
            run = false;

        scanner.close();
    }

I want to perform something until the user types 'N'.
Currently, I'm able to run the while loop only one time.
The second time I'm not able to type my choice and I have the following error:

Another action? [Y/N]     <--- here no chance to type choice
Incorrect input
java.util.NoSuchElementException
    at java.util.Scanner.throwFor
    at java.util.Scanner.next

What is wrong?
Thanks

EDIT: I think my problem is in "do something". It is in turn a sequence of user input where i close the scanner.

Body:
I took off the scanner.close(); and added "fF" to the pattern, it runs until I input f or F:

 boolean run = true;
    while(run){
      System.out.println("Another action? [Y/N]");
        while (!scanner.hasNext("[YyNnfF]")) {
          System.out.println("Incorrehct input");
           scanner.next();
      }
        String choice = scanner.next();
         if(choice.toLowerCase().equals("f"))
            run = false;

      //  scanner.close();
    }


答:
To get the individual strings, you could get the children of the div element and filter them by their type.

```<code>>>> bs = bs4.BeautifulSoup(html)
>>> div = bs.find(attrs={"class":"column4"})
>>> [c.strip() for c in div.children if type(c) is bs4.element.NavigableString]
['Unlimited Subscription', 'Discount for Monthly', 'Total Amount']
</code>```

Or shorter, using div.stripped_strings (or just div.strings if you don't want to strip):

```<code>>>> list(div.stripped_strings)
['Unlimited Subscription', 'Discount for Monthly', 'Total Amount']
</code>```

Title: Extract strings from HTML

Body:
To get the individual strings, you could get the children of the div element and filter them by their type.

>>> bs = bs4.BeautifulSoup(html)
>>> div = bs.find(attrs={"class":"column4"})
>>> [c.strip() for c in div.children if type(c) is bs4.element.NavigableString]
['Unlimited Subscription', 'Discount for Monthly', 'Total Amount']

Or shorter, using div.stripped_strings (or just div.strings if you don't want to strip):

>>> list(div.stripped_strings)
['Unlimited Subscription', 'Discount for Monthly', 'Total Amount']