问:
PHP7.0 & Informix DB connectors
I am trying to connect to an Informix db remotely via php7.0
I've found the driver
https://pecl.php.net/package/PDO_INFORMIX/1.3.3

Downloaded the .tar.gz. and extracted it.
Prepped the php files via phpize and ran ./configure as explained in:

http://php.net/manual/en/ref.pdo-informix.php

However, it crashes with the following error:

checking for PDO includes... configure: error: Cannot find php_pdo_driver.h.

I know that PDO has been a core PHP lib for a while and probably the C header file is named differently than the one referenced in the lib.

Any ideas where to go from here?
It's been a very rough day.
Installing the Informix SDK is a nightmare for itself anyway. Can't even find the installation dir.

答:
The Informix SDK has been carefully and specifically designed by IBM to ruin your day.

The whole set lives under /opt/IBM/informix by default

Add /opt/IBM/informix/lib/cli and /opt/IBM/informix/lib/esql to your dynamic linker lookup paths. On Fedora you can do this by putting them in a new file /etc/ld.so.conf.d/informix.conf

You need to set the environment variable INFORMIXDIR. On Fedora you may add a new file /etc/profile.d/informix.sh and add export INFORMIXDIR=/opt/IBM/informix

Edit /opt/IBM/informix/etc/sqlhosts and put your basic connection information there. In the most simple case it has only one line that reads YOUR_SERVER_NAME\tonsoctcp\tYOUR_DB_NAME\tpdap-np. Note that pdap-np is actually port 1526 which is also the Informix "Turbo"-Driver tcp port. See your /etc/services.

Get the environment-changes going, e.g. by a reboot if you did them globally.

I can't remember the include-dir but you probably need /opt/IBM/informix/include in your CFLAGS's -I

Title: PHP7.0 & Informix DB connectors


来源: stackexchange

问:
Mobile technology products using PHP/Javascript/jquery
I wanted to know the mobile technology products which are developed using PHP/Javascript/jquery.

Which are latest mobile products are available in market developed using above mentioned langauges.

Are iphone,blackberry,nokia and etc uses these above technologies to develop product and which are those products.

If anyone has any reference for above question please share their ideas.

Thanks in advance

答:
PHP is server side. If it prints a valid XHTML code, there shouldn't be a problem reading XHTML.

Further, I would use / am using jQuery.

For the alpha release, the following devices have been tested and should have a fairly solid jQuery Mobile experience. That being said, there are still a fair amount of bugs and performance improvements to be tackled before the 1.0 release in January.

```<code>* Apple iOS: iPhone, iPod Touch, iPad (all versions)
* Android: all devices (all versions)
* Blackberry Torch (version 6)
* Palm WebOS Pre, Pixi
* Nokia N900
</code>```

Older versions of Blackberry, Nokia/Symbian, and Windows Mobile may work but we're still seeing JavaScript errors and rendering bugs that need to be tracked down. We don't yet have phones to test Windows Mobile 7, bada, or MeeGo but these will be added as soon as we can get devices.

Since jQuery Mobile is built on the jQuery core, all pages should also work great on most recent versions of desktop browsers too - Firefox, Chrome, Safari, Internet Explorer, Opera, etc.

See more: Mobile Graded Browser Support

ContentLicense: CC BY-SA 2.5

Body:
PHP is server side. If it prints a valid XHTML code, there shouldn't be a problem reading XHTML.

Further, I would use / am using jQuery.

For the alpha release, the following devices have been tested and should have a fairly solid jQuery Mobile experience. That being said, there are still a fair amount of bugs and performance improvements to be tackled before the 1.0 release in January.

* Apple iOS: iPhone, iPod Touch, iPad (all versions)
* Android: all devices (all versions)
* Blackberry Torch (version 6)
* Palm WebOS Pre, Pixi
* Nokia N900

Older versions of Blackberry, Nokia/Symbian, and Windows Mobile may work but we're still seeing JavaScript errors and rendering bugs that need to be tracked down. We don't yet have phones to test Windows Mobile 7, bada, or MeeGo but these will be added as soon as we can get devices.

Since jQuery Mobile is built on the jQuery core, all pages should also work great on most recent versions of desktop browsers too - Firefox, Chrome, Safari, Internet Explorer, Opera, etc.

See more: Mobile Graded Browser Support


问:
DialogFragment : EditText keyboard covers whole screen in landscape mode
I have a DialogFragment with two input fields and two buttons. In portrait mode everything is fine, but in landscape mode when an input field is focused the whole Dialog disappears so the buttons are not there. Screen is then covered by a keyboard and a "next" buttons image (where does it come from ?). What can I do to prevent ? Tried setting android:windowSoftInputMode but no difference

答:
Best way is to use different layouts:</p>

```<code>res/layout [Portrait Mode; default]
 main.xml
res/layout-land [Landscape Mode]
 main.xml
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Best way is to use different layouts:

res/layout [Portrait Mode; default]
 main.xml
res/layout-land [Landscape Mode]
 main.xml

ContentLicense: CC BY-SA 4.0


问:
Grouped listview crashes on second refresh
I've got a grouped Xamarin ListView, and found it troublesome updating the values within the ListView.

ViewModel;

```<code>public class MainViewModel
{
    private ObservableCollection<ObservableGroupCollection<string, TaskItem>> _userTasksGrouped;
    public ObservableCollection<ObservableGroupCollection<string, TaskItem>> UserTasksGrouped
    {
        get => _userTasksGrouped;
        set
        {
            _userTasksGrouped = value;
            OnPropertyChanged();
        }
    }

    private void PopulateMyTasks()
    {
        UserTasks.Clear();
        foreach (var task in MyTasks)
        {
            UserTasks.Add(new TaskItem(task));
        }
        DoTaskGrouping();
    }

    private void DoTaskGrouping()
    {
        UserTasksGrouped.Clear();
        var groupedData =
            UserTasks
                .OrderBy(ut => ut.Name)
                .GroupBy(ut => ut.StateEnum.ToString())
                .Select(ut => new ObservableGroupCollection<string, TaskItem>(ut))
                .ToList();
        foreach (var group in groupedData)
            UserTasksGrouped.Add(group);
    }

    public void UpdateTaskItem(TaskChanged taskChanged)
    {
        // update listing
        var usertask = UserTasksGrouped.First(utg => utg.Any(ut => ut.Task.Id == taskChanged.Task.Id))
            .First(t => t.Task.Id == taskChanged.Task.Id);
        if (usertask != null)
        {
            usertask.Task = taskChanged.Task;
        }
        else
        {
            // something else
        }
        DoTaskGrouping();
    }

    public MainViewModel()
    {
        UserTasks = new ObservableCollection<TaskItem>();
        UserTasksGrouped = new ObservableCollection<ObservableGroupCollection<string, TaskItem>>();
    }
}
</code>```

XAML;

```<code><ListView
    IsGroupingEnabled="true"
    ItemsSource="{Binding UserTasksGrouped}"
    GroupDisplayBinding="{Binding Key}"
    GroupShortNameBinding="{Binding Key}">

    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <ViewCell.View>
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto" />
                            <RowDefinition Height="Auto" />
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="50*" />
                            <ColumnDefinition Width="Auto" />
                        </Grid.ColumnDefinitions>

                        <BoxView
                            Grid.Row="0" Grid.RowSpan="2"
                            Grid.Column="0" Grid.ColumnSpan="2"
                            MinimumHeightRequest="16"
                            MinimumWidthRequest="16"
                            Margin="0"
                            Color="{Binding StatusColour}" />

                        <Label
                            Grid.Row="0" Grid.Column="2"
                            Text="{Binding Name}"
                            Style="{StaticResource LabelStyle}"
                            WidthRequest="200" />
                    </Grid>
                </ViewCell.View>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
</code>```

Task Item:

```<code>public class TaskItem : INotifyPropertyChanged
{
    private MyTask _task;
    public MyTask Task
    {
        get => _task;
        set
        {
            _task = value;
            Name = value.Name;
            OnPropertyChanged();
        }
    }

    private string _name;
    public string Name
    {
        get => _name;
        set
        {
            _name = value;
            OnPropertyChanged();
        }
    }

    public string StatusColour => "Green"
}
</code>```

The problem when I call DoTaskGrouping() for the second time to force a refresh the App crashes with an UnhandledException. I managed to track this down to a "An item with the same key has already been added" error, so I added the ViewCell.View thinking it might fix things. Please help, I have a few questions;

How do I fix the error "An item with same key has already been added" and successfully refresh my grouped listing.

Do Observable collections within observable collections update themselves. Meaning if the properties or what their grouped by changes, so does the grouping? Meaning an item can move between groups?

Is my approach sound from a MVVM perspective? TaskItem could do with cleaning up.

答:
Fixed by removing from the MainViewModel

```<code>public ObservableCollection<ObservableGroupCollection<string, TaskItem>> UserTasksGrouped
</code>```

DoTaskGrouping() building the collection afresh each time;

```<code>UserTasksGrouped = new ObservableCollection<ObservableGroupCollection<string, TaskItem>>(groupedData);
</code>```

Body:
I've got a grouped Xamarin ListView, and found it troublesome updating the values within the ListView.

ViewModel;

public class MainViewModel
{
    private ObservableCollection<ObservableGroupCollection<string, TaskItem>> _userTasksGrouped;
    public ObservableCollection<ObservableGroupCollection<string, TaskItem>> UserTasksGrouped
    {
        get => _userTasksGrouped;
        set
        {
            _userTasksGrouped = value;
            OnPropertyChanged();
        }
    }

    private void PopulateMyTasks()
    {
        UserTasks.Clear();
        foreach (var task in MyTasks)
        {
            UserTasks.Add(new TaskItem(task));
        }
        DoTaskGrouping();
    }

    private void DoTaskGrouping()
    {
        UserTasksGrouped.Clear();
        var groupedData =
            UserTasks
                .OrderBy(ut => ut.Name)
                .GroupBy(ut => ut.StateEnum.ToString())
                .Select(ut => new ObservableGroupCollection<string, TaskItem>(ut))
                .ToList();
        foreach (var group in groupedData)
            UserTasksGrouped.Add(group);
    }

    public void UpdateTaskItem(TaskChanged taskChanged)
    {
        // update listing
        var usertask = UserTasksGrouped.First(utg => utg.Any(ut => ut.Task.Id == taskChanged.Task.Id))
            .First(t => t.Task.Id == taskChanged.Task.Id);
        if (usertask != null)
        {
            usertask.Task = taskChanged.Task;
        }
        else
        {
            // something else
        }
        DoTaskGrouping();
    }

    public MainViewModel()
    {
        UserTasks = new ObservableCollection<TaskItem>();
        UserTasksGrouped = new ObservableCollection<ObservableGroupCollection<string, TaskItem>>();
    }
}

XAML;

<ListView
    IsGroupingEnabled="true"
    ItemsSource="{Binding UserTasksGrouped}"
    GroupDisplayBinding="{Binding Key}"
    GroupShortNameBinding="{Binding Key}">

    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <ViewCell.View>
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto" />
                            <RowDefinition Height="Auto" />
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="50*" />
                            <ColumnDefinition Width="Auto" />
                        </Grid.ColumnDefinitions>

                        <BoxView
                            Grid.Row="0" Grid.RowSpan="2"
                            Grid.Column="0" Grid.ColumnSpan="2"
                            MinimumHeightRequest="16"
                            MinimumWidthRequest="16"
                            Margin="0"
                            Color="{Binding StatusColour}" />

                    </Grid>
                </ViewCell.View>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Task Item:

public class TaskItem : INotifyPropertyChanged
{
    private MyTask _task;
    public MyTask Task
    {
        get => _task;
        set
        {
            _task = value;
            Name = value.Name;
            OnPropertyChanged();
        }
    }

    private string _name;
    public string Name
    {
        get => _name;
        set
        {
            _name = value;
            OnPropertyChanged();
        }
    }

    public string StatusColour => "Green"
}

The problem when I call DoTaskGrouping() for the second time to force a refresh the App crashes with an UnhandledException. I managed to track this down to a "An item with the same key has already been added" error, so I added the ViewCell.View thinking it might fix things. Please help, I have a few questions;

How do I fix the error "An item with same key has already been added" and successfully refresh my grouped listing.

Do Observable collections within observable collections update themselves. Meaning if the properties or what their grouped by changes, so does the grouping? Meaning an item can move between groups?

Is my approach sound from a MVVM perspective? TaskItem could do with cleaning up.

Body:
Fixed by removing from the MainViewModel

public ObservableCollection<ObservableGroupCollection<string, TaskItem>> UserTasksGrouped

DoTaskGrouping() building the collection afresh each time;

UserTasksGrouped = new ObservableCollection<ObservableGroupCollection<string, TaskItem>>(groupedData);


问:
Vectorization: matrix array multiplication element wise one by one
I have a matrix:

R = [0 -1;1 0];

```<code>array = 1:1:10;
</code>```

Also x0 = [2;1]

How can I obtain another array in the most efficient way without loop?

```<code>array2 = [expm(1*R) expm(2*R) expm(3*R) .... expm(10*R)];
</code>```

Then I want to obtain
array3 of dimension 2 by 10 such that:

```<code>array3 = [expm(1*R)*x0 expm(2*R)*x0 expm(3*R)*x0 .... expm(10*R)*x0];
</code>```

答:
I still don't know if I got your question right. Here are two solutions which are not fully vectorized, but fairly fast:

```<code>R = [0 -1;1 0];
A = 1:1:10;
x0 = [2;1];

%// option 1
temp = arrayfun(@(x) (expm(R*x)*x0).', A, 'uni', 0);
array3 = vertcat( temp{:} )

%// option 2
temp = accumarray( (1:numel(A)).', A(:), [], @(x) {(expm(R*x)*x0).'})
array3 = vertcat( temp{:} )
</code>```

Benchmark

I haven't considered Leander's Answer as it doesn't calculate array3:

```<code>function [t] = bench()
    R = [0 -1;1 0];
    A = 1:1:10;
    x0 = [2;1];

    % functions to compare
    fcns = {
        @() compare1(A,R,x0);
        @() compare2(A,R,x0);
        @() compare3(A,R,x0);
    };

    % timeit
    t = zeros(3,1);
    for ii = 1:100;
        t = t + cellfun(@timeit, fcns);
    end
end

function array3 = compare1(A,R,x0)  %rahnema1
    n = numel(A);
    array3 = reshape(expm(kron(diag(A),R))*repmat(x0,n,1),2,[])
end
function array3 = compare2(A,R,x0)  %thewaywewalk 1
    temp = arrayfun(@(x) (expm(R*x)*x0).', A, 'uni', 0);
    array3 = vertcat( temp{:} )
end
function array3 = compare3(A,R,x0)  %thewaywewalk 2
    temp = accumarray( (1:numel(A)).', A(:), [], @(x) {(expm(R*x)*x0).'});
    array3 = vertcat( temp{:} )
end
</code>```

Results:

for A = 1:1:10;

```<code>0.1006   %// rahnema
0.2831   %// thewaywewalk arrayfun
0.3103   %// thewaywewalk accumarray
</code>```

As kron gets really slow for large arrays, the benchmark results change for A = 1:1:100;:

```<code>4.0068   %// rahnema
1.8045   %// thewaywewalk arrayfun
2.4257   %// thewaywewalk accumarray
</code>```

Body:
I have a matrix:

R = [0 -1;1 0];

array = 1:1:10;

Also x0 = [2;1]

How can I obtain another array in the most efficient way without loop?

array2 = [expm(1*R) expm(2*R) expm(3*R) .... expm(10*R)];

Then I want to obtain
array3 of dimension 2 by 10 such that:

array3 = [expm(1*R)*x0 expm(2*R)*x0 expm(3*R)*x0 .... expm(10*R)*x0];

Body:
I still don't know if I got your question right. Here are two solutions which are not fully vectorized, but fairly fast:

R = [0 -1;1 0];
A = 1:1:10;
x0 = [2;1];

%// option 1
temp = arrayfun(@(x) (expm(R*x)*x0).', A, 'uni', 0);
array3 = vertcat( temp{:} )

%// option 2
temp = accumarray( (1:numel(A)).', A(:), [], @(x) {(expm(R*x)*x0).'})
array3 = vertcat( temp{:} )

Benchmark

I haven't considered Leander's Answer as it doesn't calculate array3:

function [t] = bench()
    R = [0 -1;1 0];
    A = 1:1:10;
    x0 = [2;1];

    % functions to compare
    fcns = {
        @() compare1(A,R,x0);
        @() compare2(A,R,x0);
        @() compare3(A,R,x0);
    };

    % timeit
    t = zeros(3,1);
    for ii = 1:100;
        t = t + cellfun(@timeit, fcns);
    end
end

function array3 = compare1(A,R,x0)  %rahnema1
    n = numel(A);
    array3 = reshape(expm(kron(diag(A),R))*repmat(x0,n,1),2,[])
end
function array3 = compare2(A,R,x0)  %thewaywewalk 1
    temp = arrayfun(@(x) (expm(R*x)*x0).', A, 'uni', 0);
    array3 = vertcat( temp{:} )
end
function array3 = compare3(A,R,x0)  %thewaywewalk 2
    temp = accumarray( (1:numel(A)).', A(:), [], @(x) {(expm(R*x)*x0).'});
    array3 = vertcat( temp{:} )
end

Results:

for A = 1:1:10;

0.1006   %// rahnema
0.2831   %// thewaywewalk arrayfun
0.3103   %// thewaywewalk accumarray

As kron gets really slow for large arrays, the benchmark results change for A = 1:1:100;:

4.0068   %// rahnema
1.8045   %// thewaywewalk arrayfun
2.4257   %// thewaywewalk accumarray


问:
Converting C# hash function to C++
I have this function in C#:

```<code>public static unsafe int GetMonoHash(string str) {
    unsafe {
        fixed (char* src = str) {
            char* chPtr2 = src; // + offset;
            char* chPtr3 = (chPtr2 + str.Length) - 1;
            int num = 0;
            while (chPtr2 < chPtr3) {
                num = ((num << 5) - num) + chPtr2[0];
                num = ((num << 5) - num) + chPtr2[1];
                chPtr2 += 2;
            }
            chPtr3++;
            if (chPtr2 < chPtr3) {
                num = ((num << 5) - num) + chPtr2[0];
            }
            return num;
        }
    }
}
</code>```

I tried to rewrite it in C++ and I got this far:

```<code>int Utils::getMonoHash(std::string str)
{
    char* src = &str[0];
    char* chPtr2 = src; // + offset;
->  char* chPtr3 = (chPtr2 + str.length) - 1;
    int num = 0;
    while (chPtr2 < chPtr3) {
        num = ((num << 5) - num) + chPtr2[0];
        num = ((num << 5) - num) + chPtr2[1];
        chPtr2 += 2;
    }
    chPtr3++;
    if (chPtr2 < chPtr3) {
        num = ((num << 5) - num) + chPtr2[0];
    }
    return num;
}
</code>```

This was throwing a compilation errors:

```<code>C3867 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>::length': non-standard syntax; use '&' to create a pointer to member
C2297 '+': illegal, right operand has type 'unsigned __int64 (__cdecl std::basic_string<char,std::char_traits<char>,std::allocator<char>>::* )(void) noexcept const'
</code>```

So I changed the indicated (->) line to

```<code>char* chPtr3 = (chPtr2 + (char *)str.length) - 1;
</code>```

which gave me a new compilation error (just one this time, yay!):

```<code>C2440 'type cast': cannot convert from 'unsigned __int64 (__cdecl std::basic_string<char,std::char_traits<char>,std::allocator<char>>::* )(void) noexcept const' to 'char *'
</code>```

I have no idea what to do now. I need the C++ function to have the same output as the C# one when given the same input as the C# one.

What do I do here?

答:
What do you do? You stop "translating" as if C++ and C# have anything in common, and write from scratch using your base requirements — and your C++ book — as a guide.

In this case your problem is that you are using a member function incorrectly. It is str.length(). The compiler's complaints are about using a function name incorrectly, without actually calling it.

Title: Converting C# hash function to C++

Body:
I have this function in C#:

public static unsafe int GetMonoHash(string str) {
    unsafe {
        fixed (char* src = str) {
            char* chPtr2 = src; // + offset;
            char* chPtr3 = (chPtr2 + str.Length) - 1;
            int num = 0;
            while (chPtr2 < chPtr3) {
                num = ((num << 5) - num) + chPtr2[0];
                num = ((num << 5) - num) + chPtr2[1];
                chPtr2 += 2;
            }
            chPtr3++;
            if (chPtr2 < chPtr3) {
                num = ((num << 5) - num) + chPtr2[0];
            }
            return num;
        }
    }
}

I tried to rewrite it in C++ and I got this far:

int Utils::getMonoHash(std::string str)
{
    char* src = &str[0];
    char* chPtr2 = src; // + offset;
->  char* chPtr3 = (chPtr2 + str.length) - 1;
    int num = 0;
    while (chPtr2 < chPtr3) {
        num = ((num << 5) - num) + chPtr2[0];
        num = ((num << 5) - num) + chPtr2[1];
        chPtr2 += 2;
    }
    chPtr3++;
    if (chPtr2 < chPtr3) {
        num = ((num << 5) - num) + chPtr2[0];
    }
    return num;
}

This was throwing a compilation errors:

C3867 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>::length': non-standard syntax; use '&' to create a pointer to member
C2297 '+': illegal, right operand has type 'unsigned __int64 (__cdecl std::basic_string<char,std::char_traits<char>,std::allocator<char>>::* )(void) noexcept const'

So I changed the indicated (->) line to

char* chPtr3 = (chPtr2 + (char *)str.length) - 1;

which gave me a new compilation error (just one this time, yay!):

C2440 'type cast': cannot convert from 'unsigned __int64 (__cdecl std::basic_string<char,std::char_traits<char>,std::allocator<char>>::* )(void) noexcept const' to 'char *'

I have no idea what to do now. I need the C++ function to have the same output as the C# one when given the same input as the C# one.

What do I do here?


问:
Custom TagHelpers in ASP.NET MVC6 & EF 7
Here's my codes:

_ViewImport.cs

```<code>@using BFcMVC
@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"
@addTagHelper "BFcMVC.TagsHelpers.TagsHelpers, BFcMVC"
</code>```

BFcMVC.TagsHelpers:

```<code>using Microsoft.AspNet.Razor.TagHelpers;

namespace BFcMVC.TagsHelpers
{
    public class TagsHelpers : TagHelper
    {
        public static string Truncate(string text, int length)
        {
            if (text.Length >= length)
                return text.Substring(0, length) + "...";

            return text;
        }
    }
}
</code>```

Index.cshtml

All of the next code returns error:

```<code>@Html.DisplayFor(modelItem => item.Article).Truncate(this, 50)
@Html.DisplayFor(modelItem => item.Article.Truncate(this,50))
</code>```

How can I solve this?

答:
```<code><p asp-for-display="item.Article" length="400"></p> (Substring(0, 400))
<div asp-for-display="item.Article" length="160"></div> (Substring(0, 160))
<span asp-for-display="item.Article"></span> (Full length)
<h1 asp-for-display="item.Article"></h1> (Full length)
**<b asp-for-display="item.Article"></b>** (Not work, HtmlTargetElement not exist)
</code>```

Asp.Net Core TagHelper

```<code>/// <summary>
/// <see cref="ITagHelper"/> implementation targeting <p> elements with an <c>asp-for</c> attribute.
/// </summary>
[HtmlTargetElement("p", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("div", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("dd", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("span", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("th", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("td", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("span", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("i", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("h1", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("h2", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("h3", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("h4", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("h5", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("h6", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("code", Attributes = ModelValueForAttributeName)]
public class ModelValueForTagHelper : TagHelper
{
    private const string ModelValueForAttributeName = "asp-for-display";

    [HtmlAttributeName(ModelValueForAttributeName)]
    public ModelExpression For { get; set; }

    public int length { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        ***// If you need clear result use "TagName = "";"***
        //output.TagName = "label";
        //output.TagMode = TagMode.StartTagAndEndTag;

        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        if (output == null)
        {
            throw new ArgumentNullException(nameof(output));
        }

        var text = For.ModelExplorer.GetSimpleDisplayText();
        if (text.Length >= length)
        {
            text = text.Substring(0, length) + "...";
        }

        output.Content.SetContent(text);
    }
}
</code>```

Body:
Here's my codes:

_ViewImport.cs

@using BFcMVC
@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"
@addTagHelper "BFcMVC.TagsHelpers.TagsHelpers, BFcMVC"

BFcMVC.TagsHelpers:

using Microsoft.AspNet.Razor.TagHelpers;

namespace BFcMVC.TagsHelpers
{
    public class TagsHelpers : TagHelper
    {
        public static string Truncate(string text, int length)
        {
            if (text.Length >= length)
                return text.Substring(0, length) + "...";

            return text;
        }
    }
}

Index.cshtml

All of the next code returns error:

@Html.DisplayFor(modelItem => item.Article).Truncate(this, 50)
@Html.DisplayFor(modelItem => item.Article.Truncate(this,50))

How can I solve this?

Body:
<p asp-for-display="item.Article" length="400"></p> (Substring(0, 400))
<div asp-for-display="item.Article" length="160"></div> (Substring(0, 160))
<span asp-for-display="item.Article"></span> (Full length)
<h1 asp-for-display="item.Article"></h1> (Full length)
**<b asp-for-display="item.Article"></b>** (Not work, HtmlTargetElement not exist)

Asp.Net Core TagHelper

/// <summary>
/// <see cref="ITagHelper"/> implementation targeting &lt;p&gt; elements with an <c>asp-for</c> attribute.
/// </summary>
[HtmlTargetElement("p", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("div", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("dd", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("span", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("th", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("td", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("span", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("i", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("h1", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("h2", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("h3", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("h4", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("h5", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("h6", Attributes = ModelValueForAttributeName)]
[HtmlTargetElement("code", Attributes = ModelValueForAttributeName)]
public class ModelValueForTagHelper : TagHelper
{
    private const string ModelValueForAttributeName = "asp-for-display";

    [HtmlAttributeName(ModelValueForAttributeName)]
    public ModelExpression For { get; set; }

    public int length { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        ***// If you need clear result use "TagName = "";"***
        //output.TagName = "label";
        //output.TagMode = TagMode.StartTagAndEndTag;

        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        if (output == null)
        {
            throw new ArgumentNullException(nameof(output));
        }

        var text = For.ModelExplorer.GetSimpleDisplayText();
        if (text.Length >= length)
        {
            text = text.Substring(0, length) + "...";
        }

        output.Content.SetContent(text);
    }
}


问:
login to website using httpulrconnection
I've got a server set up to accept email & password credentials and I want my app to login using HttpURLconnection. The connection part seems to be ok, since the response is alway 200, but I'm having trouble actually sending the data. I convert the json pair to string and send it through DataOutputStream. I read the response through InputStream.

My main problem is the response I read with InputStream is always the same (the html of the login page) even if the email&password are wrong, which has me thinking I'm not sending the data correctly.

You can take a look at my code:

```<code>import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.JsonWriter;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.app.ProgressDialog;
import java.io.DataOutputStream;
import java.net.MalformedURLException;
import android.net.Uri;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.content.Intent;
import org.json.JSONObject;
import org.json.JSONStringer;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

private EditText user;
private EditText pswrd;
private Button login;
private String email;
private String password;
private String HOST;
private String DEFAULT_IPADDRESS;
private String PREFERENCES_IPADDRESSSERVER;
private String PREFERENCES_TOKEN;
private Context ctx;
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private String sRequest;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    user = (EditText) findViewById(R.id.Email);
    pswrd = (EditText) findViewById(R.id.Password);
    login = (Button) findViewById(R.id.button);

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            email = user.getText().toString();
            password = pswrd.getText().toString();
            try {
                //HttpURLConnection example = serverLogin(email, password);
                new AsyncLogin().execute(email, password);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    });

}

private class AsyncLogin extends AsyncTask<String, String, String> {
    ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
    HttpURLConnection conn;
    URL url = null;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tLoading...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {
        try {

            // Enter URL address
            url = new URL("http://81.169.151.83/users/sign_in");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "exception";
        }
        try {
            // Setup HttpURLConnection class to send and receive data
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput method depict handling of both send and receive
            conn.setDoInput(true);
            conn.setDoOutput(true);

            JSONObject request = new JSONObject();
            try {
                request.put("email", params[0]);
                request.put("password", params[1]);

            } catch (org.json.JSONException e) {
                e.printStackTrace();
            }
            sRequest = request.toString();

            // Open connection for sending data
            conn.connect();
            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes(sRequest);
            wr.flush();
            wr.close();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return "exception";
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

              // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());

            } else {

                return ("unsuccessful");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return "exception";
        } finally {
            conn.disconnect();
        }

    }

    @Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread

        pdLoading.dismiss();

        if (result.equalsIgnoreCase("true")) {
            /* Here launching another activity when login successful. If you persist login state
            use sharedPreferences of Android. and logout button to clear sharedPreferences.
             */
            Toast.makeText(MainActivity.this, "GREAT SUCCESS", Toast.LENGTH_LONG).show();
         /*   Intent intent = new Intent(MainActivity.this,SuccessActivity.class);
            startActivity(intent);
            MainActivity.this.finish();*/

        } else if (result.equalsIgnoreCase("false")) {

            // If username and password does not match display a error message
            Toast.makeText(MainActivity.this, "Invalid email or password", Toast.LENGTH_LONG).show();

        } else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {

            Toast.makeText(MainActivity.this, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).show();

        }
    }

}
</code>```

Thanks

答:
I would recommend you to try OKHTTP, check out their recipes, it is a lot simpler to do GET / POST requests in Android.

On a side note, I've checked out your website at http://81.169.151.83/users/sign_in and the parameters used for the login form is user[email] and user[password]. Not the email and password which you added above. There are also several other form fields such as authenticity_token which might be the cause.

Body:
I've got a server set up to accept email & password credentials and I want my app to login using HttpURLconnection. The connection part seems to be ok, since the response is alway 200, but I'm having trouble actually sending the data. I convert the json pair to string and send it through DataOutputStream. I read the response through InputStream.

My main problem is the response I read with InputStream is always the same (the html of the login page) even if the email&password are wrong, which has me thinking I'm not sending the data correctly.

You can take a look at my code:

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.JsonWriter;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.app.ProgressDialog;
import java.io.DataOutputStream;
import java.net.MalformedURLException;
import android.net.Uri;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.content.Intent;
import org.json.JSONObject;
import org.json.JSONStringer;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

private EditText user;
private EditText pswrd;
private Button login;
private String email;
private String password;
private String HOST;
private String DEFAULT_IPADDRESS;
private String PREFERENCES_IPADDRESSSERVER;
private String PREFERENCES_TOKEN;
private Context ctx;
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private String sRequest;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    user = (EditText) findViewById(R.id.Email);
    pswrd = (EditText) findViewById(R.id.Password);
    login = (Button) findViewById(R.id.button);

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            email = user.getText().toString();
            password = pswrd.getText().toString();
            try {
                //HttpURLConnection example = serverLogin(email, password);
                new AsyncLogin().execute(email, password);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    });

}

private class AsyncLogin extends AsyncTask<String, String, String> {
    ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
    HttpURLConnection conn;
    URL url = null;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tLoading...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {
        try {

            // Enter URL address
            url = new URL("http://81.169.151.83/users/sign_in");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "exception";
        }
        try {
            // Setup HttpURLConnection class to send and receive data
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput method depict handling of both send and receive
            conn.setDoInput(true);
            conn.setDoOutput(true);

            JSONObject request = new JSONObject();
            try {
                request.put("email", params[0]);
                request.put("password", params[1]);

            } catch (org.json.JSONException e) {
                e.printStackTrace();
            }
            sRequest = request.toString();

            // Open connection for sending data
            conn.connect();
            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes(sRequest);
            wr.flush();
            wr.close();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return "exception";
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

              // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());

            } else {

                return ("unsuccessful");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return "exception";
        } finally {
            conn.disconnect();
        }

    }

    @Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread

        pdLoading.dismiss();

        if (result.equalsIgnoreCase("true")) {
            /* Here launching another activity when login successful. If you persist login state
            use sharedPreferences of Android. and logout button to clear sharedPreferences.
             */
            Toast.makeText(MainActivity.this, "GREAT SUCCESS", Toast.LENGTH_LONG).show();
         /*   Intent intent = new Intent(MainActivity.this,SuccessActivity.class);
            startActivity(intent);
            MainActivity.this.finish();*/

        } else if (result.equalsIgnoreCase("false")) {

            // If username and password does not match display a error message
            Toast.makeText(MainActivity.this, "Invalid email or password", Toast.LENGTH_LONG).show();

        } else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {

            Toast.makeText(MainActivity.this, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).show();

        }
    }

}

Thanks


问:
Opening hyperlink in a browser from iOS app
I am new to iOS development. I created a basic html page with hyperlink. I converted the html page into app using the following code.

```<code>class ViewController: UIViewController, UIWebViewDelegate {

    @IBOutlet weak var lupView: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        lupView.loadRequest(URLRequest(url: Bundle.main.url(forResource: "lup_package/lup/index", withExtension: "html")!))

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
</code>```

Everything works good when I build it to iPad Air. But when I tap on the hyperlink, the target website is opening in the app itself. I would want that to be opened in a browser. Please help me to achieve that and it would be great if you explain me is that working.

答:
If you simply want to open a url using Safari, the following should help.

```<code>if let url = URL(string: "https://www.google.com") {
    UIApplication.shared.open(url, options: [:])
}
</code>```

In case you want to open hyperlinks on your WebView using Safari. Check this out. You need to use webView:shouldStartLoadWith delegate method. Remember to set lupView.delegate = self in your view controller or Storyboard.

```<code>    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {

        if navigationType == .linkClicked {
            // Open links in Safari
            guard let url = request.url else { return true }

            if #available(iOS 10.0, *) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            } else {
                // openURL(_:) is deprecated in iOS 10+.
                UIApplication.shared.openURL(url)
            }
            return false
        }

        // Handle other navigation types...
        return true
    }
</code>```

Body:
I am new to iOS development. I created a basic html page with hyperlink. I converted the html page into app using the following code.

class ViewController: UIViewController, UIWebViewDelegate {

    @IBOutlet weak var lupView: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        lupView.loadRequest(URLRequest(url: Bundle.main.url(forResource: "lup_package/lup/index", withExtension: "html")!))

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Everything works good when I build it to iPad Air. But when I tap on the hyperlink, the target website is opening in the app itself. I would want that to be opened in a browser. Please help me to achieve that and it would be great if you explain me is that working.

Body:
If you simply want to open a url using Safari, the following should help.

if let url = URL(string: "https://www.google.com") {
    UIApplication.shared.open(url, options: [:])
}

In case you want to open hyperlinks on your WebView using Safari. Check this out. You need to use webView:shouldStartLoadWith delegate method. Remember to set lupView.delegate = self in your view controller or Storyboard.

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {

        if navigationType == .linkClicked {
            // Open links in Safari
            guard let url = request.url else { return true }

            if #available(iOS 10.0, *) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            } else {
                // openURL(_:) is deprecated in iOS 10+.
                UIApplication.shared.openURL(url)
            }
            return false
        }

        // Handle other navigation types...
        return true
    }


问:
Accessing Entry widget created using for loop
An array of Entries was created using the following code

```<code>from tkinter import *
root = Tk()

height = 5
width = 5

delta=0

for i in range(height): #Rows
  for j in range(width): #Columns
    b = Entry(root, text="",width=8)
    b.grid(row=i, column=j)

mainloop()
</code>```

How do I access each Entry to update its value ( using StringVar - for example ) ?

答:
You need to first declare the StringVar variable:

myvar = StringVar()

Then in your loop whenever you want to check to content of the variable use the get() method.

x = myvar.get()

Now x will hold the value. You can also perform a bool test with if

```<code>if myvar.get():
     print(myvar.get())
</code>```

In that if statement the program checks if there is data in the var. If not it will move on

Looking at it again you should also declare the StringVar() in your button. Like so:

```<code>b = Button(text='clickme', texvariable=myvar)
</code>```

Look Here for more info

Body:
An array of Entries was created using the following code

from tkinter import *
root = Tk()

height = 5
width = 5

delta=0

for i in range(height): #Rows
  for j in range(width): #Columns
    b = Entry(root, text="",width=8)
    b.grid(row=i, column=j)

mainloop()

How do I access each Entry to update its value ( using StringVar - for example ) ?

Body:
You need to first declare the StringVar variable:

myvar = StringVar()

Then in your loop whenever you want to check to content of the variable use the get() method.

x = myvar.get()

Now x will hold the value. You can also perform a bool test with if

if myvar.get():
     print(myvar.get())

In that if statement the program checks if there is data in the var. If not it will move on

Looking at it again you should also declare the StringVar() in your button. Like so:

b = Button(text='clickme', texvariable=myvar)

Look Here for more info


问:
Grep regex not working with square brackets
So I was trying to write a regex in grep to match square brackets, i.e [ad] should match [ and ]. But I was getting different results on using capturing groups and character classes. Also the result is different on putting ' in the beginning and end of regex string.

So these are the different result that I am getting.

Using capturing groups works fine

```<code>echo "[ad]" | grep -E '(\[|\])'
[ad]
</code>```

Using capturing groups without ' gives syntax error

```<code>echo "[ad]" | grep -E (\[|\])
bash: syntax error near unexpected token `('
</code>```

using character class with [ followed by ] gives no output

```<code>echo "[ad]" | grep -E [\[\]]
</code>```

Using character class with ] followed by [ works correctly

```<code>echo "[ad]" | grep -E [\]\[]
[ad]
</code>```

Using character class with ] followed by [ and using ' does not work

```<code>echo "[ad]" | grep -E '[\]\[]'
</code>```

It'd be great if someone could explain the difference between them.

答:
You should know about:

BRE ( = Basic Regular  Expression )

ERE ( = Extended Regular Expression )

BRE metacharacters require a backslash to give them their special meaning and grep is based on

The ERE flavor standardizes a flavor similar to the one used by the UNIX egrep command.

Pay attention to -E and -G

```<code>grep --help
Usage: grep [OPTION]... PATTERN [FILE]...
Search for PATTERN in each FILE or standard input.
PATTERN is, by default, a basic regular expression (BRE).
Example: grep -i 'hello world' menu.h main.c

Regexp selection and interpretation:
  -E, --extended-regexp     PATTERN is an extended regular expression (ERE)
  -F, --fixed-strings       PATTERN is a set of newline-separated strings
  -G, --basic-regexp        PATTERN is a basic regular expression (BRE)
  -P, --perl-regexp         PATTERN is a Perl regular expression
  ...
  ...
</code>```

POSIX Basic Regular Expressions

POSIX Extended Regular Expressions

POSIX Bracket Expressions

And you should also know about bash, since some of your input is related to bash interpreter not grep or anything else

```<code>echo "[ad]" | grep -E (\[|\])
</code>```

Here bash assumes you try to use () something like:

```<code>echo $(( 10 * 10 ))
</code>```

and by using single quote ' you tell the bash that you do not want it treats as a special operator for it. So

```<code>echo "[ad]" | grep -E '(\[|\])'
</code>```

is correct.

Body:
So I was trying to write a regex in grep to match square brackets, i.e [ad] should match [ and ]. But I was getting different results on using capturing groups and character classes. Also the result is different on putting ' in the beginning and end of regex string.

So these are the different result that I am getting.

Using capturing groups works fine

echo "[ad]" | grep -E '(\[|\])'
[ad]

Using capturing groups without ' gives syntax error

echo "[ad]" | grep -E (\[|\])
bash: syntax error near unexpected token `('

using character class with [ followed by ] gives no output

echo "[ad]" | grep -E [\[\]]

Using character class with ] followed by [ works correctly

echo "[ad]" | grep -E [\]\[]
[ad]

Using character class with ] followed by [ and using ' does not work

echo "[ad]" | grep -E '[\]\[]'

It'd be great if someone could explain the difference between them.

Body:
You should know about:

BRE ( = Basic Regular  Expression )

ERE ( = Extended Regular Expression )

BRE metacharacters require a backslash to give them their special meaning and grep is based on

The ERE flavor standardizes a flavor similar to the one used by the UNIX egrep command.

Pay attention to -E and -G

grep --help
Usage: grep [OPTION]... PATTERN [FILE]...
Search for PATTERN in each FILE or standard input.
PATTERN is, by default, a basic regular expression (BRE).
Example: grep -i 'hello world' menu.h main.c

Regexp selection and interpretation:
  -E, --extended-regexp     PATTERN is an extended regular expression (ERE)
  -F, --fixed-strings       PATTERN is a set of newline-separated strings
  -G, --basic-regexp        PATTERN is a basic regular expression (BRE)
  -P, --perl-regexp         PATTERN is a Perl regular expression
  ...
  ...

POSIX Basic Regular Expressions

POSIX Extended Regular Expressions

POSIX Bracket Expressions

And you should also know about bash, since some of your input is related to bash interpreter not grep or anything else

echo "[ad]" | grep -E (\[|\])

Here bash assumes you try to use () something like:

echo $(( 10 * 10 ))

and by using single quote ' you tell the bash that you do not want it treats as a special operator for it. So

echo "[ad]" | grep -E '(\[|\])'

is correct.


答:
str.length is not a property, it is a function and needs ()

In my experience as a C# programmer, this is one of the most common mistakes C# programmers make when writing C++.

Title: Converting C# hash function to C++


问:
How do I create a GUID / UUID?
How do I create GUIDs (globally-unique identifiers) in JavaScript? The GUID / UUID should be at least 32 characters and should stay in the ASCII range to avoid trouble when passing them around.

I'm not sure what routines are available on all browsers, how "random" and seeded the built-in random number generator is, etc.

OwnerDisplayName: Jason Cohen

Title: How do I create a GUID / UUID?

Body:
ES6 sample

const guid=()=> {
  const s4=()=> Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
  return `${s4() + s4()}-${s4()}-${s4()}-${s4()}-${s4() + s4() + s4()}`;
}


问:
LibGDX issue setting black screen and showing white text
I'm having an issue with LibGDX.

I followed their guide on GitHub and then i went ahead modifying the game. (Ref: https://github.com/libgdx/libgdx/wiki/A-simple-game)

I wanted to create a game over screen when the drop touched the ground 3 times.
When it touches the ground for the 3rd time, i set lost to true, and at the start of the render() method i check if lost is true.

This is the contenent:

```<code>        if(lost){
        bucket.dispose();
        lostSound.play();
        sprite.setProjectionMatrix(camera.combined);
        Gdx.gl.glClearColor(0,0,0,0);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        drop.dispose();
        font.setColor(Color.WHITE);
        GlyphLayout layout = new GlyphLayout(font, "Game Over!");
        int fontX = 800 + 64 / 2;
        int fontY = 480 / 2;
        sprite.begin();
        font.draw(sprite, layout, fontX, fontY);
        sprite.end();
        return;
    }
</code>```

The lostSound is sorta bugged, it repeats his start at the infinite, and i get a black screen without any Game Over text.

EDIT: If i run via command line i don't get any exceptions

答:
If I'm not wrong every loop you are entering in lost condition, so the sound is playing every loop, add a flag like gameover=true for not entering again in the main loop.
Also, which is your game resolution? If you want half of 864 (if is maximum resolution), center of X, you must do fontX= (800+64)/2 (432) instead of fontX= 800+64 /2 (832)

Hope it helps

Body:
I'm having an issue with LibGDX.

I followed their guide on GitHub and then i went ahead modifying the game. (Ref: https://github.com/libgdx/libgdx/wiki/A-simple-game)

I wanted to create a game over screen when the drop touched the ground 3 times.
When it touches the ground for the 3rd time, i set lost to true, and at the start of the render() method i check if lost is true.

This is the contenent:

        if(lost){
        bucket.dispose();
        lostSound.play();
        sprite.setProjectionMatrix(camera.combined);
        Gdx.gl.glClearColor(0,0,0,0);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        drop.dispose();
        font.setColor(Color.WHITE);
        GlyphLayout layout = new GlyphLayout(font, "Game Over!");
        int fontX = 800 + 64 / 2;
        int fontY = 480 / 2;
        sprite.begin();
        font.draw(sprite, layout, fontX, fontY);
        sprite.end();
        return;
    }

The lostSound is sorta bugged, it repeats his start at the infinite, and i get a black screen without any Game Over text.

EDIT: If i run via command line i don't get any exceptions


问:
Exception when Controller's property is private or protected
I have this TextField in FXMLDocument.fxml:

```<code><TextField fx:id="searchBox" onKeyPressed="#updateText">
   <StackPane.margin>
      <Insets left="60.0" right="30.0" top="50.0" />
   </StackPane.margin>
</TextField>
</code>```

The FXML document (where the above code resides) has the controller class named FXMLDocumentController.java. Inside this, I have the following code:

```<code>public class FXMLDocumentController {

    public TextField searchBox;

    @FXML
    public void updateText (KeyEvent e) {
        System.out.println(searchBox.getText());
    }
}
</code>```

Note that the searchBox property is public. When I set it to private, my code throws an Exception at runtime. I have seen people specifying the "event bounded property" as private in Stack Overflow answers (here's one). Seeing those answers, I assume that specifying a property as private should not give any error. What's wrong with my code then?

答:
Use @FXML Annotation over your TextField searchBox. See below code:-</p>

```<code>public class FXMLDocumentController {

        @FXML
        private TextField searchBox;

        @FXML
        public void updateText (KeyEvent e) {
            System.out.println(searchBox.getText());
        }
    }
</code>```

Body:
I have this TextField in FXMLDocument.fxml:

<TextField fx:id="searchBox" onKeyPressed="#updateText">
   <StackPane.margin>
      <Insets left="60.0" right="30.0" top="50.0" />
   </StackPane.margin>
</TextField>

The FXML document (where the above code resides) has the controller class named FXMLDocumentController.java. Inside this, I have the following code:

public class FXMLDocumentController {

    public TextField searchBox;

    @FXML
    public void updateText (KeyEvent e) {
        System.out.println(searchBox.getText());
    }
}

Note that the searchBox property is public. When I set it to private, my code throws an Exception at runtime. I have seen people specifying the "event bounded property" as private in Stack Overflow answers (here's one). Seeing those answers, I assume that specifying a property as private should not give any error. What's wrong with my code then?

Body:
Use @FXML Annotation over your TextField searchBox. See below code:-

public class FXMLDocumentController {

        @FXML
        private TextField searchBox;

        @FXML
        public void updateText (KeyEvent e) {
            System.out.println(searchBox.getText());
        }
    }


问:
make mongodb insert() to ONLY insert data of object
I've been trying out mongodb for a few days but I have a problem.
It was kind of diccicult for me to explain the problem in a short title though.

So my mongodb Collection creates an autoindex which I want it to create.
But when I insert a json like this:

```<code>var body // contains JSON data
collection.insert({
  body
});
</code>```

The Object in my Collection looks like this:

```<code>{
    "_id" : ObjectId("59621dfb13eecc8a083d3951"),
    "body" : {
        "name" : "leaf",
        "type" : 2
        }
}
</code>```

What I am aiming for though is for it to look like this:

```<code>{
    "_id" : ObjectId("59621dfb13eecc8a083d3951"),
    "name" : "leaf",
    "type" : 2
}
</code>```

Any kind of help would be greatly appreciated.
Thank you for your time!

答:
just insert body not object that contains body

```<code>collection.insert(body);
</code>```

Body:
I've been trying out mongodb for a few days but I have a problem.
It was kind of diccicult for me to explain the problem in a short title though.

So my mongodb Collection creates an autoindex which I want it to create.
But when I insert a json like this:

var body // contains JSON data
collection.insert({
  body
});

The Object in my Collection looks like this:

{
    "_id" : ObjectId("59621dfb13eecc8a083d3951"),
    "body" : {
        "name" : "leaf",
        "type" : 2
        }
}

What I am aiming for though is for it to look like this:

{
    "_id" : ObjectId("59621dfb13eecc8a083d3951"),
    "name" : "leaf",
    "type" : 2
}

Any kind of help would be greatly appreciated.
Thank you for your time!

Body:
just insert body not object that contains body

collection.insert(body);


Title: How to avoid sorting pivot table by index

Body:
I have a dataframe:

t1=r.data[(r.data['test_num']==2) & (r.data['el_num'] < 4)]

     test_num  el_num  file_num     dose  is_anneal     value   fail
99          2       1         0    100.0      False -0.000056  False
100         2       1         1   5052.0      False -0.000056  False
101         2       1         2  10107.0      False -0.000056  False
102         2       1         3  16561.0      False -0.000056  False
103         2       1         4  22536.0      False -0.000056  False
104         2       1         5  25020.0      False -0.000056  False
105         2       1         6  35123.0      False -0.000056  False
106         2       1         7     24.0       True -0.000056  False
107         2       1         8    168.0       True -0.000055  False
108         2       2         0    100.0      False -0.000056  False
109         2       2         1   5052.0      False -0.000056  False
110         2       2         2  10107.0      False -0.000056  False
111         2       2         3  16561.0      False -0.000056  False
112         2       2         4  22536.0      False -0.000056  False
113         2       2         5  25020.0      False -0.000056  False
114         2       2         6  35123.0      False -0.000056  False
115         2       2         7     24.0       True -0.000056  False
116         2       2         8    168.0       True -0.000055  False
117         2       3         0    100.0      False -0.000060  False
118         2       3         1   5052.0      False -0.000061  False
119         2       3         2  10107.0      False -0.000061  False
120         2       3         3  16561.0      False -0.000061  False
121         2       3         4  22536.0      False -0.000061  False
122         2       3         5  25020.0      False -0.000061  False
123         2       3         6  35123.0      False -0.000061  False
124         2       3         7     24.0       True -0.000061  False
125         2       3         8    168.0       True -0.000061  False

When I want to create pivot table, I get this:

print(t1.pivot(index='dose',columns='el_num',values='value'))

el_num          1         2         3
dose
24.0    -0.000056 -0.000056 -0.000061
100.0   -0.000056 -0.000056 -0.000060
168.0   -0.000055 -0.000055 -0.000061
5052.0  -0.000056 -0.000056 -0.000061
10107.0 -0.000056 -0.000056 -0.000061
16561.0 -0.000056 -0.000056 -0.000061
22536.0 -0.000056 -0.000056 -0.000061
25020.0 -0.000056 -0.000056 -0.000061
35123.0 -0.000056 -0.000056 -0.000061

But I want the dose column to have an order like in the main table:

100.0
5052.0
10107.0
16561.0
22536.0
25020.0
35123.0
24.0
168.0

How to avoid sorting in pivot table?

Body:
Since the file_nums are already sorted in the desired order, you could use

(t1.set_index(['file_num','dose','el_num']['value']
   .unstack('el_num').reset_index('file_num', drop=True))

which yields

el_num          1         2         3
dose
100.0   -0.000056 -0.000056 -0.000060
5052.0  -0.000056 -0.000056 -0.000061
10107.0 -0.000056 -0.000056 -0.000061
16561.0 -0.000056 -0.000056 -0.000061
22536.0 -0.000056 -0.000056 -0.000061
25020.0 -0.000056 -0.000056 -0.000061
35123.0 -0.000056 -0.000056 -0.000061
24.0    -0.000056 -0.000056 -0.000061
168.0   -0.000055 -0.000055 -0.000061

The set_index/unstack operation is similar to pivoting except that it allows more than one column to be used as the index. file_num is included to enforce the desired row order.


答:
Above answers are very elegant. I have written this function long back where i was also struggling to concatenate two dataframe with distinct columns.

Suppose you have dataframe sdf1 and sdf2

```<code>from pyspark.sql import functions as F
from pyspark.sql.types import *

def unequal_union_sdf(sdf1, sdf2):
    s_df1_schema = set((x.name, x.dataType) for x in sdf1.schema)
    s_df2_schema = set((x.name, x.dataType) for x in sdf2.schema)

    for i,j in s_df2_schema.difference(s_df1_schema):
        sdf1 = sdf1.withColumn(i,F.lit(None).cast(j))

    for i,j in s_df1_schema.difference(s_df2_schema):
        sdf2 = sdf2.withColumn(i,F.lit(None).cast(j))

    common_schema_colnames = sdf1.columns
    sdk = \
        sdf1.select(common_schema_colnames).union(sdf2.select(common_schema_colnames))
    return sdk

sdf_concat = unequal_union_sdf(sdf1, sdf2)
</code>```

Title: Concatenate two PySpark dataframes

Body:
I'm trying to concatenate two PySpark dataframes with some columns that are only on one of them:

from pyspark.sql.functions import randn, rand

df_1 = sqlContext.range(0, 10)

+--+
|id|
+--+
| 0|
| 1|
| 2|
| 3|
| 4|
| 5|
| 6|
| 7|
| 8|
| 9|
+--+

df_2 = sqlContext.range(11, 20)

+--+
|id|
+--+
| 10|
| 11|
| 12|
| 13|
| 14|
| 15|
| 16|
| 17|
| 18|
| 19|
+--+

df_1 = df_1.select("id", rand(seed=10).alias("uniform"), randn(seed=27).alias("normal"))
df_2 = df_2.select("id", rand(seed=10).alias("uniform"), randn(seed=27).alias("normal_2"))

and now I want to generate a third dataframe. I would like something like pandas concat:

df_1.show()
+---+--------------------+--------------------+
| id|             uniform|              normal|
+---+--------------------+--------------------+
|  0|  0.8122802274304282|  1.2423430583597714|
|  1|  0.8642043127063618|  0.3900018344856156|
|  2|  0.8292577771850476|  1.8077401259195247|
|  3|   0.198558705368724| -0.4270585782850261|
|  4|0.012661361966674889|   0.702634599720141|
|  5|  0.8535692890157796|-0.42355804115129153|
|  6|  0.3723296190171911|  1.3789648582622995|
|  7|  0.9529794127670571| 0.16238718777444605|
|  8|  0.9746632635918108| 0.02448061333761742|
|  9|   0.513622008243935|  0.7626741803250845|
+---+--------------------+--------------------+

df_2.show()
+---+--------------------+--------------------+
| id|             uniform|            normal_2|
+---+--------------------+--------------------+
| 11|  0.3221262660507942|  1.0269298899109824|
| 12|  0.4030672316912547|   1.285648175568798|
| 13|  0.9690555459609131|-0.22986601831364423|
| 14|0.011913836266515876|  -0.678915153834693|
| 15|  0.9359607054250594|-0.16557488664743034|
| 16| 0.45680471157575453| -0.3885563551710555|
| 17|  0.6411908952297819|  0.9161177183227823|
| 18|  0.5669232696934479|  0.7270125277020573|
| 19|   0.513622008243935|  0.7626741803250845|
+---+--------------------+--------------------+

#do some concatenation here, how?

df_concat.show()

| id|             uniform|              normal| normal_2   |
+---+--------------------+--------------------+------------+
|  0|  0.8122802274304282|  1.2423430583597714| None       |
|  1|  0.8642043127063618|  0.3900018344856156| None       |
|  2|  0.8292577771850476|  1.8077401259195247| None       |
|  3|   0.198558705368724| -0.4270585782850261| None       |
|  4|0.012661361966674889|   0.702634599720141| None       |
|  5|  0.8535692890157796|-0.42355804115129153| None       |
|  6|  0.3723296190171911|  1.3789648582622995| None       |
|  7|  0.9529794127670571| 0.16238718777444605| None       |
|  8|  0.9746632635918108| 0.02448061333761742| None       |
|  9|   0.513622008243935|  0.7626741803250845| None       |
| 11|  0.3221262660507942|  None              | 0.123      |
| 12|  0.4030672316912547|  None              |0.12323     |
| 13|  0.9690555459609131|  None              |0.123       |
| 14|0.011913836266515876|  None              |0.18923     |
| 15|  0.9359607054250594|  None              |0.99123     |
| 16| 0.45680471157575453|  None              |0.123       |
| 17|  0.6411908952297819|  None              |1.123       |
| 18|  0.5669232696934479|  None              |0.10023     |
| 19|   0.513622008243935|  None              |0.916332123 |
+---+--------------------+--------------------+------------+

Is that possible?

Body:
Above answers are very elegant. I have written this function long back where i was also struggling to concatenate two dataframe with distinct columns.

Suppose you have dataframe sdf1 and sdf2

from pyspark.sql import functions as F
from pyspark.sql.types import *

def unequal_union_sdf(sdf1, sdf2):
    s_df1_schema = set((x.name, x.dataType) for x in sdf1.schema)
    s_df2_schema = set((x.name, x.dataType) for x in sdf2.schema)

    for i,j in s_df2_schema.difference(s_df1_schema):
        sdf1 = sdf1.withColumn(i,F.lit(None).cast(j))

    for i,j in s_df1_schema.difference(s_df2_schema):
        sdf2 = sdf2.withColumn(i,F.lit(None).cast(j))

    common_schema_colnames = sdf1.columns
    sdk = \
        sdf1.select(common_schema_colnames).union(sdf2.select(common_schema_colnames))
    return sdk

sdf_concat = unequal_union_sdf(sdf1, sdf2)


答:
Don't forget parenthesis after str.length. Correct type should be like this</p>

```<code>char* chPtr3 = (chPtr2 + str.length()) - 1;
</code>```

Title: Converting C# hash function to C++

Body:
I have this function in C#:

public static unsafe int GetMonoHash(string str) {
    unsafe {
        fixed (char* src = str) {
            char* chPtr2 = src; // + offset;
            char* chPtr3 = (chPtr2 + str.Length) - 1;
            int num = 0;
            while (chPtr2 < chPtr3) {
                num = ((num << 5) - num) + chPtr2[0];
                num = ((num << 5) - num) + chPtr2[1];
                chPtr2 += 2;
            }
            chPtr3++;
            if (chPtr2 < chPtr3) {
                num = ((num << 5) - num) + chPtr2[0];
            }
            return num;
        }
    }
}

I tried to rewrite it in C++ and I got this far:

int Utils::getMonoHash(std::string str)
{
    char* src = &str[0];
    char* chPtr2 = src; // + offset;
->  char* chPtr3 = (chPtr2 + str.length) - 1;
    int num = 0;
    while (chPtr2 < chPtr3) {
        num = ((num << 5) - num) + chPtr2[0];
        num = ((num << 5) - num) + chPtr2[1];
        chPtr2 += 2;
    }
    chPtr3++;
    if (chPtr2 < chPtr3) {
        num = ((num << 5) - num) + chPtr2[0];
    }
    return num;
}

This was throwing a compilation errors:

C3867 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>::length': non-standard syntax; use '&' to create a pointer to member
C2297 '+': illegal, right operand has type 'unsigned __int64 (__cdecl std::basic_string<char,std::char_traits<char>,std::allocator<char>>::* )(void) noexcept const'

So I changed the indicated (->) line to

char* chPtr3 = (chPtr2 + (char *)str.length) - 1;

which gave me a new compilation error (just one this time, yay!):

C2440 'type cast': cannot convert from 'unsigned __int64 (__cdecl std::basic_string<char,std::char_traits<char>,std::allocator<char>>::* )(void) noexcept const' to 'char *'

I have no idea what to do now. I need the C++ function to have the same output as the C# one when given the same input as the C# one.

What do I do here?

Body:
Don't forget parenthesis after str.length. Correct type should be like this

char* chPtr3 = (chPtr2 + str.length()) - 1;


问:
Virtual functions and performance - C++
In my class design, I use abstract classes and virtual functions extensively. I had a  feeling that virtual functions affects the performance. Is this true? But I think this performance difference is not noticeable and looks like I am doing premature optimization. Right?</p>

答:
From page 44 of Agner Fog's "Optimizing Software in C++" manual:

The time it takes to call a virtual member function is a few clock cycles more than it takes to call a non-virtual member function, provided that the function call statement always calls the same version of the virtual function. If the version changes then you will get a misprediction penalty of 10 - 30 clock cycles. The rules for prediction and misprediction of virtual function calls is the same as for switch statements...

OwnerDisplayName: Appu

Title: Virtual functions and performance - C++

LastEditorDisplayName: Serge

OwnerDisplayName: Boojum


问:
Docker Container Networking with Docker-in-Docker
I would like to network with a child docker container from a parent docker container, with a docker-in-docker setup.

Let's say I'm trying to connect to a simple Apache httpd server. When I run the httpd container on my host machine, everything works fine:

```<code>asnyder:~$ docker run -d -p 8080:80 httpd:alpine
asnyder:~$ curl localhost:8080
<html><body><h1>It works!</h1></body></html>
</code>```

But when I do the same from a docker-in-docker setup, I get a Connection refused error:

```<code>asnyder:~$ docker run -d --name mydind --privileged docker:dind
asnyder:~$ docker run -it --link mydind:docker docker:latest sh
/ # docker run -d -p 8080:80 httpd:alpine
/ # curl localhost:8080
curl: (7) Failed to connect to localhost port 8080: Connection refused
</code>```

I have tried a couple alterations without luck. Specifying the 0.0.0.0 interface:

```<code>asnyder:~$ docker run -d --name mydind --privileged docker:dind
asnyder:~$ docker run -it --link mydind:docker docker:latest sh
/ # docker run -d -p 0.0.0.0:8080:80 httpd:alpine
/ # curl 0.0.0.0:8080
curl: (7) Failed to connect to 0.0.0.0 port 8080: Connection refused
</code>```

Using the host network:

```<code>asnyder:~$ docker run -d --name mydind --privileged docker:dind
asnyder:~$ docker run -it --link mydind:docker docker:latest sh
/ # docker run -d --network host httpd:alpine
/ # curl localhost:80
curl: (7) Failed to connect to localhost port 80: Connection refused
</code>```

Surprisingly, I was unable to find any existing articles on this. Does anyone here have some insight?

Thanks!

答:
There are pros and cons for both DinD and bind mounting the Docker socket and there are certainly use cases for both. As an example, check out this set of blog posts, which does a good job of explaining one of the use cases.

Given your example docker-in-docker setup above, you can access Apache httpd server in one of two ways:

1) From inside the docker:dind container, it will be available on localhost:8080.

2) From inside the docker:latest container, where you were trying to access it originally, it will be available on whatever hostname is set for the docker:dind container. In this case, you used --name mydind, therefore curl mydind:8080 would give you the standard Apache
It works!
.

Hope it makes sense!

Body:
I would like to network with a child docker container from a parent docker container, with a docker-in-docker setup.

Let's say I'm trying to connect to a simple Apache httpd server. When I run the httpd container on my host machine, everything works fine:

asnyder:~$ docker run -d -p 8080:80 httpd:alpine
asnyder:~$ curl localhost:8080

It works!

But when I do the same from a docker-in-docker setup, I get a Connection refused error:

asnyder:~$ docker run -d --name mydind --privileged docker:dind
asnyder:~$ docker run -it --link mydind:docker docker:latest sh
/ # docker run -d -p 8080:80 httpd:alpine
/ # curl localhost:8080
curl: (7) Failed to connect to localhost port 8080: Connection refused

I have tried a couple alterations without luck. Specifying the 0.0.0.0 interface:

asnyder:~$ docker run -d --name mydind --privileged docker:dind
asnyder:~$ docker run -it --link mydind:docker docker:latest sh
/ # docker run -d -p 0.0.0.0:8080:80 httpd:alpine
/ # curl 0.0.0.0:8080
curl: (7) Failed to connect to 0.0.0.0 port 8080: Connection refused

Using the host network:

asnyder:~$ docker run -d --name mydind --privileged docker:dind
asnyder:~$ docker run -it --link mydind:docker docker:latest sh
/ # docker run -d --network host httpd:alpine
/ # curl localhost:80
curl: (7) Failed to connect to localhost port 80: Connection refused

Surprisingly, I was unable to find any existing articles on this. Does anyone here have some insight?

Thanks!

Body:
There are pros and cons for both DinD and bind mounting the Docker socket and there are certainly use cases for both. As an example, check out this set of blog posts, which does a good job of explaining one of the use cases.

Given your example docker-in-docker setup above, you can access Apache httpd server in one of two ways:

1) From inside the docker:dind container, it will be available on localhost:8080.

2) From inside the docker:latest container, where you were trying to access it originally, it will be available on whatever hostname is set for the docker:dind container. In this case, you used --name mydind, therefore curl mydind:8080 would give you the standard Apache <html><body><h1>It works!</h1></body></html>.

Hope it makes sense!


问:
After animation in CSS the object changes position a little bit
I am trying to make a login page, and I want an animation of the input swiping in from below. This is the code:

body {
  padding: 0;
  margin: 0;
}

form {
  position: absolute;
  display: block;
  height: 80%;
  width: 100%;
  left: 0;
  top: 20%;
  text-align: center;
  animation: swipein .5s forwards;
}

@keyframes swipein {
  from {
    top: 30%
  }
  to {
    top: 20%
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div>
    <form>
      <input type="text" placeholder="username"><br>
      <input type="password" placeholder="password">
    </form>
  </div>
</body></code>```

But after the animation ends, the input moves a little bit to the right, as you can see in this jsfiddle link. Why does that happen, and how can I fix it?

答:
The form height is 80%, and the starting top is 30%. Together they are higher than the body height, and this creates a scroll bar on the right. After the animation ends, the top is 20%, and the scrollbar disappears. When the scrollbar disappear form jumps right.

If you remove the form's height, you won't get the height overflow and the scrollbar.

body {
  padding: 0;
  margin: 0;
}

form {
  position: absolute;
  display: block;
  width: 100%;
  left: 0;
  top: 20%;
  text-align: center;
  animation: swipein .5s forwards;
}

@keyframes swipein {
  from{top:30%}
  to{top:20%}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div>
    <form>
      <input type="text" placeholder="username"><br>
      <input type="password" placeholder="password">
    </form>
  </div>
</body></code>```

Body:
I am trying to make a login page, and I want an animation of the input swiping in from below. This is the code:

body {
  padding: 0;
  margin: 0;
}

form {
  position: absolute;
  display: block;
  height: 80%;
  width: 100%;
  left: 0;
  top: 20%;
  text-align: center;
  animation: swipein .5s forwards;
}

@keyframes swipein {
  from {
    top: 30%
  }
  to {
    top: 20%
  }
}

    <form>
      <input type="text" placeholder="username">

      <input type="password" placeholder="password">
    </form>

But after the animation ends, the input moves a little bit to the right, as you can see in this jsfiddle link. Why does that happen, and how can I fix it?

Body:
The form height is 80%, and the starting top is 30%. Together they are higher than the body height, and this creates a scroll bar on the right. After the animation ends, the top is 20%, and the scrollbar disappears. When the scrollbar disappear form jumps right.

If you remove the form's height, you won't get the height overflow and the scrollbar.

body {
  padding: 0;
  margin: 0;
}

form {
  position: absolute;
  display: block;
  width: 100%;
  left: 0;
  top: 20%;
  text-align: center;
  animation: swipein .5s forwards;
}

@keyframes swipein {
  from{top:30%}
  to{top:20%}
}

<body>
  <div>
    <form>
      <input type="text" placeholder="username"><br>
      <input type="password" placeholder="password">
    </form>
  </div>
</body>


问:
How to subset a linnet object
I would like to subset a linnet object to get a list of linnet objects. In the helpfile I see that this is possible with a owin object. But I get errors as the syntax is not clear to me and also not clear is the use of snip argument in the call to subset.

I want to split linnet based on a user-attribute coming from marks or split a linnet object based on a windows (each window being a polygon from an shapefile)

Could someone please suggest how to subset a linnet based on a factor/window to get a list of linnet objects:

Using a user attribute/factor/mark on line segments.
Same values of marks are on contagious line segments, so this is ideally similar to using a window.

Using polygons as owin.

Thank you

答:
If L is a network and P is a polygonal window then L[P] computes the intersection of L and P.

The help file for [.linnet includes examples which demonstrate the syntax of this command and which show the effect of the argument snip.

Title: How to subset a linnet object


问:
change the image doesnt work
here is my javasript:

```<code>$(function() {
    $(".image2").click(function() {
        var image = $(this).attr("rel");
        $('#random_img').hide();
        $('#random_img').fadeIn('slow');
        $('#random_img').attr('src') == image;
        var image2 = $('#random_img').attr('src');
        $("#thumb2 a img").removeClass("open");
        $("#thumb2 a[rel='" + image2 + "'] img").addClass("open");
        return false;
    });
});
</code>```

here is my html:

```<code><div id="image2">
    <img id="random_img" src="/documents/templates/projedepo/banner/indigovision.jpg" height="420" width="964" />
</div>
<div id="thumb2">
    <a href="#" rel="/documents/templates/projedepo/banner/canon.jpg" class="image2">
        <img title="Canon" class="slider_thumb" src="/documents/templates/bilgiteknolojileri/images/t_flash/t1.png" border="0"/></a>
    <a href="#" rel="/documents/templates/projedepo/banner/indigovision.jpg" class="image2">
        <img title="IndigoVision" class="slider_thumb" src="/documents/templates/bilgiteknolojileri/images/t_flash/t2.png" border="0"/>
    </a>
</div>
</code>```

when i click on a thumbnail, the animation fadeIn and hide works, but the image is not changed...why?

答:
Thank u @Shurdoof! now everything works fine!
here is the solution:</p>

```<code>$('#random_img').attr('src',image);
</code>```

Title: change the image doesnt work

Body:
here is my javasript:

$(function() {
    $(".image2").click(function() {
        var image = $(this).attr("rel");
        $('#random_img').hide();
        $('#random_img').fadeIn('slow');
        $('#random_img').attr('src') == image;
        var image2 = $('#random_img').attr('src');
        $("#thumb2 a img").removeClass("open");
        $("#thumb2 a[rel='" + image2 + "'] img").addClass("open");
        return false;
    });
});

here is my html:

when i click on a thumbnail, the animation fadeIn and hide works, but the image is not changed...why?

Body:
Thank u @Shurdoof! now everything works fine!
here is the solution:

$('#random_img').attr('src',image);


答:
the change is caused by the scrollbar, you need to hide it to fix the problem

add overflow: hidden; to body

body {
  padding: 0;
  margin: 0;
  overflow: hidden;
}

form {
  position: absolute;
  display: block;
  height: 80%;
  width: 100%;
  left: 0;
  top: 20%;
  text-align: center;
  animation: swipein .5s forwards;
}

@keyframes swipein {
  from {
    top: 30%
  }
  to {
    top: 20%
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div>
    <form>
      <input type="text" placeholder="username"><br>
      <input type="password" placeholder="password">
    </form>
  </div>
</body></code>```

Title: After animation in CSS the object changes position a little bit

Body:
the change is caused by the scrollbar, you need to hide it to fix the problem

add overflow: hidden; to body

body {
  padding: 0;
  margin: 0;
  overflow: hidden;
}

form {
  position: absolute;
  display: block;
  height: 80%;
  width: 100%;
  left: 0;
  top: 20%;
  text-align: center;
  animation: swipein .5s forwards;
}

@keyframes swipein {
  from {
    top: 30%
  }
  to {
    top: 20%
  }
}

<body>
  <div>
    <form>
      <input type="text" placeholder="username"><br>
      <input type="password" placeholder="password">
    </form>
  </div>
</body>


问:
iOS Colors Incorrect When Saving Animated Gif
I am having this very strange issue. I am creating animated gifs from UIImages and most of the time they come out correct. However when I start to get into larger size images my colors start to disappear. For example if I do a 4 frame 32 x 32 pixel image with no more than 10 colors no issue. If I scale the same image up to 832 x 832 I lose a pink color and my brown turns green.

@1x 32 x 32

@10x 320 x 320

@26x 832 x 832

Here is the code I use to create the gif...

```<code>var kFrameCount = 0

for smdLayer in drawingToUse!.layers{
    if !smdLayer.hidden {
        kFrameCount += 1
    }
}

let loopingProperty = [String(kCGImagePropertyGIFLoopCount): 0]
let fileProperties: [String: AnyObject] = [String(kCGImagePropertyGIFDictionary): loopingProperty as AnyObject];

let frameProperty = [String(kCGImagePropertyGIFDelayTime):  Float(speedLabel.text!)!]
let frameProperties: [String: AnyObject] = [String(kCGImagePropertyGIFDictionary): frameProperty as AnyObject];

let documentsDirectoryPath = "file://\(NSTemporaryDirectory())"

if let documentsDirectoryURL = URL(string: documentsDirectoryPath){

    let fileURL = documentsDirectoryURL.appendingPathComponent("\(drawing.name)\(getScaleString()).gif")
    let destination = CGImageDestinationCreateWithURL(fileURL as CFURL, kUTTypeGIF, kFrameCount, nil)!

    CGImageDestinationSetProperties(destination, fileProperties as CFDictionary);

    for smdLayer in drawingToUse!.layers{

        if !smdLayer.hidden{

            let image = UIImage(smdLayer: smdLayer, alphaBlend: useAlphaLayers, backgroundColor: backgroundColorButton.backgroundColor!, scale: scale)
            CGImageDestinationAddImage(destination, image.cgImage!, frameProperties as CFDictionary)
        }
    }

    if (!CGImageDestinationFinalize(destination)) {
        print("failed to finalize image destination")
    }
}
</code>```

I have put in a break point right before I call CGImageDestinationAddImage(destination, image.cgImage!, frameProperties as CFDictionary) and the image is perfectly fine with the correct colors. I hope someone out there knows what I am missing.

Update

Here is a sample project. Note that although it isn't animated in the preview it is saving an animated gif and I log out the location of the image in the console.

https://www.dropbox.com/s/pb52awaj8w3amyz/gifTest.zip?dl=0

Body:
I am having this very strange issue. I am creating animated gifs from UIImages and most of the time they come out correct. However when I start to get into larger size images my colors start to disappear. For example if I do a 4 frame 32 x 32 pixel image with no more than 10 colors no issue. If I scale the same image up to 832 x 832 I lose a pink color and my brown turns green.

@1x 32 x 32

@10x 320 x 320

@26x 832 x 832

Here is the code I use to create the gif...

var kFrameCount = 0

for smdLayer in drawingToUse!.layers{
    if !smdLayer.hidden {
        kFrameCount += 1
    }
}

let loopingProperty = [String(kCGImagePropertyGIFLoopCount): 0]
let fileProperties: [String: AnyObject] = [String(kCGImagePropertyGIFDictionary): loopingProperty as AnyObject];

let frameProperty = [String(kCGImagePropertyGIFDelayTime):  Float(speedLabel.text!)!]
let frameProperties: [String: AnyObject] = [String(kCGImagePropertyGIFDictionary): frameProperty as AnyObject];

let documentsDirectoryPath = "file://\(NSTemporaryDirectory())"

if let documentsDirectoryURL = URL(string: documentsDirectoryPath){

    let fileURL = documentsDirectoryURL.appendingPathComponent("\(drawing.name)\(getScaleString()).gif")
    let destination = CGImageDestinationCreateWithURL(fileURL as CFURL, kUTTypeGIF, kFrameCount, nil)!

    CGImageDestinationSetProperties(destination, fileProperties as CFDictionary);

    for smdLayer in drawingToUse!.layers{

        if !smdLayer.hidden{

            let image = UIImage(smdLayer: smdLayer, alphaBlend: useAlphaLayers, backgroundColor: backgroundColorButton.backgroundColor!, scale: scale)
            CGImageDestinationAddImage(destination, image.cgImage!, frameProperties as CFDictionary)
        }
    }

    if (!CGImageDestinationFinalize(destination)) {
        print("failed to finalize image destination")
    }
}

I have put in a break point right before I call CGImageDestinationAddImage(destination, image.cgImage!, frameProperties as CFDictionary) and the image is perfectly fine with the correct colors. I hope someone out there knows what I am missing.

Update

Here is a sample project. Note that although it isn't animated in the preview it is saving an animated gif and I log out the location of the image in the console.

https://www.dropbox.com/s/pb52awaj8w3amyz/gifTest.zip?dl=0

Body:
Following on, here's some more background on the quantisation fail that is occurring. If you run the GIF output through imagemagick to extract the colour palettes for the version with a global colour map vs. a per-frame colour map, there is some insight into the root of the problem:

The version with GLOBAL colour map:

$ convert test.gif -format %c -depth 8  histogram:info:-
     28392: (  0,  0,  0,255) #000000FF black
    240656: ( 71,162, 58,255) #47A23AFF srgba(71,162,58,1)
    422500: (147,221,253,255) #93DDFDFF srgba(147,221,253,1)
       676: (255,255,255,255) #FFFFFFFF white
      2704: ( 71,162, 58,255) #47A23AFF srgba(71,162,58,1)
       676: (147,221,253,255) #93DDFDFF srgba(147,221,253,1)
      2704: ( 71,162, 58,255) #47A23AFF srgba(71,162,58,1)
       676: (147,221,253,255) #93DDFDFF srgba(147,221,253,1)
      2704: ( 71,162, 58,255) #47A23AFF srgba(71,162,58,1)
       676: (147,221,253,255) #93DDFDFF srgba(147,221,253,1)

The version with per-frame colour maps:

$ convert test.gif -format %c -depth 8  histogram:info:-
     28392: (  0,  0,  0,255) #000000FF black
    237952: ( 71,163, 59,255) #47A33BFF srgba(71,163,59,1)
      2704: (113, 78,  0,255) #714E00FF srgba(113,78,0,1)
    421824: (147,221,253,255) #93DDFDFF srgba(147,221,253,1)
       676: (246, 81,249,255) #F651F9FF srgba(246,81,249,1)
       676: (255,255,255,255) #FFFFFFFF white
     28392: (  0,  0,  0,255) #000000FF black
    237952: ( 71,163, 59,255) #47A33BFF srgba(71,163,59,1)
      2704: (113, 78,  0,255) #714E00FF srgba(113,78,0,1)
    421824: (147,221,253,255) #93DDFDFF srgba(147,221,253,1)
       676: (246, 81,249,255) #F651F9FF srgba(246,81,249,1)
       676: (255,255,255,255) #FFFFFFFF white
     28392: (  0,  0,  0,255) #000000FF black
    237952: ( 71,163, 59,255) #47A33BFF srgba(71,163,59,1)
      2704: (113, 78,  0,255) #714E00FF srgba(113,78,0,1)
    421824: (147,221,253,255) #93DDFDFF srgba(147,221,253,1)
       676: (246, 81,249,255) #F651F9FF srgba(246,81,249,1)
       676: (255,255,255,255) #FFFFFFFF white
     28392: (  0,  0,  0,255) #000000FF black
    237952: ( 71,163, 59,255) #47A33BFF srgba(71,163,59,1)
      2704: (113, 78,  0,255) #714E00FF srgba(113,78,0,1)
    421824: (147,221,253,255) #93DDFDFF srgba(147,221,253,1)
       676: (246, 81,249,255) #F651F9FF srgba(246,81,249,1)
       676: (255,255,255,255) #FFFFFFFF white

So the first one is missing the brown and pink, the colours with 246 and 113 in the red channel are not listed at all, and these are listed correctly in the histogram (presumably repeated for every frame in the longer output) for the per-frame colour map version.

This is proof that the palette is generated incorrectly in the GIF, which is what we see easily with our eyes. However, what makes me wonder is that the global colour map version has duplicate entries for several colours. This points at a pretty clear bug in palette quantisation in ImageIO. There should be no duplicate entries in a limited colour palette.

In short: do not rely on Core Graphics to quantise your 24-bit RGB images. Pre-quantise them in advance before sending them to ImageIO and turn off global colour maps. If the problem still manifests then, ImageIO palette writing is broken and you should use a different GIF output library


问:
Find a substring and print it
I have this string

```<code>$string = "create or replace view COMPLEX_NAME_2 (b21d,21ld21)";
</code>```

I want to get the COMPLEX_NAME_2 and print it.

Keep in mind that that COMPLEX_NAME_2 is the sub string I need to find and it changes its value. I don't know how to get the substring in that place in the string—the value of the substring doesn't matter.

I tried

```<code>$string =~ m/view/gi;
print $';
</code>```

But the problem it is that it prints (b21d,21ld21) as well and I need only the name.

答:
You can slightly alter your current approach to add a capture group to extract the view name from your query.  Then, access that capture group using the special variable $1 after making the match.

```<code>$string="create or replace view COMPLEX_NAME_2 (b21d,21ld21)";
if ($string=~m/view\s+(\S+)/) {
    print $1;
} else {
    print "no match";
}
</code>```

Demo here:

Rextester

Title: Find a substring and print it

Body:
I have this string

$string = "create or replace view COMPLEX_NAME_2 (b21d,21ld21)";

I want to get the COMPLEX_NAME_2 and print it.

Keep in mind that that COMPLEX_NAME_2 is the sub string I need to find and it changes its value. I don't know how to get the substring in that place in the string—the value of the substring doesn't matter.

I tried

$string =~ m/view/gi;
print $';

But the problem it is that it prints (b21d,21ld21) as well and I need only the name.

Body:
You can slightly alter your current approach to add a capture group to extract the view name from your query.  Then, access that capture group using the special variable $1 after making the match.

$string="create or replace view COMPLEX_NAME_2 (b21d,21ld21)";
if ($string=~m/view\s+(\S+)/) {
    print $1;
} else {
    print "no match";
}

Demo here:

Rextester