问:
Why won't WPF choose the right DataTemplate in my case?
I have 4 classes in my ViewModel that implements the IPage interface (an interface I created). In the ViewModel of my app I've a CurrentPage Property of IPage type.

In the View layer of my app, I've a ContentControl which Content is bound to the CurrentPage property.

So, when I'm using the following code WPF won't find the right DataTemplate

```<code><UserControl ...>
    <ContentControl Content="{Binding CurrentPage, Mode=OneWay}"
                    VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
        <ContentControl.Resources>
            <DataTemplate DataType="{x:Type operation:OperationListPageVM}">
                <pages1:OperationListPageV/>
            </DataTemplate>
            <DataTemplate DataType="{x:Type operation:OperationDetailPageVM}">
                <pages1:OperationDetailPageV/>
            </DataTemplate>
            <DataTemplate DataType="{x:Type part:PartListPageVM}">
                <pages1:PartListPageV/>
            </DataTemplate>
            <DataTemplate DataType="{x:Type part:PartDetailPageVM}">
                <pages1:PartDetailPageV/>
            </DataTemplate>
            <DataTemplate DataType="{x:Type pages:SettingsPageVM}">
                <pages1:SettingsPageV/>
            </DataTemplate>
        </ContentControl.Resources>
    </ContentControl>
</UserControl>
</code>```

But if I only put one DataTemplate as ContentControl.ContentTemplate then it'll apply it correctly

```<code><UserControl ...>
    <ContentControl Content="{Binding CurrentPage, Mode=OneWay}"
                    VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
        <ContentControl.ContentTemplate>
            <DataTemplate DataType="{x:Type operation:OperationListPageVM}">
                <pages1:OperationListPageV/>
            </DataTemplate>
        </ContentControl.ContentTemplate>
    </ContentControl>
</UserControl>
</code>```

If I then put those DataTemplates back as resources, give them a key and create a DataTemplateSelector and add

```<code>ContentTemplateSelector="{StaticResource PageTemplateSelector}"
</code>```

To the ControlTemplate with the DataTemplateSelector as this:

```<code>using System.Windows;
using System.Windows.Controls;
using MaintenanceModuleV3.ViewModel;
using MaintenanceModuleV3.ViewModel.Pages;
using MaintenanceModuleV3.ViewModel.Pages.Operation;
using MaintenanceModuleV3.ViewModel.Pages.Part;

namespace MaintenanceModuleV3.View.TemplateSelector {
    public class PageTemplateSelector : DataTemplateSelector {
        public override DataTemplate SelectTemplate(object item, DependencyObject container) {
            if (AppVM.Instance.CurrentPage != null) {
                if (AppVM.Instance.CurrentPage is OperationListPageVM) {
                    return (container as FrameworkElement).FindResource("OperationListPageTemplate") as DataTemplate;
                } else if (AppVM.Instance.CurrentPage is OperationDetailPageVM) {
                    return (container as FrameworkElement).FindResource("OperationDetailPageTemplate") as DataTemplate;
                } else if (AppVM.Instance.CurrentPage is PartListPageVM) {
                    return (container as FrameworkElement).FindResource("PartListPageTemplate") as DataTemplate;
                } else if (AppVM.Instance.CurrentPage is PartDetailPageVM) {
                    return (container as FrameworkElement).FindResource("PartDetailPageTemplate") as DataTemplate;
                } else if (AppVM.Instance.CurrentPage is SettingsPageVM) {
                    return (container as FrameworkElement).FindResource("SettingsPageTemplate") as DataTemplate;
                }
            }
            return null;
        }
    }
}
</code>```

Then the right DataTemplate is choosen.

Why won't WPF choose the right DataTemplate if I put DataTemplates in the element resources in this case?

Thank you

NB: Using Framework 3.5

EDIT: I noticed a second problem: the DataContext inside the DataTemplates are null. Why is that? Why won't they take CurrentPage as DataContext? This is the case when I directly set the ContentTemplate too. WPF seems not to like bindings to interface typed properties.

EDIT 2: If I set the DataContext of the OperationListPageV explicitly in its constructor and use TemplateSelector everything works, but why do I have to use those?

EDIT 3: The full ViewModel code, if it helps:

The app ViewModel

```<code>public class AppVM : INotifyPropertyChanged {

    #region constructor
    private AppVM() {
        AppM.LanguageChanged += (sender, args) => {
            onPropertyChanged("CurrentLanguage");
        };

        AppM.NbDaysAvgChanged += (sender, args) => {
            onPropertyChanged("NbDaysAvg");
        };

        AppM.NbDaysMenuNotificationChanged += (sender, args) => {
            onPropertyChanged("NbDaysMenuNotification");
        };
    }
    #endregion

    #region business

    #endregion

    #region events
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void onPropertyChanged(string propertyName) {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion

    #region properties

    private static AppVM _instance;
    public static AppVM Instance {
        get { return _instance ?? (_instance = new AppVM()); }
    }

    #region notifypropertychanged
    private OperationListPageVM _currentPage = OperationListPageVM.Instance;
    public OperationListPageVM CurrentPage {
        get { return _currentPage; }
        set {
            _currentPage = value;
            onPropertyChanged("CurrentPage");
        }
    }

    public Language CurrentLanguage {
        get { return AppM.CurrentLanguage; }
    }

    public int NbDaysMenuNotification {
        get { return AppM.NbDaysMenuNotification; }
    }

    public int NbDaysAvg {
        get { return AppM.NbDaysAvg; }
    }

    public Dictionary<String, String> AvailableTranslations {
        get { return AppM.AvailableTranslations; }
    }
    #endregion
    #region commands
    #endregion
    #endregion
}
</code>```

The page I was to display ViewModel

```<code>public sealed class OperationListPageVM : INotifyPropertyChanged, IPage {

    #region constructor
    private OperationListPageVM() {
        //fill the available operations with data stored in the App Model coming from the DataBase
        foreach (MaintenanceOperation operation in AppM.Operations) {
            AvailableOperations.Add(new MaintenanceOperationVM(operation));
        }
        foreach (MaintenanceOperationVM operation in AvailableOperations) {
            DisplayedOperations.Add(operation);
        }
    }
    #endregion

    #region business

    #endregion

    #region events
    public event PropertyChangedEventHandler PropertyChanged;

    private void onPropertyChanged(string propertyName) {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion

    #region properties

    private static OperationListPageVM _instance;

    public static OperationListPageVM Instance {
        get { return _instance ?? (_instance = new OperationListPageVM()); }
    }

    #region notifypropertychanged
    private ObservableCollection<MaintenanceOperationVM> _displayedOperations = new ObservableCollection<MaintenanceOperationVM>();
    public ObservableCollection<MaintenanceOperationVM> DisplayedOperations {
        get { return _displayedOperations; }
        set {
            _displayedOperations = value;
            onPropertyChanged("DisplayedOperations");
        }
    }

    private readonly List<MaintenanceOperationVM> _availableOperations = new List<MaintenanceOperationVM>();

    internal List<MaintenanceOperationVM> AvailableOperations {
        get { return _availableOperations; }
    }

    #endregion

    #region commands

    #endregion

    #endregion
}
</code>```

The View layer of the page I was to display (OperationListPageV)

```<code><UserControl x:Class="MaintenanceModuleV3.View.Pages.OperationListPageV"
            ...>
    <touch:ScrollFriction2>
        <ListBox ItemsSource="{Binding DisplayedOperations}">
                <ListBox.ItemContainerStyle>
                    <Style TargetType="{x:Type ListBoxItem}">
                        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
                    </Style>
                </ListBox.ItemContainerStyle>
            <ListBox.ItemTemplate>
                <DataTemplate DataType="{x:Type viewModel:MaintenanceOperationVM}">
                    <view:MaintenanceOperationV/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </touch:ScrollFriction2>
</UserControl>
</code>```

If you need more code just ask for it. Thank you!

答: put the templates in Resources of your ItemControl. I don't know why they made it this way, but they should be one level above your ContentControl</p>

Body:
I have 4 classes in my ViewModel that implements the IPage interface (an interface I created). In the ViewModel of my app I've a CurrentPage Property of IPage type.

In the View layer of my app, I've a ContentControl which Content is bound to the CurrentPage property.

So, when I'm using the following code WPF won't find the right DataTemplate

<UserControl ...>
    <ContentControl Content="{Binding CurrentPage, Mode=OneWay}"
                    VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
        <ContentControl.Resources>
            <DataTemplate DataType="{x:Type operation:OperationListPageVM}">
                <pages1:OperationListPageV/>
            </DataTemplate>
            <DataTemplate DataType="{x:Type operation:OperationDetailPageVM}">
                <pages1:OperationDetailPageV/>
            </DataTemplate>
            <DataTemplate DataType="{x:Type part:PartListPageVM}">
                <pages1:PartListPageV/>
            </DataTemplate>
            <DataTemplate DataType="{x:Type part:PartDetailPageVM}">
                <pages1:PartDetailPageV/>
            </DataTemplate>
            <DataTemplate DataType="{x:Type pages:SettingsPageVM}">
                <pages1:SettingsPageV/>
            </DataTemplate>
        </ContentControl.Resources>
    </ContentControl>
</UserControl>

But if I only put one DataTemplate as ContentControl.ContentTemplate then it'll apply it correctly

<UserControl ...>
    <ContentControl Content="{Binding CurrentPage, Mode=OneWay}"
                    VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
        <ContentControl.ContentTemplate>
            <DataTemplate DataType="{x:Type operation:OperationListPageVM}">
                <pages1:OperationListPageV/>
            </DataTemplate>
        </ContentControl.ContentTemplate>
    </ContentControl>
</UserControl>

If I then put those DataTemplates back as resources, give them a key and create a DataTemplateSelector and add

ContentTemplateSelector="{StaticResource PageTemplateSelector}"

To the ControlTemplate with the DataTemplateSelector as this:

using System.Windows;
using System.Windows.Controls;
using MaintenanceModuleV3.ViewModel;
using MaintenanceModuleV3.ViewModel.Pages;
using MaintenanceModuleV3.ViewModel.Pages.Operation;
using MaintenanceModuleV3.ViewModel.Pages.Part;

namespace MaintenanceModuleV3.View.TemplateSelector {
    public class PageTemplateSelector : DataTemplateSelector {
        public override DataTemplate SelectTemplate(object item, DependencyObject container) {
            if (AppVM.Instance.CurrentPage != null) {
                if (AppVM.Instance.CurrentPage is OperationListPageVM) {
                    return (container as FrameworkElement).FindResource("OperationListPageTemplate") as DataTemplate;
                } else if (AppVM.Instance.CurrentPage is OperationDetailPageVM) {
                    return (container as FrameworkElement).FindResource("OperationDetailPageTemplate") as DataTemplate;
                } else if (AppVM.Instance.CurrentPage is PartListPageVM) {
                    return (container as FrameworkElement).FindResource("PartListPageTemplate") as DataTemplate;
                } else if (AppVM.Instance.CurrentPage is PartDetailPageVM) {
                    return (container as FrameworkElement).FindResource("PartDetailPageTemplate") as DataTemplate;
                } else if (AppVM.Instance.CurrentPage is SettingsPageVM) {
                    return (container as FrameworkElement).FindResource("SettingsPageTemplate") as DataTemplate;
                }
            }
            return null;
        }
    }
}

Then the right DataTemplate is choosen.

Why won't WPF choose the right DataTemplate if I put DataTemplates in the element resources in this case?

Thank you

NB: Using Framework 3.5

EDIT: I noticed a second problem: the DataContext inside the DataTemplates are null. Why is that? Why won't they take CurrentPage as DataContext? This is the case when I directly set the ContentTemplate too. WPF seems not to like bindings to interface typed properties.

EDIT 2: If I set the DataContext of the OperationListPageV explicitly in its constructor and use TemplateSelector everything works, but why do I have to use those?

EDIT 3: The full ViewModel code, if it helps:

The app ViewModel

public class AppVM : INotifyPropertyChanged {

    #region constructor
    private AppVM() {
        AppM.LanguageChanged += (sender, args) => {
            onPropertyChanged("CurrentLanguage");
        };

        AppM.NbDaysAvgChanged += (sender, args) => {
            onPropertyChanged("NbDaysAvg");
        };

        AppM.NbDaysMenuNotificationChanged += (sender, args) => {
            onPropertyChanged("NbDaysMenuNotification");
        };
    }
    #endregion

    #region business

    #endregion

    #region events
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void onPropertyChanged(string propertyName) {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion

    #region properties

    private static AppVM _instance;
    public static AppVM Instance {
        get { return _instance ?? (_instance = new AppVM()); }
    }

    #region notifypropertychanged
    private OperationListPageVM _currentPage = OperationListPageVM.Instance;
    public OperationListPageVM CurrentPage {
        get { return _currentPage; }
        set {
            _currentPage = value;
            onPropertyChanged("CurrentPage");
        }
    }

    public Language CurrentLanguage {
        get { return AppM.CurrentLanguage; }
    }

    public int NbDaysMenuNotification {
        get { return AppM.NbDaysMenuNotification; }
    }

    public int NbDaysAvg {
        get { return AppM.NbDaysAvg; }
    }

    public Dictionary<String, String> AvailableTranslations {
        get { return AppM.AvailableTranslations; }
    }
    #endregion
    #region commands
    #endregion
    #endregion
}

The page I was to display ViewModel

public sealed class OperationListPageVM : INotifyPropertyChanged, IPage {

    #region constructor
    private OperationListPageVM() {
        //fill the available operations with data stored in the App Model coming from the DataBase
        foreach (MaintenanceOperation operation in AppM.Operations) {
            AvailableOperations.Add(new MaintenanceOperationVM(operation));
        }
        foreach (MaintenanceOperationVM operation in AvailableOperations) {
            DisplayedOperations.Add(operation);
        }
    }
    #endregion

    #region business

    #endregion

    #region events
    public event PropertyChangedEventHandler PropertyChanged;

    private void onPropertyChanged(string propertyName) {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion

    #region properties

    private static OperationListPageVM _instance;

    public static OperationListPageVM Instance {
        get { return _instance ?? (_instance = new OperationListPageVM()); }
    }

    #region notifypropertychanged
    private ObservableCollection<MaintenanceOperationVM> _displayedOperations = new ObservableCollection<MaintenanceOperationVM>();
    public ObservableCollection<MaintenanceOperationVM> DisplayedOperations {
        get { return _displayedOperations; }
        set {
            _displayedOperations = value;
            onPropertyChanged("DisplayedOperations");
        }
    }

    private readonly List<MaintenanceOperationVM> _availableOperations = new List<MaintenanceOperationVM>();

    internal List<MaintenanceOperationVM> AvailableOperations {
        get { return _availableOperations; }
    }

    #endregion

    #region commands

    #endregion

    #endregion
}

The View layer of the page I was to display (OperationListPageV)

<UserControl x:Class="MaintenanceModuleV3.View.Pages.OperationListPageV"
            ...>
    <touch:ScrollFriction2>
        <ListBox ItemsSource="{Binding DisplayedOperations}">
                <ListBox.ItemContainerStyle>

                </ListBox.ItemContainerStyle>
            <ListBox.ItemTemplate>
                <DataTemplate DataType="{x:Type viewModel:MaintenanceOperationVM}">
                    <view:MaintenanceOperationV/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </touch:ScrollFriction2>
</UserControl>

If you need more code just ask for it. Thank you!


来源: stackexchange

问:
Make docker machine available under host name in Windows
I'm trying to make a docker machine available to my Windows by a host name. After creating it like

```<code>docker-machine create -d virtualbox mymachine
</code>```

and setting up a docker container that exposes the port 80, how can I give that docker machine a host name such that I can enter "http://mymachine/" into my browser to load the website? When I change "mymachine" to the actual IP address then it works.

There is an answer to this question but I would like to achieve it without an entry in the hosts file. Is that possible?

答:
You might want to refer to docker documentaion:
https://docs.docker.com/engine/userguide/networking/#exposing-and-publishing-ports

You expose ports using the EXPOSE keyword in the Dockerfile or the
  --expose flag to docker run. Exposing ports is a way of documenting which ports are used, but does not actually map or open any ports.
  Exposing ports is optional.

You publish ports using the --publish or --publish-all flag to docker
  run. This tells Docker which ports to open on the container’s network
  interface. When a port is published, it is mapped to an available
  high-order port (higher than 30000) on the host machine, unless you
  specify the port to map to on the host machine at runtime. You cannot
  specify the port to map to on the host machine when you build the
  image (in the Dockerfile), because there is no way to guarantee that
  the port will be available on the host machine where you run the
  image.

I also suggest reviewing the -P flag as it differs from the -p one.

Also i suggest you try "Kitematic" for Windows or Mac, https://kitematic.com/ . It's much simpler (but dont forget to commit after any changes!)

Now concerning the network in your company, it has nothing to do with docker, as long as you're using docker locally on your computer it wont matter what configuration your company set. Even you dont have to change any VM network config in order to expose things to your local host, all comes by default if you're using Vbox ( adapter 1 ==> NAT & adapter 2 ==> host only )

hope this is what you're looking for

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to make a docker machine available to my Windows by a host name. After creating it like

docker-machine create -d virtualbox mymachine

and setting up a docker container that exposes the port 80, how can I give that docker machine a host name such that I can enter "http://mymachine/" into my browser to load the website? When I change "mymachine" to the actual IP address then it works.

There is an answer to this question but I would like to achieve it without an entry in the hosts file. Is that possible?


问:
Stuck in an infinite while loop
I am trying to write this code so that if the process reads map finished in the pipe it increments a variable by 1 so that it eventually breaks out of the while loop. Otherwise it will add unique parameters to a keys file. However it goes into an infinite loop and never breaks out of the loop.

```<code>while [ $a -le 5 ]; do
    read input < map_pipe;
    if [ $input = "map finished" ]; then
            ((a++))
            echo $a
    else
            sort -u map_pipe >> keys.txt;
    fi
done
</code>```

答:
I decided to fix it for you, not sure if this is what you wanted, but I think I am close:</p>

```<code>#!/bin/bash
a=0 #Initialize your variable to something
while [ $a -le 5 ]; do
    read input < map_pipe;
    if [ "$input" = "map finished" ]; then #Put double quotes around variables to allow values with spaces
        a=$(($a + 1)) #Your syntax was off, use spaces and do something with the output
    else
        echo $input >> keys.txt #Don't re-read the pipe, it's empty by now and sort will wait for the next input
        sort -u keys.txt > tmpfile #Instead sort your file, don't save directly into the same file it will break
        mv tmpfile keys.txt
        #sort -u keys.txt | sponge keys.txt #Will also work instead of the other sort and mv, but sponge is not installed on most machines
    fi
done
</code>```

Title: Stuck in an infinite while loop

Body:
I am trying to write this code so that if the process reads map finished in the pipe it increments a variable by 1 so that it eventually breaks out of the while loop. Otherwise it will add unique parameters to a keys file. However it goes into an infinite loop and never breaks out of the loop.

while [ $a -le 5 ]; do
    read input < map_pipe;
    if [ $input = "map finished" ]; then
            ((a++))
            echo $a
    else
            sort -u map_pipe >> keys.txt;
    fi
done

Body:
I decided to fix it for you, not sure if this is what you wanted, but I think I am close:

#!/bin/bash
a=0 #Initialize your variable to something
while [ $a -le 5 ]; do
    read input < map_pipe;
    if [ "$input" = "map finished" ]; then #Put double quotes around variables to allow values with spaces
        a=$(($a + 1)) #Your syntax was off, use spaces and do something with the output
    else
        echo $input >> keys.txt #Don't re-read the pipe, it's empty by now and sort will wait for the next input
        sort -u keys.txt > tmpfile #Instead sort your file, don't save directly into the same file it will break
        mv tmpfile keys.txt
        #sort -u keys.txt | sponge keys.txt #Will also work instead of the other sort and mv, but sponge is not installed on most machines
    fi
done


问:
Linux command: How to 'find' only text files?
After a few searches from Google, what I come up with is:

```<code>find my_folder -type f -exec grep -l "needle text" {} \; -exec file {} \; | grep text
</code>```

which is very unhandy and outputs unneeded texts such as mime type information. Any better solutions? I have lots of images and other binary files in the same folder with a lot of text files that I need to search through.

答:
How about this</p>

```<code> find . -type f|xargs grep "needle text"
</code>```

ContentLicense: CC BY-SA 2.5

Body:
After a few searches from Google, what I come up with is:

find my_folder -type f -exec grep -l "needle text" {} \; -exec file {} \; | grep text

which is very unhandy and outputs unneeded texts such as mime type information. Any better solutions? I have lots of images and other binary files in the same folder with a lot of text files that I need to search through.

Body:
How about this

 find . -type f|xargs grep "needle text"


问:
How to make button click listener event in Kotlin/JavaScript?
Inside IntellJ IDEA, I ve created a button in my HTML file with an id. What I'm trying to achieve is to change the  header tag to "button clicked" using kotlin.

Upon searching the kolinlang.org website and others resources I have trouble finding simple reference for doing specific things I wonder if there a translated kotlin/javascript site where all of them is put together like this site for example: https://www.w3schools.com/js/default.asp

Thanks

答:
Create a Kotlin/JS project in IntelliJ, named "JSProject"

Create an index.html file including a button with ID "mybutton"

Create a Kotlin file main.kt with the following content:

```<code>import org.w3c.dom.HTMLButtonElement
import kotlin.browser.document

fun main(args: Array<String>) {
    val button = document.getElementById("mybutton") as HTMLButtonElement
    button.addEventListener("click", {
        document.title = "button was clicked"
    })
}
</code>```

Import the Kotlin JS library and your code (JS compiled from Kotlin) in at the end of your HTML file:

```<code>       ...
       <script src="out/production/JSProject/lib/kotlin.js"></script>
       <script src="out/production/JSProject/JSProject.js"></script>
    </body>
    </html>
</code>```

Compile your Kotlin code to JS (menu: Build | Rebuild Project)

Open the index.html file in a web browser and click on the button. "button was clicked" appears in the title.

Body:
Create a Kotlin/JS project in IntelliJ, named "JSProject"

Create an index.html file including a button with ID "mybutton"

Create a Kotlin file main.kt with the following content:

import org.w3c.dom.HTMLButtonElement
import kotlin.browser.document

fun main(args: Array<String>) {
    val button = document.getElementById("mybutton") as HTMLButtonElement
    button.addEventListener("click", {
        document.title = "button was clicked"
    })
}

Import the Kotlin JS library and your code (JS compiled from Kotlin) in at the end of your HTML file:

       ...
       <script src="out/production/JSProject/lib/kotlin.js"></script>
       <script src="out/production/JSProject/JSProject.js"></script>
    </body>
    </html>

Compile your Kotlin code to JS (menu: Build | Rebuild Project)

Open the index.html file in a web browser and click on the button. "button was clicked" appears in the title.


问:
How can I compare two dates in PHP?
How can I compare two dates in PHP?

The date is stored in the database in the following format

2011-10-2

If I wanted to compare today's date against the date in the database to see which one is greater, how would I do it?

I tried this,

```<code>$today = date("Y-m-d");
$expire = $row->expireDate //from db

if($today < $expireDate) { //do something; }
</code>```

but it doesn't really work that way. What's another way of doing it?

答:
Here's a way on how to get the difference between two dates in minutes.

```<code>// set dates
$date_compare1= date("d-m-Y h:i:s a", strtotime($date1));
// date now
$date_compare2= date("d-m-Y h:i:s a", strtotime($date2));

// calculate the difference
$difference = strtotime($date_compare1) - strtotime($date_compare2);
$difference_in_minutes = $difference / 60;

echo $difference_in_minutes;
</code>```

ContentLicense: CC BY-SA 4.0

Title: How can I compare two dates in PHP?

Body:
How can I compare two dates in PHP?

The date is stored in the database in the following format

2011-10-2

If I wanted to compare today's date against the date in the database to see which one is greater, how would I do it?

I tried this,

$today = date("Y-m-d");
$expire = $row->expireDate //from db

if($today < $expireDate) { //do something; }

but it doesn't really work that way. What's another way of doing it?

Body:
Here's a way on how to get the difference between two dates in minutes.

// set dates
$date_compare1= date("d-m-Y h:i:s a", strtotime($date1));
// date now
$date_compare2= date("d-m-Y h:i:s a", strtotime($date2));

// calculate the difference
$difference = strtotime($date_compare1) - strtotime($date_compare2);
$difference_in_minutes = $difference / 60;

echo $difference_in_minutes;


问:
Removing part of condition in some cases
Is there a way to remove part of condition in IF statement depending if I need it or not. Next code is example, because in my code there are a lot of user defined functions and procedures in my language:

```<code>IF A THEN
Q := TQuery.Create(Application);
IF B AND C AND D AND E AND Q.FieldByName('Example').AsInteger = 1 then
BEGIN
...
END
</code>```

So, let's say after creating TQuery that I have imported some data into it (I didn't write that part of code here). Is there a way to remove part with Q in the second IF statement if the Q wasn't created (because the condition A was not satisfied) or do I have to writhe the whole IF statement again just without Q part?

I was thinking using something like CASE to check if Q is created and if it is not, just to skip that part of sentence. If it is possible, how can I skip it?

答:
Quick and dirty way

```<code>IF B AND C AND D AND E AND (NOT A OR Q.FieldByName('Example').AsInteger = 1) then
</code>```

As a note, try to keep your if conditions simpler.

```<code>EvaluationRequested := A AND C ...
QueryNeedsAval := NOT A OR ...
if EvaluationRequested AND QueryNeedsAval then
begin
   ...
end;
</code>```

Body:
Is there a way to remove part of condition in IF statement depending if I need it or not. Next code is example, because in my code there are a lot of user defined functions and procedures in my language:

IF A THEN
Q := TQuery.Create(Application);
IF B AND C AND D AND E AND Q.FieldByName('Example').AsInteger = 1 then
BEGIN
...
END

So, let's say after creating TQuery that I have imported some data into it (I didn't write that part of code here). Is there a way to remove part with Q in the second IF statement if the Q wasn't created (because the condition A was not satisfied) or do I have to writhe the whole IF statement again just without Q part?

I was thinking using something like CASE to check if Q is created and if it is not, just to skip that part of sentence. If it is possible, how can I skip it?

Body:
Quick and dirty way

IF B AND C AND D AND E AND (NOT A OR Q.FieldByName('Example').AsInteger = 1) then

As a note, try to keep your if conditions simpler.

EvaluationRequested := A AND C ...
QueryNeedsAval := NOT A OR ...
if EvaluationRequested AND QueryNeedsAval then
begin
   ...
end;


问:
Issue with RestSharp installation in Visual-Studio 2013
I am trying to use RestSharp in my C# Visual-Studio 2013 project to POST data at a given URL. When i try to install the package via NuGet it gives me the following error:

```<code>Installing 'RestSharp 106.1.0'.
Successfully installed 'RestSharp 106.1.0'.
Adding 'RestSharp 106.1.0' to WebApplicationJson.
Uninstalling 'RestSharp 106.1.0'.
Successfully uninstalled 'RestSharp 106.1.0'.
Install failed. Rolling back...
Could not install package 'RestSharp 106.1.0'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.5', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.
</code>```

As far as I have read in GitHub this is mostly an issue for .NetPortable framework so I am out of ideas. I have also tried to change my framework version to 3.5 but still the same error.

Has anyone encountered a similar issue?

If you need further information please comment.

答:
The latest version, which supports old .NET Framework versions, is 105.2.3.

```<code>Install-Package RestSharp -Version 105.2.3
</code>```

Since the lowest .NET Framework LTE, which supports async methods is 4.5.2, support of legacy framework has been removed in favour of supporting .NET Standard 2.0 (and .NET Framework 4.5.2).

Body:
I am trying to use RestSharp in my C# Visual-Studio 2013 project to POST data at a given URL. When i try to install the package via NuGet it gives me the following error:

Installing 'RestSharp 106.1.0'.
Successfully installed 'RestSharp 106.1.0'.
Adding 'RestSharp 106.1.0' to WebApplicationJson.
Uninstalling 'RestSharp 106.1.0'.
Successfully uninstalled 'RestSharp 106.1.0'.
Install failed. Rolling back...
Could not install package 'RestSharp 106.1.0'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.5', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

As far as I have read in GitHub this is mostly an issue for .NetPortable framework so I am out of ideas. I have also tried to change my framework version to 3.5 but still the same error.

Has anyone encountered a similar issue?

If you need further information please comment.

Body:
The latest version, which supports old .NET Framework versions, is 105.2.3.

Install-Package RestSharp -Version 105.2.3

Since the lowest .NET Framework LTE, which supports async methods is 4.5.2, support of legacy framework has been removed in favour of supporting .NET Standard 2.0 (and .NET Framework 4.5.2).


问:
How to create Synthea demographic County files?
I am using Synthea to generate synthetic populations using the default county demographics for Massachusetts.

How are these json config files created? Specifically, how could I create them for a different US State?

答:
First, you need to obtain several publicly available data files and place them into your ./resources folder.

I think you answered some of your own question over in this GitHub issue. But in case someone finds the question here, you need four different files.

“subcounty population estimates for towns and cities”
https://www.census.gov/data/datasets/2016/demo/popest/total-cities-and-towns.html

“county population estimates by age, gender, race, ethnicity”
https://www.census.gov/data/datasets/2016/demo/popest/counties-detail.html

“income data”
https://factfinder.census.gov/faces/tableservices/jsf/pages/productview.xhtml?pid=ACS_15_5YR_S1901&prodType=table

“Education data”
https://factfinder.census.gov/faces/tableservices/jsf/pages/productview.xhtml?pid=ACS_15_5YR_S1501&prodType=table

Once you obtain the files for the US State you are interested in:

Copy the files into your ./resources folder

git checkout other_usa_states The ability to process other states is not currently within the master branch in GitHub.

bundle exec rake synthea:census This will process the files in ./resources (you may need to rename the files) and generate the JSON configuration files into ./config

bundle exec rake synthea:generate[XXX.json] where XXX.json is the name of the county file within the ./config folder that you want to generate.

Caveats:

Geospatial lat/lon information will not be generated without additional data.

Zip codes outside of Massachusetts are stubbed to XXXXX

Hospital and healthcare facilities will seem odd, since only organizations in Massachusetts are included by default. It will seem like everyone in town travels across the country to go see their doctor in Massachusetts.

Those issues will be fixed in the future.


问:
Why am I getting OutOfMemory exceptions when I have plenty of memory?
I have a program (Fractal10) that executes a loop where the number of iterations depends on a parameter I set manually. When the number of iterations is small the program runs fine. When the number of iterations is large I get the following error:

```<code>Unhandled Exception: System.TypeInitializationException: The type initializer for '<StartupCode$Fractal10>.$Program' threw an exception. ---> System.AggregateException: One or more errors occurred. ---> System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
</code>```

I am running Windows 10 Professional with 16 GB of memory and 25600 MB of virtual memory on an Intel Haswell processor and the latest version of Microsoft Visual Studio 2017. After the exception is thrown, the Task Manager shows the following:

```<code>Memory: 64%
Fractal10 (32 bit)L 1,719.2 MB # this is the culprit
Microsoft Visual Studio 2017 (32 bit): 822.7 MB
... # other apps
</code>```

Why am I getting this error when only 64% of memory has been used? Is there anything I can do about it?

答:
First of all, is your OS 32 or 64bit? If it's the former, you won't actually have access to all of the installed memory.

Additionally, (and I'm assuming you're using the .Net framework, correct me if I'm wrong) you'll need to set your platform target to x64 inside your build configuration. On top of this, you can add the following config to your app.config file:

<runtime>
    <gcAllowVeryLargeObjects enabled="true" />
</runtime>

This will allow traversal of objects greater than 2GB.

Body:
I have a program (Fractal10) that executes a loop where the number of iterations depends on a parameter I set manually. When the number of iterations is small the program runs fine. When the number of iterations is large I get the following error:

Unhandled Exception: System.TypeInitializationException: The type initializer for '<StartupCode$Fractal10>.$Program' threw an exception. ---> System.AggregateException: One or more errors occurred. ---> System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.

I am running Windows 10 Professional with 16 GB of memory and 25600 MB of virtual memory on an Intel Haswell processor and the latest version of Microsoft Visual Studio 2017. After the exception is thrown, the Task Manager shows the following:

Memory: 64%
Fractal10 (32 bit)L 1,719.2 MB # this is the culprit
Microsoft Visual Studio 2017 (32 bit): 822.7 MB
... # other apps

Why am I getting this error when only 64% of memory has been used? Is there anything I can do about it?


问:
Inserting an object from a derived class into another instance of said object (using the vector.insert function) C++
I am currently working through code which has a Road class. This has a vector of lanes and includes a lane class. The lane class has a vector of vehicles and each vehicle has its derived classes (Car, Motorcycle, Lorry).
I would like a vehicle to be able to assess whether it can move into another lane, i.e. be inserted into another lane's vector of vehicles, safely (a car requires some safe distance, so I have already implemented how a vehicle knows if it is clear to switch lanes).

```<code>void Road::Simulate(double time)
{

for (unsigned int iLane = 0; iLane < getNLanes()-1; iLane++)
{
    for (unsigned int iV = 0; iV < getCurrentLane(iLane)->getNVehiclesinLane(); iV++)
    {
        std::cout<< " AllowedOvertake TEST "<<   getCurrentLane(iLane+1)->allowedOvertake(getCurrentLane(iLane)->getCurrentVehicle(iV)->getPosition(), getCurrentLane(iLane)->getCurrentVehicle(iV)->getMinDistance())<<std::endl;
        getCurrentLane(iLane+1)->setCanOvertake(allowedOvertake(getCurrentLane(iLane)->getCurrentVehicle(iV)->getPosition(), getCurrentLane(iLane)->getCurrentVehicle(iV)->getMinDistance()));

        if (getCurrentLane(iLane+1)->getCanOvertake() == true)
        {
            getCurrentLane(iLane+1)->insertVehicle(getCurrentLane(iLane)->getCurrentVehicle(iV), 0);
            delete getCurrentLane(iLane)->getCurrentVehicle(iV);
        }

    }
}
for (unsigned int iLane = 0; iLane < getNLanes(); iLane++)
{
    getCurrentLane(iLane)->Simulate(time);
</code>```

}
}

I loop over all the present lanes, except the last one as any vehicle in this lane cannot overtake. After looping over the vehicles contained in each lane, I have a function which returns a Boolean which confirms whether an overtake scenario can be executed. This is done in allowedOvertake(). If this returns true, I implement an insert function.

My issue/question: How can I make this ideology work, and whether it is sensible to have these setCanOvertake() and getCanOvertake() functions.

One possible solution could be to just pushback a new vehicle into the intended lane, but with the appropriate positions, velocities etc. However, I am not sure how to ensure that the vehicle being entered has the same type (Car, Lorry...) too.

Currently, I do not get any build errors if I exclude the insertVehicle() function, and I have vehicle motion being drawn using QPainter. However, with the insertVehicle()  function, I do not get any build errors but I do get a crash once I run the project.

Any help would be appreciated, and apologies for any coding errors (I'm a keen, but very inexperienced C++ user).

For reference, I have the above functions' definitions as follows

```<code>bool Lane::allowedOvertake(double pos, double mindist)
{
    for (unsigned int iV = 0; iV < getNVehiclesinLane() - 1; iV++)
    {
        if ((fVehicles[iV]->getPosition() > pos - mindist)// If inside rear safety distance.
            || fVehicles[iV]->getPosition() < pos + mindist)// If inside front safety distance.
       {}//continue
    else {return false;}
    }
return true;
}

//IN Lane.h
bool getCanOvertake() const{return FREE_LANE_OVERTAKE;}
//IN Lane.h
void setCanOvertake(bool overtake = true){FREE_LANE_OVERTAKE = overtake;}
</code>```

答:
Apologies, I was under the impression I had referenced my insertVehicle() function definition.</p>

```<code>void Lane::insertVehicle(Vehicle*v, int ielement) {

    Vehicle* vins = new Vehicle(v->getPosition(), v->getVelocity(), v->getAcceleration());

    for (unsigned int iDist = 0; iDist < fVehicles.size()+1; iDist++){fVehicles.insert(fVehicles.begin() + (ielement+1), vins);}
}
</code>```

Body:
I am currently working through code which has a Road class. This has a vector of lanes and includes a lane class. The lane class has a vector of vehicles and each vehicle has its derived classes (Car, Motorcycle, Lorry).
I would like a vehicle to be able to assess whether it can move into another lane, i.e. be inserted into another lane's vector of vehicles, safely (a car requires some safe distance, so I have already implemented how a vehicle knows if it is clear to switch lanes).

void Road::Simulate(double time)
{

for (unsigned int iLane = 0; iLane < getNLanes()-1; iLane++)
{
    for (unsigned int iV = 0; iV < getCurrentLane(iLane)->getNVehiclesinLane(); iV++)
    {
        std::cout<< " AllowedOvertake TEST "<<   getCurrentLane(iLane+1)->allowedOvertake(getCurrentLane(iLane)->getCurrentVehicle(iV)->getPosition(), getCurrentLane(iLane)->getCurrentVehicle(iV)->getMinDistance())<<std::endl;
        getCurrentLane(iLane+1)->setCanOvertake(allowedOvertake(getCurrentLane(iLane)->getCurrentVehicle(iV)->getPosition(), getCurrentLane(iLane)->getCurrentVehicle(iV)->getMinDistance()));

        if (getCurrentLane(iLane+1)->getCanOvertake() == true)
        {
            getCurrentLane(iLane+1)->insertVehicle(getCurrentLane(iLane)->getCurrentVehicle(iV), 0);
            delete getCurrentLane(iLane)->getCurrentVehicle(iV);
        }

    }
}
for (unsigned int iLane = 0; iLane < getNLanes(); iLane++)
{
    getCurrentLane(iLane)->Simulate(time);

}
}

I loop over all the present lanes, except the last one as any vehicle in this lane cannot overtake. After looping over the vehicles contained in each lane, I have a function which returns a Boolean which confirms whether an overtake scenario can be executed. This is done in allowedOvertake(). If this returns true, I implement an insert function.

My issue/question: How can I make this ideology work, and whether it is sensible to have these setCanOvertake() and getCanOvertake() functions.

One possible solution could be to just pushback a new vehicle into the intended lane, but with the appropriate positions, velocities etc. However, I am not sure how to ensure that the vehicle being entered has the same type (Car, Lorry...) too.

Currently, I do not get any build errors if I exclude the insertVehicle() function, and I have vehicle motion being drawn using QPainter. However, with the insertVehicle()  function, I do not get any build errors but I do get a crash once I run the project.

Any help would be appreciated, and apologies for any coding errors (I'm a keen, but very inexperienced C++ user).

For reference, I have the above functions' definitions as follows

bool Lane::allowedOvertake(double pos, double mindist)
{
    for (unsigned int iV = 0; iV < getNVehiclesinLane() - 1; iV++)
    {
        if ((fVehicles[iV]->getPosition() > pos - mindist)// If inside rear safety distance.
            || fVehicles[iV]->getPosition() < pos + mindist)// If inside front safety distance.
       {}//continue
    else {return false;}
    }
return true;
}

//IN Lane.h
bool getCanOvertake() const{return FREE_LANE_OVERTAKE;}
//IN Lane.h
void setCanOvertake(bool overtake = true){FREE_LANE_OVERTAKE = overtake;}

Body:
Apologies, I was under the impression I had referenced my insertVehicle() function definition.

void Lane::insertVehicle(Vehicle*v, int ielement) {

    Vehicle* vins = new Vehicle(v->getPosition(), v->getVelocity(), v->getAcceleration());

    for (unsigned int iDist = 0; iDist < fVehicles.size()+1; iDist++){fVehicles.insert(fVehicles.begin() + (ielement+1), vins);}
}


答: You should use 64 bit versions of your software if you intend to use more than ~1,8 GB of memory.</p>

Title: Why am I getting OutOfMemory exceptions when I have plenty of memory?


问:
convert different arrays to array of object using lodash or vanila js
I have different arrays of same size like this:

```<code>var a = ["x", "y", "z"];
var b = [1,2,3];
var c = ["l", "m", "n"];
</code>```

I want this to convert to an array of object like this:

```<code>final_array = [{a: 'x', b: 1, c: 'l'}, {a: 'y', b: 2, c: 'm'}, {a: 'z', b: 3, c: 'n'}]
</code>```

I know I can process the arrays using loops and somehow convert this in above format. What I have tried is this way (since size of all arrays will be same):

```<code>var final_array = [];
_.forEach(a, function(value, key){
  var each_list = {};
  each_list.a = a[key];
  each_list.b = b[key];
  each_list.c = c[key];
  final_array[key] = each_list;
})
console.log(final_array); // [{a: 'x', b: 1, c: 'l'}, {a: 'y', b: 2, c: 'm'}, {a: 'z', b: 3, c: 'n'}]
</code>```

But this seems to be a very lengthy way and I am sure there will be some good way to do this using lodash or some other approach.

Can any one please help me with this. I already have searched enough on stack overflow and lodash documentation but could not find a better approach for this.

答:
In plain ES6, you could use an object with short hand properties and iterate the keys and the the items of the arrays.

var a = ["x", "y", "z"],
    b = [1, 2, 3],
    c = ["l", "m", "n"],
    object = { a, b, c },
    result = Object.keys(object).reduce(function (r, k) {
        object[k].forEach((v, i) => (r[i] = r[i] || {})[k] = v);
        return r;
    }, []);

console.log(result);```

Body:
I have different arrays of same size like this:

var a = ["x", "y", "z"];
var b = [1,2,3];
var c = ["l", "m", "n"];

I want this to convert to an array of object like this:

final_array = [{a: 'x', b: 1, c: 'l'}, {a: 'y', b: 2, c: 'm'}, {a: 'z', b: 3, c: 'n'}]

I know I can process the arrays using loops and somehow convert this in above format. What I have tried is this way (since size of all arrays will be same):

var final_array = [];
_.forEach(a, function(value, key){
  var each_list = {};
  each_list.a = a[key];
  each_list.b = b[key];
  each_list.c = c[key];
  final_array[key] = each_list;
})
console.log(final_array); // [{a: 'x', b: 1, c: 'l'}, {a: 'y', b: 2, c: 'm'}, {a: 'z', b: 3, c: 'n'}]

But this seems to be a very lengthy way and I am sure there will be some good way to do this using lodash or some other approach.

Can any one please help me with this. I already have searched enough on stack overflow and lodash documentation but could not find a better approach for this.


问:
Can't test libgdx Project
I am busy with my project team writing a cross platform game using libgdx. I am trying to do the unit testing, currently I just imported classes and here is my code:

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;

import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.mygdx.game.*;
import com.mygdx.game.input.TouchInputProcessor;

public class CarTest {

    Car car;
    World world;
    Vector2 vector;

    @Before
    public void setUp() throws Exception {
        vector = new Vector2(0.0f, 0.0f);
        try {
            this.world = new World(vector, true);

            this.car = new Car(world, 2, 4, new Vector2(10, 10), (float) Math.PI,
                    60, 20, 60);
        } catch (Exception e) {
            e.getMessage();
        }

    }

    […]

}
```

<p>and we  get following error when running junit:</p>

```java.lang.ExceptionInInitializerError
at CarTest.setUp(CarTest.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

Caused by: com.badlogic.gdx.utils.GdxRuntimeException: Unable to read file for extraction: gdx-box2d64.dll
```

how can i make my  setup function for test work? or better how do you unit test libgdx projects ?

答:
Add the dependencies via testCompile in the project gradle script.</p>

```<code>testCompile "com.badlogicgames.gdx:gdx:$gdxVersion"
testCompile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
testCompile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"
testCompile "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-desktop"
</code>```

Title: Can't test libgdx Project

Body:
I am busy with my project team writing a cross platform game using libgdx. I am trying to do the unit testing, currently I just imported classes and here is my code:

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;

import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.mygdx.game.*;
import com.mygdx.game.input.TouchInputProcessor;

public class CarTest {

    Car car;
    World world;
    Vector2 vector;

    @Before
    public void setUp() throws Exception {
        vector = new Vector2(0.0f, 0.0f);
        try {
            this.world = new World(vector, true);

            this.car = new Car(world, 2, 4, new Vector2(10, 10), (float) Math.PI,
                    60, 20, 60);
        } catch (Exception e) {
            e.getMessage();
        }

    }

    […]

}

and we  get following error when running junit:

java.lang.ExceptionInInitializerError
at CarTest.setUp(CarTest.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

Caused by: com.badlogic.gdx.utils.GdxRuntimeException: Unable to read file for extraction: gdx-box2d64.dll

how can i make my  setup function for test work? or better how do you unit test libgdx projects ?

Body:
Add the dependencies via testCompile in the project gradle script.

testCompile "com.badlogicgames.gdx:gdx:$gdxVersion"
testCompile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
testCompile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"
testCompile "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-desktop"


问:
Create chat message layout
I have a problem with my chat message Layout in Android.

I have 3 custom textview, but the Time of textView should be set on Bottom and Right align.

Here is my screenshot:

And here is my code:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginRight="60dp"
    android:background="@drawable/msg_in"
    android:orientation="vertical">

    <com.fearefull.chatstory.Widgets.MyTextView
        android:id="@+id/nickname_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:autoLink="none"
        android:layout_alignParentLeft="true"
        android:paddingBottom="7dp"
        android:paddingLeft="16dp"
        android:paddingRight="12dp"
        android:paddingTop="5dp"
        android:text="adawd awdaw"
        android:textStyle="bold"
        android:textColor="@android:color/holo_green_light"
        android:textSize="18sp"
        tools:ignore="ObsoleteLayoutParam,RtlHardcoded" />

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <com.fearefull.chatstory.Widgets.MyTextView
            android:id="@+id/textview_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:autoLink="none"
            android:paddingBottom="7dp"
            android:paddingLeft="16dp"
            android:paddingRight="12dp"
            android:paddingTop="5dp"
            android:text="dlsadfafawfafawawfawf a fawfawfafafkawmflaknfalfntigtggt"
            android:textColor="@android:color/black"
            android:textSize="17sp"
            tools:ignore="ObsoleteLayoutParam,RtlHardcoded" />

        <com.fearefull.chatstory.Widgets.MyTextView
            android:id="@+id/textview_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="11:15 PM"
            android:textColor="#a6abad"
            android:textSize="12sp"
            android:layout_alignBottom="@id/textview_message"
            android:layout_alignParentRight="true"
            android:padding="5dp"
            tools:ignore="RtlHardcoded" />
    </RelativeLayout>

</LinearLayout>
```

I used any Alignment for my Time of textView, but it didn't work.

答:
Try this

```<code><LinearLayout android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_marginRight="60dp"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <com.fearefull.chatstory.Widgets.MyTextView
        android:id="@+id/nickname_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:autoLink="none"
        android:layout_alignParentLeft="true"
        android:paddingBottom="7dp"
        android:paddingLeft="16dp"
        android:paddingRight="12dp"
        android:paddingTop="5dp"
        android:text="adawd awdaw"
        android:textStyle="bold"
        android:textColor="@android:color/holo_green_light"
        android:textSize="18sp"
        tools:ignore="ObsoleteLayoutParam,RtlHardcoded" />

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <com.fearefull.chatstory.Widgets.MyTextView
            android:id="@+id/textview_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:autoLink="none"
            android:paddingBottom="7dp"
            android:paddingLeft="16dp"
            android:paddingRight="12dp"
            android:paddingTop="5dp"
            android:text="dlsadfafawfafawawfawf a fawfawfafafkawmflaknfalfntigtggt"
            android:textColor="@android:color/black"
            android:textSize="17sp"
            tools:ignore="ObsoleteLayoutParam,RtlHardcoded" />

        <com.fearefull.chatstory.Widgets.MyTextView
            android:id="@+id/textview_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="11:15 PM"
            android:layout_below="@id/textview_message"
            android:textColor="#a6abad"
            android:textSize="12sp"
            android:layout_alignParentRight="true"
            android:padding="2dp"
            tools:ignore="RtlHardcoded" />
    </RelativeLayout>

</LinearLayout>
</code>```

Output

Title: Create chat message layout

Body:
I have a problem with my chat message Layout in Android.

I have 3 custom textview, but the Time of textView should be set on Bottom and Right align.

Here is my screenshot:

And here is my code:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginRight="60dp"
    android:background="@drawable/msg_in"
    android:orientation="vertical">

    <com.fearefull.chatstory.Widgets.MyTextView
        android:id="@+id/nickname_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:autoLink="none"
        android:layout_alignParentLeft="true"
        android:paddingBottom="7dp"
        android:paddingLeft="16dp"
        android:paddingRight="12dp"
        android:paddingTop="5dp"
        android:text="adawd awdaw"
        android:textStyle="bold"
        android:textColor="@android:color/holo_green_light"
        android:textSize="18sp"
        tools:ignore="ObsoleteLayoutParam,RtlHardcoded" />

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <com.fearefull.chatstory.Widgets.MyTextView
            android:id="@+id/textview_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:autoLink="none"
            android:paddingBottom="7dp"
            android:paddingLeft="16dp"
            android:paddingRight="12dp"
            android:paddingTop="5dp"
            android:text="dlsadfafawfafawawfawf a fawfawfafafkawmflaknfalfntigtggt"
            android:textColor="@android:color/black"
            android:textSize="17sp"
            tools:ignore="ObsoleteLayoutParam,RtlHardcoded" />

        <com.fearefull.chatstory.Widgets.MyTextView
            android:id="@+id/textview_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="11:15 PM"
            android:textColor="#a6abad"
            android:textSize="12sp"
            android:layout_alignBottom="@id/textview_message"
            android:layout_alignParentRight="true"
            android:padding="5dp"
            tools:ignore="RtlHardcoded" />
    </RelativeLayout>

</LinearLayout>

I used any Alignment for my Time of textView, but it didn't work.

Body:
Try this

<LinearLayout android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_marginRight="60dp"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <com.fearefull.chatstory.Widgets.MyTextView
        android:id="@+id/nickname_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:autoLink="none"
        android:layout_alignParentLeft="true"
        android:paddingBottom="7dp"
        android:paddingLeft="16dp"
        android:paddingRight="12dp"
        android:paddingTop="5dp"
        android:text="adawd awdaw"
        android:textStyle="bold"
        android:textColor="@android:color/holo_green_light"
        android:textSize="18sp"
        tools:ignore="ObsoleteLayoutParam,RtlHardcoded" />

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <com.fearefull.chatstory.Widgets.MyTextView
            android:id="@+id/textview_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:autoLink="none"
            android:paddingBottom="7dp"
            android:paddingLeft="16dp"
            android:paddingRight="12dp"
            android:paddingTop="5dp"
            android:text="dlsadfafawfafawawfawf a fawfawfafafkawmflaknfalfntigtggt"
            android:textColor="@android:color/black"
            android:textSize="17sp"
            tools:ignore="ObsoleteLayoutParam,RtlHardcoded" />

        <com.fearefull.chatstory.Widgets.MyTextView
            android:id="@+id/textview_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="11:15 PM"
            android:layout_below="@id/textview_message"
            android:textColor="#a6abad"
            android:textSize="12sp"
            android:layout_alignParentRight="true"
            android:padding="2dp"
            tools:ignore="RtlHardcoded" />
    </RelativeLayout>

</LinearLayout>

Output


问:
Kubernetes: Choose volume dependent on namespace
In a simple Postgres Deployment, I wish to choose the volume dependent on the namespace. The aim is to use the same Deployment configuration file to create Postgres deployments  in different namespaces (e.g. production/staging).

What ways are there to achieve this?

Below my configuration file, I basically want to make MAKE_THIS_DEPENDENT_ON_NAMESPACE dependent on the environment (or namespace) this Deployment is used in.

```<code>kind: Deployment
metadata:
  name: postgres
  labels:
    app: postgres
spec:
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
        - image: postgres:9.6
          name: postgres
          volumeMounts:
            -name: postgres-storage
            mountPath: /var/lib/postgresql
      volumes:
        - name: postgres-persistent-storage
          gcePersistentDisk:
            pdName: MAKE_THIS_DEPENDENT_ON_NAMESPACE
</code>```

答:
You should try using a Persistent Volume Claim instead, PVCs are namespaced.

https://kubernetes.io/docs/concepts/storage/persistent-volumes/#claims-as-volumes

```<code>kind: Pod
apiVersion: v1
metadata:
  name: mypod
spec:
  containers:
    - name: myfrontend
      image: dockerfile/nginx
      volumeMounts:
      - mountPath: "/var/www/html"
        name: mypd
  volumes:
    - name: mypd
      persistentVolumeClaim:
        claimName: myclaim
</code>```

Body:
In a simple Postgres Deployment, I wish to choose the volume dependent on the namespace. The aim is to use the same Deployment configuration file to create Postgres deployments  in different namespaces (e.g. production/staging).

What ways are there to achieve this?

Below my configuration file, I basically want to make MAKE_THIS_DEPENDENT_ON_NAMESPACE dependent on the environment (or namespace) this Deployment is used in.

kind: Deployment
metadata:
  name: postgres
  labels:
    app: postgres
spec:
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
        - image: postgres:9.6
          name: postgres
          volumeMounts:
            -name: postgres-storage
            mountPath: /var/lib/postgresql
      volumes:
        - name: postgres-persistent-storage
          gcePersistentDisk:
            pdName: MAKE_THIS_DEPENDENT_ON_NAMESPACE

Body:
You should try using a Persistent Volume Claim instead, PVCs are namespaced.

https://kubernetes.io/docs/concepts/storage/persistent-volumes/#claims-as-volumes

kind: Pod
apiVersion: v1
metadata:
  name: mypod
spec:
  containers:
    - name: myfrontend
      image: dockerfile/nginx
      volumeMounts:
      - mountPath: "/var/www/html"
        name: mypd
  volumes:
    - name: mypd
      persistentVolumeClaim:
        claimName: myclaim


问:
Specify visible input fields from simple_form layout
I'm loading two views that render a simple_form form layout, new and edit.

I need to show all input fields when the user profile is initially being created (new), and specify fields that will not show when it is being used for edit. I've seen a lot of info around persisted but can't figure it out.

My _form.html.slim file.

```<code>= simple_form_for([:admin, User.new]) do |f|
  = f.error_notification
  .form-inputs
    = f.input :name, required: true, label: 'Name'
    = f.input :email, required: true
    = f.input :password, required: true, placeholder: ("#{@minimum_password_length} characters minimum" if @minimum_password_length)
    = f.input :password_confirmation, required: true

  .form-actions
    = f.button :submit, "Create User", class: 'btn btn-primary btn-block btn-lg'
</code>```

I'm using Rails and Slim - Any help appreciated.

答:
You can indeed use persisted? to conditionally render the fields in form.

```<code>= simple_form_for([:admin, User.new]) do |f|
  = f.error_notification
  .form-inputs
    = f.input :name, required: true, label: 'Name'
    = f.input :email, required: true

    -# Say you don't want user to edit his password after creation
    - unless f.object.persisted?
      = f.input :password, required: true, placeholder: ("#{@minimum_password_length} characters minimum" if @minimum_password_length)
      = f.input :password_confirmation, required: true

    .form-actions
      = f.button :submit, "Create User", class: 'btn btn-primary btn-block btn-lg'
</code>```

Here f.object will be the User instance for which the form will be rendered.

Body:
I'm loading two views that render a simple_form form layout, new and edit.

I need to show all input fields when the user profile is initially being created (new), and specify fields that will not show when it is being used for edit. I've seen a lot of info around persisted but can't figure it out.

My _form.html.slim file.

= simple_form_for([:admin, User.new]) do |f|
  = f.error_notification
  .form-inputs
    = f.input :name, required: true, label: 'Name'
    = f.input :email, required: true
    = f.input :password, required: true, placeholder: ("#{@minimum_password_length} characters minimum" if @minimum_password_length)
    = f.input :password_confirmation, required: true

  .form-actions
    = f.button :submit, "Create User", class: 'btn btn-primary btn-block btn-lg'

I'm using Rails and Slim - Any help appreciated.

Body:
You can indeed use persisted? to conditionally render the fields in form.

= simple_form_for([:admin, User.new]) do |f|
  = f.error_notification
  .form-inputs
    = f.input :name, required: true, label: 'Name'
    = f.input :email, required: true

    -# Say you don't want user to edit his password after creation
    - unless f.object.persisted?
      = f.input :password, required: true, placeholder: ("#{@minimum_password_length} characters minimum" if @minimum_password_length)
      = f.input :password_confirmation, required: true

    .form-actions
      = f.button :submit, "Create User", class: 'btn btn-primary btn-block btn-lg'

Here f.object will be the User instance for which the form will be rendered.


问:
Error in Code when input is correct
Im making a simple game as my first project in Python. I'm having a problem with this code:

```<code>invalid=True
def start():
    x=input('Enter the Keyword:')
    if ("m" == x) or ("M"==x):
        print('Correct!')
    elif x!='m' or x!='M':
        print('Invalid Input.')
        invalid=False
    while invalid:
        start()
</code>```

When the user's input is correct the program still asks again for the input..

How do I continue with the next lines of code when the input is correct?

答:
The problem is that the variable invalid inside the function is local to the function (since you made an assignment which hides the global var) and doesn't affect the global variable.

Simple solution is to declare invalid as global inside function start.

```<code>def start():
    global invalid
    ...
    ...
    invalid=False
</code>```

So the code looks like

```<code>invalid=True
def start():
    global invalid
    x=input('Enter the Keyword:')
    if ("m" == x) or ("M"==x):
        print('Correct!')
    elif x!='m' or x!='M':
        print('Invalid Input.')
        invalid=False
while invalid:
    start()
</code>```

Title: Error in Code when input is correct

Body:
Im making a simple game as my first project in Python. I'm having a problem with this code:

invalid=True
def start():
    x=input('Enter the Keyword:')
    if ("m" == x) or ("M"==x):
        print('Correct!')
    elif x!='m' or x!='M':
        print('Invalid Input.')
        invalid=False
    while invalid:
        start()

When the user's input is correct the program still asks again for the input..

How do I continue with the next lines of code when the input is correct?

Body:
The problem is that the variable invalid inside the function is local to the function (since you made an assignment which hides the global var) and doesn't affect the global variable.

Simple solution is to declare invalid as global inside function start.

def start():
    global invalid
    ...
    ...
    invalid=False

So the code looks like

invalid=True
def start():
    global invalid
    x=input('Enter the Keyword:')
    if ("m" == x) or ("M"==x):
        print('Correct!')
    elif x!='m' or x!='M':
        print('Invalid Input.')
        invalid=False
while invalid:
    start()


问:
When I use Androidplot in my Fragment it can not read values from line_point_formatter_with_labels.xml
I am trying to use the example from this link

I did small amendment to the code and I am using a fragment instead of activity like in the example code. Now, I am having issues with the  line_point_formatter_with_labels.xml and line_point_formatter_with_labels_2.xml config files. The example code can not read values from the files. It happens at the line:

```<code>LineAndPointFormatter series1Format =
                    new LineAndPointFormatter(getActivity(), R.xml.line_point_formatter_with_labels);
</code>```

I have errors like that

java.lang.NumberFormatException: Invalid int: "#00AA00".

Any idea why it is happening ?

Thanks.

答:
There is a issue that manifests very similarly to this that appears to be caused some sort of undocumented change to the Android Gradle plugin in 3.0.1.

If you want to check to see if this is what's impacting you, the short term fix is to revert to 2.3.3.  The issue will also be resolved in Androidplot 1.5.2.

BTW, Androidplot has moved it's primary repo home from Bitbucket to Github.  You can use either one, but the Bitbucket repo occasionally lags behind by a release.

Body:
I am trying to use the example from this link

I did small amendment to the code and I am using a fragment instead of activity like in the example code. Now, I am having issues with the  line_point_formatter_with_labels.xml and line_point_formatter_with_labels_2.xml config files. The example code can not read values from the files. It happens at the line:

LineAndPointFormatter series1Format =
                    new LineAndPointFormatter(getActivity(), R.xml.line_point_formatter_with_labels);

I have errors like that

java.lang.NumberFormatException: Invalid int: "#00AA00".

Any idea why it is happening ?

Thanks.


问:
Using JSON in postgres, how do I query a nested array?
I have a few User records with a details json column that look like this:

```<code>User.create(details: {accounts: [{name: 'one', id: 1}, {name: 'two', id: 2}])
User.create(details: {accounts: [{name: 'three', id: 3}, {name: 'two', id: 2}])
User.create(details: {accounts: [{name: 'three', id: 3}, {name: 'four', id: 4}])
</code>```

How do I query for all records where id is 2?

答:
Thanks to Using jsonb (PostgreSQL), how do I retrieve items with a certain value that's saved as an array? I was put on the right track.

The query to match:

```<code>User.where("? in (SELECT json_array_elements(details->'accounts')->>'id')", "2")
</code>```

Body:
I have a few User records with a details json column that look like this:

User.create(details: {accounts: [{name: 'one', id: 1}, {name: 'two', id: 2}])
User.create(details: {accounts: [{name: 'three', id: 3}, {name: 'two', id: 2}])
User.create(details: {accounts: [{name: 'three', id: 3}, {name: 'four', id: 4}])

How do I query for all records where id is 2?

Body:
Thanks to Using jsonb (PostgreSQL), how do I retrieve items with a certain value that's saved as an array? I was put on the right track.

The query to match:

User.where("? in (SELECT json_array_elements(details->'accounts')->>'id')", "2")


答:
Why is it unhandy? If you need to use it often, and don't want to type it every time just define a bash function for it:

```<code>function findTextInAsciiFiles {
    # usage: findTextInAsciiFiles DIRECTORY NEEDLE_TEXT
    find "$1" -type f -exec grep -l "$2" {} \; -exec file {} \; | grep text
}
</code>```

put it in your .bashrc and then just run:

```<code>findTextInAsciiFiles your_folder "needle text"
</code>```

whenever you want.

EDIT to reflect OP's edit:

if you want to cut out mime informations you could just add a further stage to the pipeline that filters out mime informations. This should do the trick, by taking only what comes before :: cut -d':' -f1:

```<code>function findTextInAsciiFiles {
    # usage: findTextInAsciiFiles DIRECTORY NEEDLE_TEXT
    find "$1" -type f -exec grep -l "$2" {} \; -exec file {} \; | grep text | cut -d ':' -f1
}
</code>```

Title: Linux command: How to 'find' only text files?

Body:
After a few searches from Google, what I come up with is:

find my_folder -type f -exec grep -l "needle text" {} \; -exec file {} \; | grep text

which is very unhandy and outputs unneeded texts such as mime type information. Any better solutions? I have lots of images and other binary files in the same folder with a lot of text files that I need to search through.

Body:
Why is it unhandy? If you need to use it often, and don't want to type it every time just define a bash function for it:

function findTextInAsciiFiles {
    # usage: findTextInAsciiFiles DIRECTORY NEEDLE_TEXT
    find "$1" -type f -exec grep -l "$2" {} \; -exec file {} \; | grep text
}

put it in your .bashrc and then just run:

findTextInAsciiFiles your_folder "needle text"

whenever you want.

EDIT to reflect OP's edit:

if you want to cut out mime informations you could just add a further stage to the pipeline that filters out mime informations. This should do the trick, by taking only what comes before :: cut -d':' -f1:

function findTextInAsciiFiles {
    # usage: findTextInAsciiFiles DIRECTORY NEEDLE_TEXT
    find "$1" -type f -exec grep -l "$2" {} \; -exec file {} \; | grep text | cut -d ':' -f1
}


问:
How to get the browser and Operating System name using Geb and Spock framework at runtime
I want to get the browser name which is currently being used to execute the test scripts and the Operating system name using Geb and Spock framework.

I want these details at runtime to append into the test report.

For example.

If test currently running in Chrome browser then I should get the chrome browser name its version and OS name at runtime

If test currently running in Firefox browser then I should get the Firefox browser name its version and OS name at runtime.

答:
You can use the driver.capabilities to get the browser name,

example: driver.capabilities['browserName'].
A closer look at driver.capabilities will also show the version and driver version.

To get the operating system you can use the property System.getProperty("os.name").

There are many ways to check the OS, it depends on your frameworks.


问:
shelve archives not openable on other computer
I have saved some objects with shelve. In an other file I was able to restore these objects. But when I copy the archive to an other computer shelve gives me a _gdbm.error: File read error. The packages which hold the classes of the stored objects are directly accessible on both computers (but they are stored in different locations and added with PYTHONPATH). Both machines run on Ubuntu 13.10, one is 32bit and the other 64bit.

Shouldn't these archives be machine independent?

On the 64bit machine I get

```<code>>>> import shelve
>>> shelve.open('arch.db')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.3/shelve.py", line 232, in open
    return DbfilenameShelf(filename, flag, protocol, writeback)
  File "/usr/lib/python3.3/shelve.py", line 216, in __init__
    Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback)
  File "/usr/lib/python3.3/dbm/__init__.py", line 94, in open
    return mod.open(file, flag, mode)
_gdbm.error: File read error
</code>```

and on the 32bit machine it works.

When I create an archive on the 64bit machine, it is openable on the 32bit machine, but the interactive python prompt crashes:

```<code>>>> import shelve
>>> s = shelve.open('arch.db')
>>> for i in s.items(): print(i)
...
gdbm fatal: lseek error
</code>```

I don't even get a traceback.

It is really annoying, I intended to work on both computers, but at the moment I am bound to my slow 32bit eeepc, because I've already saved a lot into the archive.

答:
The problem is that shelve uses gdbm (provided as dbm.gnu as default backend to store the serialized objects. The files created with gdbm depend on the architecture of the system and are therefore only usable on 32bit or 64bit systems.

There are some tools (gdbmexport or gdbm_dump) which allow you to convert the gdbm files, however, the workflow becomes error prone if you want to access the files from both systems on a regular basis.

Fortunately, python provides different backends: dbm.gnu, dbm.ndbm and dbm.dumb. The latter two are platform independent.

```<code>import shelve
import dbm
dbm._defaultmod = dbm.ndbm
db = shelve.open('somename')
</code>```

The database with the above code can be used on 64bit and 32bit systems.

The default backend has to be set only when you create the file. dbm checks the file type of your database before opening and uses the correct backend.

Please note that the above code changes the default dbm for the whole python process. Another component might break if it relies on gdbm being the default.

Body:
I have saved some objects with shelve. In an other file I was able to restore these objects. But when I copy the archive to an other computer shelve gives me a _gdbm.error: File read error. The packages which hold the classes of the stored objects are directly accessible on both computers (but they are stored in different locations and added with PYTHONPATH). Both machines run on Ubuntu 13.10, one is 32bit and the other 64bit.

Shouldn't these archives be machine independent?

On the 64bit machine I get

>>> import shelve
>>> shelve.open('arch.db')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.3/shelve.py", line 232, in open
    return DbfilenameShelf(filename, flag, protocol, writeback)
  File "/usr/lib/python3.3/shelve.py", line 216, in __init__
    Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback)
  File "/usr/lib/python3.3/dbm/__init__.py", line 94, in open
    return mod.open(file, flag, mode)
_gdbm.error: File read error

and on the 32bit machine it works.

When I create an archive on the 64bit machine, it is openable on the 32bit machine, but the interactive python prompt crashes:

>>> import shelve
>>> s = shelve.open('arch.db')
>>> for i in s.items(): print(i)
...
gdbm fatal: lseek error

I don't even get a traceback.

It is really annoying, I intended to work on both computers, but at the moment I am bound to my slow 32bit eeepc, because I've already saved a lot into the archive.

Body:
The problem is that shelve uses gdbm (provided as dbm.gnu as default backend to store the serialized objects. The files created with gdbm depend on the architecture of the system and are therefore only usable on 32bit or 64bit systems.

There are some tools (gdbmexport or gdbm_dump) which allow you to convert the gdbm files, however, the workflow becomes error prone if you want to access the files from both systems on a regular basis.

Fortunately, python provides different backends: dbm.gnu, dbm.ndbm and dbm.dumb. The latter two are platform independent.

import shelve
import dbm
dbm._defaultmod = dbm.ndbm
db = shelve.open('somename')

The database with the above code can be used on 64bit and 32bit systems.

The default backend has to be set only when you create the file. dbm checks the file type of your database before opening and uses the correct backend.

Please note that the above code changes the default dbm for the whole python process. Another component might break if it relies on gdbm being the default.


问:
Microsoft Teams: How to add notifications to the activity feed?
How can I push notifications to a users activity feed in Teams?

This documentation suggests its possible by setting a channelData property. Some things about this:

When using setChannelData in the Microsoft Teams Getting Started Sample it tells me it's deprecated and I should use sourceEvent() instead:

For several weeks now there is a note in the documentation saying "The following features are coming soon to the Public Developer Preview." - which is not helpful and differs from other parts of the documentation. Is it in preview or not?

It does not seem to work at all.

So we have a deprecated, soon to come function that does not work. How is the current state of this? Which documentation is correct, which outdated? If sourceEventwas to set - how is the syntax?

Any help on this topic is appreciated.

Addition:

In the app manifest there is a property isNotificationOnly. I set it, it did change nothing. Do I need this?

答: There is a bug with activity feed notifications. This will be shipped in Q1 2018.</p>


问:
UITapGesture in UITableview header
I trying to use expandable tableview in swift. So I added Gesture to header in  tableview, but it does not recognising. Kindly guide me. Just cross check my coding.

MY CODING IS BELOW:

```<code>func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let vvv = tableView.headerViewForSection(section)

        let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
        tap.delegate = self
        vvv?.addGestureRecognizer(tap)
        return vvv
    }

    func handleTap(gestureRecognizer: UITapGestureRecognizer)
    {
        if(gestureRecognizer.state == .Ended)
        {
            println("SECTION PRESSED") //NOT ENTERING TO THIS BLOCK
        }
    }
</code>```

答:
I did it by adding the UITapGestureRecognizer to the contentView of the headerView. Example:

headerCell.contentView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(headerTapped)))

Title: UITapGesture in UITableview header

Body:
I trying to use expandable tableview in swift. So I added Gesture to header in  tableview, but it does not recognising. Kindly guide me. Just cross check my coding.

MY CODING IS BELOW:

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let vvv = tableView.headerViewForSection(section)

        let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
        tap.delegate = self
        vvv?.addGestureRecognizer(tap)
        return vvv
    }

    func handleTap(gestureRecognizer: UITapGestureRecognizer)
    {
        if(gestureRecognizer.state == .Ended)
        {
            println("SECTION PRESSED") //NOT ENTERING TO THIS BLOCK
        }
    }


答:
All you need to do is modify your layout from RelativeLayout to LinearLayout and you are good to go.

```<code><LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="60dp"
android:background="@drawable/msg_in"
android:orientation="vertical">

<com.fearefull.chatstory.Widgets.MyTextView
    android:id="@+id/nickname_message"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:autoLink="none"
    android:layout_alignParentLeft="true"
    android:paddingBottom="7dp"
    android:paddingLeft="16dp"
    android:paddingRight="12dp"
    android:paddingTop="5dp"
    android:text="adawd awdaw"
    android:textStyle="bold"
    android:textColor="@android:color/holo_green_light"
    android:textSize="18sp"
    tools:ignore="ObsoleteLayoutParam,RtlHardcoded" />

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <com.fearefull.chatstory.Widgets.MyTextView
        android:id="@+id/textview_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:autoLink="none"
        android:paddingBottom="7dp"
        android:paddingLeft="16dp"
        android:paddingRight="12dp"
        android:paddingTop="5dp"
        android:text="dlsadfafawfafawawfawf a fawfawfafafkawmflaknfalfntigtggt"
        android:textColor="@android:color/black"
        android:textSize="17sp"
        tools:ignore="ObsoleteLayoutParam,RtlHardcoded" />

    <com.fearefull.chatstory.Widgets.MyTextView
        android:id="@+id/textview_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="11:15 PM"
        android:textColor="#a6abad"
        android:textSize="12sp"
        android:layout_gravity="end"
        android:padding="5dp"
        tools:ignore="RtlHardcoded" />
</RelativeLayout>
</code>```

Title: Create chat message layout

Body:
All you need to do is modify your layout from RelativeLayout to LinearLayout and you are good to go.

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="60dp"
android:background="@drawable/msg_in"
android:orientation="vertical">

<com.fearefull.chatstory.Widgets.MyTextView
    android:id="@+id/nickname_message"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:autoLink="none"
    android:layout_alignParentLeft="true"
    android:paddingBottom="7dp"
    android:paddingLeft="16dp"
    android:paddingRight="12dp"
    android:paddingTop="5dp"
    android:text="adawd awdaw"
    android:textStyle="bold"
    android:textColor="@android:color/holo_green_light"
    android:textSize="18sp"
    tools:ignore="ObsoleteLayoutParam,RtlHardcoded" />

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <com.fearefull.chatstory.Widgets.MyTextView
        android:id="@+id/textview_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:autoLink="none"
        android:paddingBottom="7dp"
        android:paddingLeft="16dp"
        android:paddingRight="12dp"
        android:paddingTop="5dp"
        android:text="dlsadfafawfafawawfawf a fawfawfafafkawmflaknfalfntigtggt"
        android:textColor="@android:color/black"
        android:textSize="17sp"
        tools:ignore="ObsoleteLayoutParam,RtlHardcoded" />

    <com.fearefull.chatstory.Widgets.MyTextView
        android:id="@+id/textview_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="11:15 PM"
        android:textColor="#a6abad"
        android:textSize="12sp"
        android:layout_gravity="end"
        android:padding="5dp"
        tools:ignore="RtlHardcoded" />
</RelativeLayout>


问:
Importing test library 'SSHLibrary' fails with the ImportError "Importing Paramiko library failed. Make sure you have Paramiko installed."
I am trying to run robot framework test cases which uses SSHLibrary. I have installed all the required libraries (paramiko in this case). But I still get this error.

The error I get is:

```<code>Error in file '/opt/bdd_keywords.robot': Importing test library 'SSHLibrary' failed: ImportError: Importing Paramiko library failed. Make sure you have Paramiko installed.
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/SSHLibrary/__init__.py", line 15, in <module>
    from .library import SSHLibrary
  File "/usr/local/lib/python2.7/dist-packages/SSHLibrary/library.py", line 22, in <module>
    from .client import SSHClient
  File "/usr/local/lib/python2.7/dist-packages/SSHLibrary/client.py", line 20, in <module>
    from pythonclient import PythonSSHClient as SSHClient
  File "/usr/local/lib/python2.7/dist-packages/SSHLibrary/pythonclient.py", line 20, in <module>
    'Importing Paramiko library failed. '
</code>```

PYTHONPATH:

```<code>  /usr/local/lib/python2.7/dist-packages/robot/libraries

  /usr/local/lib/python2.7/dist-packages

  /usr/local/bin

  /usr/lib/python2.7

  /usr/lib/python2.7/plat-x86_64-linux-gnu

  /usr/lib/python2.7/lib-tk

  /usr/lib/python2.7/lib-old

  /usr/lib/python2.7/lib-dynload

  /usr/lib/python2.7/dist-packages
  .'
</code>```

When I tried to install paramiko again, I get the below output:

`Requirement already satisfied (use --upgrade to upgrade): paramiko in /usr/local/lib/python2.7/dist-packages/paramiko-1.15.2-py2.7.egg

Requirement already satisfied (use --upgrade to upgrade): pycrypto!=2.4,>=2.1 in /usr/local/lib/python2.7/dist-packages (from paramiko)

Requirement already satisfied (use --upgrade to upgrade): ecdsa>=0.11 in /usr/local/lib/python2.7/dist-packages (from paramiko)`

P.S: I am trying to run this test on a Docker container. DatabaseLibrary keywords work fine.

答:
Faced same issue when I try to import SSHLibrary in Python 2.7. Paramiko uses enum package. The problem is that the enum package wasn't added to Python until version 3.4.

It has been back ported in lower versions of Python you just need the package from here: https://pypi.python.org/pypi/enum34#downloads

or try

"pip install enum" to get the issue resolved.

Body:
I am trying to run robot framework test cases which uses SSHLibrary. I have installed all the required libraries (paramiko in this case). But I still get this error.

The error I get is:

Error in file '/opt/bdd_keywords.robot': Importing test library 'SSHLibrary' failed: ImportError: Importing Paramiko library failed. Make sure you have Paramiko installed.
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/SSHLibrary/__init__.py", line 15, in <module>
    from .library import SSHLibrary
  File "/usr/local/lib/python2.7/dist-packages/SSHLibrary/library.py", line 22, in <module>
    from .client import SSHClient
  File "/usr/local/lib/python2.7/dist-packages/SSHLibrary/client.py", line 20, in <module>
    from pythonclient import PythonSSHClient as SSHClient
  File "/usr/local/lib/python2.7/dist-packages/SSHLibrary/pythonclient.py", line 20, in <module>
    'Importing Paramiko library failed. '

PYTHONPATH:

  /usr/local/lib/python2.7/dist-packages/robot/libraries

  /usr/local/lib/python2.7/dist-packages

  /usr/local/bin

  /usr/lib/python2.7

  /usr/lib/python2.7/plat-x86_64-linux-gnu

  /usr/lib/python2.7/lib-tk

  /usr/lib/python2.7/lib-old

  /usr/lib/python2.7/lib-dynload

  /usr/lib/python2.7/dist-packages
  .'

When I tried to install paramiko again, I get the below output:

`Requirement already satisfied (use --upgrade to upgrade): paramiko in /usr/local/lib/python2.7/dist-packages/paramiko-1.15.2-py2.7.egg

Requirement already satisfied (use --upgrade to upgrade): pycrypto!=2.4,>=2.1 in /usr/local/lib/python2.7/dist-packages (from paramiko)

Requirement already satisfied (use --upgrade to upgrade): ecdsa>=0.11 in /usr/local/lib/python2.7/dist-packages (from paramiko)`

P.S: I am trying to run this test on a Docker container. DatabaseLibrary keywords work fine.


问:
How do I implement a search function in Binary Search Tree using Python?
The function searchNode doesn't work correct. When searching an element which is in binary tree it returns None instead of True. I don't understand why it is None, because it should return either True or False but never None. Can you tip me how to fix it?</p>

```<code>class Node:
def __init__(self, value):
    self.value = value
    self.left = None
    self.right = None

class BinarySearchTree:
def __init__(self):
    self.root = None
    self.visited = 0

def insert(self,value):
    if self.root is None:
        self.root =  Node(value)
    else:
        self.insertNode(self.root, value)

def insertNode(self,current, value):
    if value <= current.value:
        if  current.left:
            self.insertNode(current.left, value)
        else:
            current.left = Node(value)
    else:
        if current.right:
            self.insertNode(current.right, value)
        else:
            current.right = Node(value)

def fromArray(self, newarr):
    for each in newarr:
        self.insert(each)
    return

def search(self, value):
    self.visited = 0
    self.searchNode(self.root, value)

def searchNode(self,current,value):
    if (current is None):
        return False
    elif (value == current.value):
        return True
    elif (value < current.value):
        self.visited += 1
        return self.searchNode(current.left, value)
    else:
        self.visited += 1
        return self.searchNode(current.right, value)
</code>```

答: You never return anything in search. You probably want to return self.searchNode(self.root, value) instead of just calling it.

Body:
The function searchNode doesn't work correct. When searching an element which is in binary tree it returns None instead of True. I don't understand why it is None, because it should return either True or False but never None. Can you tip me how to fix it?

class Node:
def __init__(self, value):
    self.value = value
    self.left = None
    self.right = None

class BinarySearchTree:
def __init__(self):
    self.root = None
    self.visited = 0

def insert(self,value):
    if self.root is None:
        self.root =  Node(value)
    else:
        self.insertNode(self.root, value)

def insertNode(self,current, value):
    if value <= current.value:
        if  current.left:
            self.insertNode(current.left, value)
        else:
            current.left = Node(value)
    else:
        if current.right:
            self.insertNode(current.right, value)
        else:
            current.right = Node(value)

def fromArray(self, newarr):
    for each in newarr:
        self.insert(each)
    return

def search(self, value):
    self.visited = 0
    self.searchNode(self.root, value)

def searchNode(self,current,value):
    if (current is None):
        return False
    elif (value == current.value):
        return True
    elif (value < current.value):
        self.visited += 1
        return self.searchNode(current.left, value)
    else:
        self.visited += 1
        return self.searchNode(current.right, value)


问:
Check 2 values in aiml file
How can I check 2 values in condition or with other tags?
I want check if the user's name is equal with Unknown user value but I don't know how can I do this.</p>

答:
Assume you have the user name stored in a global property (predicate) called user, using <set name="user">George</set> You can check the user's name with an AIML category like this:

```<code><category>
  <pattern>WHAT IS MY NAME</pattern>
  <template>
    <condition>
      <li name="user" value="unknown">You haven't told me your name</li>
      <li name="user" value="">You haven't told me your name</li>
      <li>Hello <get name="user"/>!</li>
    </condition>
  </template>
<category>
</code>```

This works as follows:

You set up a category that responds to user input "What is my name"

The
 elements in the <condition> test the name property for unknown and blank. In this case the AI replies the user hasn't told us their name.

The final
 element is triggered if we have a name, and it replies with 'Hello' followed by the user name.

I haven't tested this with program O but it's standard AIML and should work fine. I have successfully coded similar categories in my own AI.

Title: Check 2 values in aiml file

Body:
Assume you have the user name stored in a global property (predicate) called user, using <set name="user">George</set> You can check the user's name with an AIML category like this:

<category>
  <pattern>WHAT IS MY NAME</pattern>
  <template>
    <condition>
      <li name="user" value="unknown">You haven't told me your name</li>
      <li name="user" value="">You haven't told me your name</li>
      <li>Hello <get name="user"/>!</li>
    </condition>
  </template>
<category>

This works as follows:

You set up a category that responds to user input "What is my name"

The <li> elements in the <condition> test the name property for unknown and blank. In this case the AI replies the user hasn't told us their name.

The final <li> element is triggered if we have a name, and it replies with 'Hello' followed by the user name.

I haven't tested this with program O but it's standard AIML and should work fine. I have successfully coded similar categories in my own AI.