问:
Understanding MVVM - How to bind data view ↔ ViewModel + catch Key pressed on view and start function in viewModel
I'm new in C# and created a simple app that works fine, but I wanna to learn C# using the pattern MVVM. So I'm trying to migrate my app to MVVM and I become confused

My Goal is simple:

1) When opened, the app scan a folder and index all the files in the format
"[number] [name]" - It's working fine!

2) I have a window with just one textBox. The user types a number and press ENTER. In this moment I have a CatalogViewModel that is a set o File and should select the file specified by the number in textBox and open it.

Problem 1: In MVVM I can't pass the data from my view Main to my ViewModel CatalogViewModel (I'm not sure if I made correct)

Problem 2: I can't handle the ENTER key and trigger a function inside CatalogViewModel

I'm a little confused with MVVM and can't go ahead. I know that it's simple. Please, how to resolve this 2 problem (in detail please, I'm a beginner in C# and in all its concept)

UPDATE 1:

tryed the janonimus' Solution to problem 1 But the databind is just ONE WAY.
The value from VM goes to the VIEW, but the changes on the VIEW don't to to VM.
I've implemented INotifyPropertyChanged this way

```<code>using Prism.Mvvm;
...

    public class CatalogViewModel: BindableBase
    {

        private string selectedValue = "100";
        public string SelectedValue
        {
            get { return selectedValue; }
            set { SetProperty(ref selectedValue, value); }
        }
</code>```

But the Databind becomes just ON WAY
the XAML

```<code><TextBox x:Name="tbSelectedValue" Text="{Binding SelectedValue, Mode=TwoWay}"
</code>```

UPDATE 2

I found the solution for the problem 1. The code provided by janonimus works just in ONE WAY because the default behavior of TextBox.Text is to upadte when it lose the focus, but in my case it will never lose the focus see this post

The following code resolved the problem 1:

```<code>Text="{Binding Path=SelectedValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}
</code>```

The problem 2 Can be resolved with Pedro Silva's answer

```<code>if (e.Key == Key.Enter && tbSelectedValue.Text != String.Empty)
            {
                vm.OpenSelectedFile();
                tbSelectedValue.Text = String.Empty;
            }
</code>```

But I wanna to implement it using a more sofisticated way, using ICommand.
Following the advise sent by janonimus, I created the BaseCommand Class Exactly like this but it throws a mismatch error when I call the function OpenSelectedFile

```<code>private BaseCommand<CatalogViewModel> _selectFileCommand;
public ICommand SelectFileCommand
{
    get
    {
        if (_selectFileCommand == null)
        {
            _selectFileCommand = new BaseCommand<CatalogViewModel>(OpenSelectedFile, true);
        }
        return _selectFileCommand;
    }
}
public void OpenSelectedFile()
{
    try
    {
        OpenFileByNumber(Int32.Parse(SelectedValue));
    }
    catch (Exception e)
    {
        MessageBox.Show("Número inválido: \'" + SelectedValue + "\"",
           "ERRO", MessageBoxButton.OK, MessageBoxImage.Warning);
    }

}
</code>```

That's my code for reference...

Main.xaml.cs

```<code>namespace SLMT.Views
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class Main : Window
    {

        public Main()
        {
            InitializeComponent();
            DataContext = new CatalogViewModel();
            chosenNumber.Focus();
        }

        // Permite inserir somente números
        private void ChosenNumber_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("[^ 0-9]+");
            e.Handled = regex.IsMatch(e.Text);
        }

        private void ChosenNumber_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter && chosenNumber.Text != String.Empty)
            {
                //catalog.OpenFileByNumber(ConvertToInt(numeroEscolhido.Text));
                //catalog.OpenSelectedFile(); // Will become someting like this
                chosenNumber.Text = String.Empty;

            }
        }

        private int ConvertToInt(string value)
        {
            try
            {
                var str = value.Replace(" ", String.Empty);
                return Int32.Parse(str);
            }
            catch (Exception exc)
            {
                MessageBox.Show("O número: \"" + chosenNumber.Text + "\" é inválido", "ERRO", MessageBoxButton.OK, MessageBoxImage.Error);
                chosenNumber.Text = String.Empty;

                return 0;
            }
        }

        /// <summary>
        /// Controll what wil lhappen if some KEYS are pressed on APP
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GMain_KeyUp(object sender, KeyEventArgs e)
        {

            switch (e.Key){

                case Key.Escape:
                    Environment.Exit(0);
                    break;

                case Key.F1:
                    //wListFiles = new ListFiles(catalog);
                    //wListFiles.ShowDialog();
                    //numeroEscolhido.Text = wListFiles.SelectFile();
                    //numeroEscolhido.SelectAll();
                    break;
            }

        }
    }
}
</code>```

ps: The commented lines, I imported from the version without MVVM

Main.xaml

```<code><Window x:Name="wMain" x:Class="SLMT.Views.Main"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:SLMT.Views"
        mc:Ignorable="d"
        Title="Ministério Tons" Height="364" Width="700" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" WindowStyle="None">
    <Grid x:Name="gMain" KeyUp="GMain_KeyUp">
        <Image x:Name="imgBackground" HorizontalAlignment="Left" Height="364" VerticalAlignment="Top" Width="700" Source="/SLMT;component/Resources/img/background2.jpg" Opacity="100"/>
        <TextBox x:Name="chosenNumber" HorizontalAlignment="Center" Height="34" Margin="500,294,56,36" TextWrapping="Wrap" VerticalAlignment="Center" Width="144" BorderBrush="{x:Null}" Background="{x:Null}" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" UndoLimit="50" ForceCursor="True" PreviewTextInput="ChosenNumber_PreviewTextInput" KeyUp="ChosenNumber_KeyUp" BorderThickness="0" FontSize="20" Opacity="0.6" FontWeight="Bold"/>

    </Grid>
</Window>
</code>```

And the Relevant part of CatalogViewModel.cs

```<code>namespace SLMT.ViewModel
{
    public class CatalogViewModel: ObservableCollection <File>
    {

        private int selectedNumber;

        /// <summary>
        /// Contain the selected number in the View
        /// </summary>
        public int SelectedNumber
        {
            get { return selectedNumber; }
            set { selectedNumber = value; }
        }

        // REMOVED CODE TO SCAN AND INDEX THE FILES

        public CatalogViewModel() : base()
        {
            ScanFiles();
            ValidateAndAddFiles();
            ShowAlerts();
        }

        public void OpenSelectedFile()
        {
            OpenFileByNumber(SelectedNumber);
        }

        /// <summary>
        /// Get the file from catalog identified my the number
        /// </summary>
        /// <param name="number"></param>
        /// <returns>File|null</returns>
        private File GetFileByNumber(int number)
        {
            foreach (var file in this)
            {
                if (file.number == number){
                    return file;
                }
            }

            return null;
        }

        private void OpenFileByNumber(int number)
        {
            var file = GetFileByNumber(number);

            if (file == null)
            {
                MessageBox.Show("Nenhum arquivo encontrado com o número: \'" + number +"\"",
                   "ARQUIVO NÃO ENCONTRADO", MessageBoxButton.OK, MessageBoxImage.Warning);
            } else
            {
                file.Open();
            }
        }
    }
}
</code>```

答:
You need to do a few things here.

For problem 1, you must bind the View that will pass the data to ViewModel.
In this case, the TextBox.Text property must bind to CatalogViewModel.SelectedNumber property:

```<code><TextBox x:Name="chosenNumber"
     ...
     Text={Binding SelectedNumber} />
</code>```

For MVVM's sake, the CatalogViewModel class must implement the INotifyPropertyChanged interface. And just create a property for the ObservableCollection that you have.

For problem 2, you're going to need KeyBinding and ICommand to make this work.
In the View, it should look like this:

```<code><TextBox x:Name="chosenNumber"
 ...
 Text={Binding SelectedNumber}>
    <TextBox.InputBindings>
        <KeyBinding Key="Enter"
                    Command="{Binding SelectFileCommand}" />
    </TextBox.InputBindings>
</TextBox>
</code>```

In the ViewModel, you will need an ICommand property:

```<code>public class CatalogViewModel: INotifyPropertyChanged
{
        private BaseCommand _selectFileCommand;
        public ICommand SelectFileCommand
        {
            get
            {
                if (_selectFileCommand == null)
                {
                    _selectFileCommand = new BaseCommand(SelectFile, CanSelectFile);
                }
                return _selectFileCommand;
            }
        }
...
</code>```

Where, SelectFile is a function that will do the action, CanSelectFile is function tells whether or not the command can execute, BaseCommand is an implementation of the ICommand interface.
You can refer to this question: WPF selectedItem on Menu or get commandparameter in viewmodel

UPDATE:
Use this BaseCommand implementation, and not the BaseCommand<T>:

```<code>class BaseCommand : ICommand
{
    private readonly Action _executeMethod = null;
    private readonly Func<bool> _canExecuteMethod = null;

    public BaseCommand(Action executeMethod, Func<bool> canExecuteMethod)
    {
        _executeMethod = executeMethod;
        _canExecuteMethod = canExecuteMethod;
    }

    public event EventHandler CanExecuteChanged;

    public bool CanExecute()
    {
        if (_canExecuteMethod != null)
        {
            return _canExecuteMethod();
        }
        return true;
    }

    public void Execute()
    {
        if (_executeMethod != null)
        {
            _executeMethod();
        }
    }
}
</code>```

Give this a shot and let us know what happens.

Body:
I'm new in C# and created a simple app that works fine, but I wanna to learn C# using the pattern MVVM. So I'm trying to migrate my app to MVVM and I become confused

My Goal is simple:

1) When opened, the app scan a folder and index all the files in the format
"[number] [name]" - It's working fine!

2) I have a window with just one textBox. The user types a number and press ENTER. In this moment I have a CatalogViewModel that is a set o File and should select the file specified by the number in textBox and open it.

Problem 1: In MVVM I can't pass the data from my view Main to my ViewModel CatalogViewModel (I'm not sure if I made correct)

Problem 2: I can't handle the ENTER key and trigger a function inside CatalogViewModel

I'm a little confused with MVVM and can't go ahead. I know that it's simple. Please, how to resolve this 2 problem (in detail please, I'm a beginner in C# and in all its concept)

UPDATE 1:

tryed the janonimus' Solution to problem 1 But the databind is just ONE WAY.
The value from VM goes to the VIEW, but the changes on the VIEW don't to to VM.
I've implemented INotifyPropertyChanged this way

using Prism.Mvvm;
...

    public class CatalogViewModel: BindableBase
    {

        private string selectedValue = "100";
        public string SelectedValue
        {
            get { return selectedValue; }
            set { SetProperty(ref selectedValue, value); }
        }

But the Databind becomes just ON WAY
the XAML

<TextBox x:Name="tbSelectedValue" Text="{Binding SelectedValue, Mode=TwoWay}"

UPDATE 2

I found the solution for the problem 1. The code provided by janonimus works just in ONE WAY because the default behavior of TextBox.Text is to upadte when it lose the focus, but in my case it will never lose the focus see this post

The following code resolved the problem 1:

Text="{Binding Path=SelectedValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}

The problem 2 Can be resolved with Pedro Silva's answer

if (e.Key == Key.Enter && tbSelectedValue.Text != String.Empty)
            {
                vm.OpenSelectedFile();
                tbSelectedValue.Text = String.Empty;
            }

But I wanna to implement it using a more sofisticated way, using ICommand.
Following the advise sent by janonimus, I created the BaseCommand Class Exactly like this but it throws a mismatch error when I call the function OpenSelectedFile

private BaseCommand<CatalogViewModel> _selectFileCommand;
public ICommand SelectFileCommand
{
    get
    {
        if (_selectFileCommand == null)
        {
            _selectFileCommand = new BaseCommand<CatalogViewModel>(OpenSelectedFile, true);
        }
        return _selectFileCommand;
    }
}
public void OpenSelectedFile()
{
    try
    {
        OpenFileByNumber(Int32.Parse(SelectedValue));
    }
    catch (Exception e)
    {
        MessageBox.Show("Número inválido: \'" + SelectedValue + "\"",
           "ERRO", MessageBoxButton.OK, MessageBoxImage.Warning);
    }

}

That's my code for reference...

Main.xaml.cs

namespace SLMT.Views
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class Main : Window
    {

        public Main()
        {
            InitializeComponent();
            DataContext = new CatalogViewModel();
            chosenNumber.Focus();
        }

        // Permite inserir somente números
        private void ChosenNumber_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("[^ 0-9]+");
            e.Handled = regex.IsMatch(e.Text);
        }

        private void ChosenNumber_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter && chosenNumber.Text != String.Empty)
            {
                //catalog.OpenFileByNumber(ConvertToInt(numeroEscolhido.Text));
                //catalog.OpenSelectedFile(); // Will become someting like this
                chosenNumber.Text = String.Empty;

            }
        }

        private int ConvertToInt(string value)
        {
            try
            {
                var str = value.Replace(" ", String.Empty);
                return Int32.Parse(str);
            }
            catch (Exception exc)
            {
                MessageBox.Show("O número: \"" + chosenNumber.Text + "\" é inválido", "ERRO", MessageBoxButton.OK, MessageBoxImage.Error);
                chosenNumber.Text = String.Empty;

                return 0;
            }
        }

        ///
        /// Controll what wil lhappen if some KEYS are pressed on APP
        ///
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GMain_KeyUp(object sender, KeyEventArgs e)
        {

            switch (e.Key){

                case Key.Escape:
                    Environment.Exit(0);
                    break;

                case Key.F1:
                    //wListFiles = new ListFiles(catalog);
                    //wListFiles.ShowDialog();
                    //numeroEscolhido.Text = wListFiles.SelectFile();
                    //numeroEscolhido.SelectAll();
                    break;
            }

        }
    }
}

ps: The commented lines, I imported from the version without MVVM

Main.xaml

<Window x:Name="wMain" x:Class="SLMT.Views.Main"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:SLMT.Views"
        mc:Ignorable="d"
        Title="Ministério Tons" Height="364" Width="700" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" WindowStyle="None">
    <Grid x:Name="gMain" KeyUp="GMain_KeyUp">
        <Image x:Name="imgBackground" HorizontalAlignment="Left" Height="364" VerticalAlignment="Top" Width="700" Source="/SLMT;component/Resources/img/background2.jpg" Opacity="100"/>
        <TextBox x:Name="chosenNumber" HorizontalAlignment="Center" Height="34" Margin="500,294,56,36" TextWrapping="Wrap" VerticalAlignment="Center" Width="144" BorderBrush="{x:Null}" Background="{x:Null}" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" UndoLimit="50" ForceCursor="True" PreviewTextInput="ChosenNumber_PreviewTextInput" KeyUp="ChosenNumber_KeyUp" BorderThickness="0" FontSize="20" Opacity="0.6" FontWeight="Bold"/>

    </Grid>
</Window>

And the Relevant part of CatalogViewModel.cs

namespace SLMT.ViewModel
{
    public class CatalogViewModel: ObservableCollection <File>
    {

        private int selectedNumber;

        ///
        /// Contain the selected number in the View
        ///
        public int SelectedNumber
        {
            get { return selectedNumber; }
            set { selectedNumber = value; }
        }

        // REMOVED CODE TO SCAN AND INDEX THE FILES

        public CatalogViewModel() : base()
        {
            ScanFiles();
            ValidateAndAddFiles();
            ShowAlerts();
        }

        public void OpenSelectedFile()
        {
            OpenFileByNumber(SelectedNumber);
        }

        ///
        /// Get the file from catalog identified my the number
        ///
        /// <param name="number"></param>
        /// <returns>File|null</returns>
        private File GetFileByNumber(int number)
        {
            foreach (var file in this)
            {
                if (file.number == number){
                    return file;
                }
            }

            return null;
        }

        private void OpenFileByNumber(int number)
        {
            var file = GetFileByNumber(number);

            if (file == null)
            {
                MessageBox.Show("Nenhum arquivo encontrado com o número: \'" + number +"\"",
                   "ARQUIVO NÃO ENCONTRADO", MessageBoxButton.OK, MessageBoxImage.Warning);
            } else
            {
                file.Open();
            }
        }
    }
}

Body:
You need to do a few things here.

For problem 1, you must bind the View that will pass the data to ViewModel.
In this case, the TextBox.Text property must bind to CatalogViewModel.SelectedNumber property:

<TextBox x:Name="chosenNumber"
     ...
     Text={Binding SelectedNumber} />

For MVVM's sake, the CatalogViewModel class must implement the INotifyPropertyChanged interface. And just create a property for the ObservableCollection that you have.

For problem 2, you're going to need KeyBinding and ICommand to make this work.
In the View, it should look like this:

<TextBox x:Name="chosenNumber"
 ...
 Text={Binding SelectedNumber}>
    <TextBox.InputBindings>
        <KeyBinding Key="Enter"
                    Command="{Binding SelectFileCommand}" />
    </TextBox.InputBindings>
</TextBox>

In the ViewModel, you will need an ICommand property:

public class CatalogViewModel: INotifyPropertyChanged
{
        private BaseCommand _selectFileCommand;
        public ICommand SelectFileCommand
        {
            get
            {
                if (_selectFileCommand == null)
                {
                    _selectFileCommand = new BaseCommand(SelectFile, CanSelectFile);
                }
                return _selectFileCommand;
            }
        }
...

Where, SelectFile is a function that will do the action, CanSelectFile is function tells whether or not the command can execute, BaseCommand is an implementation of the ICommand interface.
You can refer to this question: WPF selectedItem on Menu or get commandparameter in viewmodel

UPDATE:
Use this BaseCommand implementation, and not the BaseCommand<T>:

class BaseCommand : ICommand
{
    private readonly Action _executeMethod = null;
    private readonly Func<bool> _canExecuteMethod = null;

    public BaseCommand(Action executeMethod, Func<bool> canExecuteMethod)
    {
        _executeMethod = executeMethod;
        _canExecuteMethod = canExecuteMethod;
    }

    public event EventHandler CanExecuteChanged;

    public bool CanExecute()
    {
        if (_canExecuteMethod != null)
        {
            return _canExecuteMethod();
        }
        return true;
    }

    public void Execute()
    {
        if (_executeMethod != null)
        {
            _executeMethod();
        }
    }
}

Give this a shot and let us know what happens.


来源: stackexchange

问:
IP Filtering using grepcidr / bash
Trying to filter IP' list and reject the IP's from the list "service_ip_list"
For some strange reason, grepcidr searches only in first 3 IP's from list "service_ip_list" and ignores the rest, any one know how to fix this ?</p>

```<code>ip_filtering() { service_ip_list=("192.168.1.1" "192.168.1.2" "192.168.1.8" "192.168.1.80" "192.168.1.20" "192.168.1.200")
    grepcidr "$service_ip_list" <(echo "$1") >/dev/null && \
        echo "$1 is a Service IP" || \
        echo $1 >> live_ser_list
}

for i in 192.168.1.{1..254}
 do
 ip_filtering $i & disown
 done
</code>```

答:
It's not grepcidr, and in case of matching ip's in Networks list, like 10.0.0.0/24 you may use/need grepcidr,
but if you need to filter IP's by rejecting the ones from the array, the simple solution would be:</p>

```<code>    #your array
    declare -a service_ip_list=("192.168.1.1" "192.168.1.2" "192.168.1.8" "192.168.1.80" "192.168.1.20" "192.168.1.200")
    ip_filtering () {
    #this will match your IP to the IP's from the array
    if [[ " ${service_ip_list[@]} " =~ " ${1} " ]]; then
        #if found in array
        echo "$1 is a Service IP"
    else
        #if not found in array
        echo $1 >> live_ser_list
    fi
    }
    # your IP source
    for i in 192.168.1.{1..254}
     do
     ip_filtering $i & disown
     done
</code>```

ContentLicense: CC BY-SA 3.0

Title: IP Filtering using grepcidr / bash

Body:
Trying to filter IP' list and reject the IP's from the list "service_ip_list"
For some strange reason, grepcidr searches only in first 3 IP's from list "service_ip_list" and ignores the rest, any one know how to fix this ?

ip_filtering() { service_ip_list=("192.168.1.1" "192.168.1.2" "192.168.1.8" "192.168.1.80" "192.168.1.20" "192.168.1.200")
    grepcidr "$service_ip_list" <(echo "$1") >/dev/null && \
        echo "$1 is a Service IP" || \
        echo $1 >> live_ser_list
}

for i in 192.168.1.{1..254}
 do
 ip_filtering $i & disown
 done

Body:
It's not grepcidr, and in case of matching ip's in Networks list, like 10.0.0.0/24 you may use/need grepcidr,
but if you need to filter IP's by rejecting the ones from the array, the simple solution would be:

    #your array
    declare -a service_ip_list=("192.168.1.1" "192.168.1.2" "192.168.1.8" "192.168.1.80" "192.168.1.20" "192.168.1.200")
    ip_filtering () {
    #this will match your IP to the IP's from the array
    if [[ " ${service_ip_list[@]} " =~ " ${1} " ]]; then
        #if found in array
        echo "$1 is a Service IP"
    else
        #if not found in array
        echo $1 >> live_ser_list
    fi
    }
    # your IP source
    for i in 192.168.1.{1..254}
     do
     ip_filtering $i & disown
     done


问:
Scipy sparse CSR matrix to TensorFlow SparseTensor - Mini-Batch gradient descent
I have a Scipy sparse CSR matrix created from sparse TF-IDF feature matrix in SVM-Light format. The number of features is huge and it is sparse so I have to use a SparseTensor or else it is too slow.

For example, number of features is 5, and a sample file can look like this:

```<code>0 4:1
1 1:3 3:4
0 5:1
0 2:1
</code>```

After parsing, the training set looks like this:

```<code>trainX = <scipy CSR matrix>
trainY = np.array( [0,1,00] )
</code>```

I have two important questions:

1) How I do convert this to a SparseTensor (sp_ids, sp_weights) efficiently so that I perform fast multiplication (W.X) using lookup: https://www.tensorflow.org/versions/master/api_docs/python/nn.html#embedding_lookup_sparse

2) How do I randomize the dataset at each epoch and recalculate sp_ids, sp_weights to so that I can feed (feed_dict) for the mini-batch gradient descent.

Example code on a simple model like logistic regression will be very appreciated. The graph will be like this:

```<code># GRAPH
mul = tf.nn.embedding_lookup_sparse(W, X_sp_ids, X_sp_weights, combiner = "sum")  # W.X
z = tf.add(mul, b) #  W.X + b

cost_op = tf.reduce_sum(tf.nn.sigmoid_cross_entropy_with_logits(z, y_true))  # this already has built in sigmoid apply
train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost_op)  # construct optimizer

predict_op = tf.nn.sigmoid(z) # sig(W.X + b)
</code>```

答:
I can answer the first part of your question.

```<code>def convert_sparse_matrix_to_sparse_tensor(X):
    coo = X.tocoo()
    indices = np.mat([coo.row, coo.col]).transpose()
    return tf.SparseTensor(indices, coo.data, coo.shape)
</code>```

First you convert the matrix to COO format.  Then you extract the indices, values, and shape and pass those directly to the SparseTensor constructor.

Body:
I have a Scipy sparse CSR matrix created from sparse TF-IDF feature matrix in SVM-Light format. The number of features is huge and it is sparse so I have to use a SparseTensor or else it is too slow.

For example, number of features is 5, and a sample file can look like this:

0 4:1
1 1:3 3:4
0 5:1
0 2:1

After parsing, the training set looks like this:

trainX = <scipy CSR matrix>
trainY = np.array( [0,1,00] )

I have two important questions:

1) How I do convert this to a SparseTensor (sp_ids, sp_weights) efficiently so that I perform fast multiplication (W.X) using lookup: https://www.tensorflow.org/versions/master/api_docs/python/nn.html#embedding_lookup_sparse

2) How do I randomize the dataset at each epoch and recalculate sp_ids, sp_weights to so that I can feed (feed_dict) for the mini-batch gradient descent.

Example code on a simple model like logistic regression will be very appreciated. The graph will be like this:

# GRAPH
mul = tf.nn.embedding_lookup_sparse(W, X_sp_ids, X_sp_weights, combiner = "sum")  # W.X
z = tf.add(mul, b) #  W.X + b

cost_op = tf.reduce_sum(tf.nn.sigmoid_cross_entropy_with_logits(z, y_true))  # this already has built in sigmoid apply
train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost_op)  # construct optimizer

predict_op = tf.nn.sigmoid(z) # sig(W.X + b)

Body:
I can answer the first part of your question.

def convert_sparse_matrix_to_sparse_tensor(X):
    coo = X.tocoo()
    indices = np.mat([coo.row, coo.col]).transpose()
    return tf.SparseTensor(indices, coo.data, coo.shape)

First you convert the matrix to COO format.  Then you extract the indices, values, and shape and pass those directly to the SparseTensor constructor.


问:
How to save Date Time without the time?
How would i save the date time, with no time or preferably with a time stamp of 12:00, no matter what the time is at that moment?

I dont want to use .ToString("dd/MM/yyyy");, because it will open up a whole lot of new  possible errors.

答:
If you have any date

```<code>DateTime anyDate = DateTime.Now;
DateTime dateAtNoon = anyDate.Date.AddHours(12);
</code>```

or if you want today you can use the shortcut

```<code>DateTime dateAtNoon = DateTime.Today.AddHours(12);
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to save Date Time without the time?

Body:
If you have any date

DateTime anyDate = DateTime.Now;
DateTime dateAtNoon = anyDate.Date.AddHours(12);

or if you want today you can use the shortcut

DateTime dateAtNoon = DateTime.Today.AddHours(12);


问:
TypeScript filter out nulls from an array
TypeScript, --strictNullChecks mode.

Suppose I have an array of nullable strings (string | null)[]. What would be a single-expression way to remove all nulls in a such a way that the result has type string[]?

```<code>const array: (string | null)[] = ["foo", "bar", null, "zoo", null];
const filterdArray: string[] = ???;
</code>```

Array.filter does not work here:

```<code>// Type '(string | null)[]' is not assignable to type 'string[]'
array.filter(x => x != null);
</code>```

Array comprehensions could've work but they are not supported by TypeScript.

Actually the question can be generalized to the problem of filtering an array of any union type by removing entries having one particular type from the union. But  let's focus on unions with null and perhaps undefined as these are the most common usecases.

答:
You can cast your filter result into the type you want:

```<code>const array: (string | null)[] = ["foo", "bar", null, "zoo", null];
const filterdArray = array.filter(x => x != null) as string[];
</code>```

This works for the more general use case that you mentioned, for example:

```<code>const array2: (string | number)[] = ["str1", 1, "str2", 2];
const onlyStrings = array2.filter(x => typeof x === "string") as string[];
const onlyNumbers = array2.filter(x => typeof x === "number") as number[];
</code>```

(code in playground)

ContentLicense: CC BY-SA 4.0

Body:
TypeScript, --strictNullChecks mode.

Suppose I have an array of nullable strings (string | null)[]. What would be a single-expression way to remove all nulls in a such a way that the result has type string[]?

const array: (string | null)[] = ["foo", "bar", null, "zoo", null];
const filterdArray: string[] = ???;

Array.filter does not work here:

// Type '(string | null)[]' is not assignable to type 'string[]'
array.filter(x => x != null);

Array comprehensions could've work but they are not supported by TypeScript.

Actually the question can be generalized to the problem of filtering an array of any union type by removing entries having one particular type from the union. But  let's focus on unions with null and perhaps undefined as these are the most common usecases.

Body:
You can cast your filter result into the type you want:

const array: (string | null)[] = ["foo", "bar", null, "zoo", null];
const filterdArray = array.filter(x => x != null) as string[];

This works for the more general use case that you mentioned, for example:

const array2: (string | number)[] = ["str1", 1, "str2", 2];
const onlyStrings = array2.filter(x => typeof x === "string") as string[];
const onlyNumbers = array2.filter(x => typeof x === "number") as number[];

(<a href="https://www.typescriptlang.org/play/#src=const%20array%3A%20(string%20%7C%20null)%5B%5D%20%3D%20%5B%22foo%22%2C%20%22bar%22%2C%20null%2C%20%22zoo%22%2C%20null%5D%3B%0Aconst%20filterdArray%20%3D%20array.filter(x%20%3D%3E%20x%20!%3D%20null)%20as%20string%5B%5D%3B%0A%0Aconst%20array2%3A%20(string%20%7C%20number)%5B%5D%20%3D%20%5B%22str1%22%2C%201%2C%20%22str2%22%2C%202%5D%3B%0Aconst%20onlyStrings%20%3D%20array2.filter(x%20%3D%3E%20typeof%20x%20%3D%3D%3D%20%22string%22)%20as%20string%5B%5D%3B%0Aconst%20onlyNumbers%20%3D%20array2.filter(x%20%3D%3E%20typeof%20x%20%3D%3D%3D%20%22number%22)%20as%20number%5B%5D%3B" rel="noreferrer">code in playground)


问:
How to zip an iterator with an infinite range?
I want to keep track of index as I iterate through an iterator. In Haskell, I could just zip the iterator with an infinite list of integers, [1..]. However, I'm not aware of functionality like this in Python. What's the easiest way to construct an iterator that works as below?

```<code>for (case,i) in zip(data, magic_infinite_list):
    print('Case #{}: {}'.format(i,case))
</code>```

(I know I could just make a variable i and manually increment it, that's not the point -- I want to know if it's possible to do this with iterators)

答:
enumerate() was already given, and that's what most people would use.  But if you really want to start at 1, and get the integer second, itertools.count() generates a lazy infinite sequence of integers:

```<code>import itertools
for case, i in zip(data, itertools.count(1)):
    ...
</code>```

Body:
I want to keep track of index as I iterate through an iterator. In Haskell, I could just zip the iterator with an infinite list of integers, [1..]. However, I'm not aware of functionality like this in Python. What's the easiest way to construct an iterator that works as below?

for (case,i) in zip(data, magic_infinite_list):
    print('Case #{}: {}'.format(i,case))

(I know I could just make a variable i and manually increment it, that's not the point -- I want to know if it's possible to do this with iterators)

Body:
enumerate() was already given, and that's what most people would use.  But if you really want to start at 1, and get the integer second, itertools.count() generates a lazy infinite sequence of integers:

import itertools
for case, i in zip(data, itertools.count(1)):
    ...


问:
Are Firebase Object Keys Guessable?
Say I have data like so:

```<code>users{
 $authId: {
     name:"",
     propertiesById:{
          uniqueId1:true,
          uniqueId2:true
     }
 }
},
properties:{
     uniqueId1:{
        key:val
     },
     uniqueId2:{
        key:val
     }
 }
</code>```

Assuming that I have the proper rules in place for users to be able to only read/write their own user object, how do I go about reading my properties safely?

I know that in rules, I can go to root, find the user object and ensure that the property that I'm trying to read exists in the propertiesById, but that seems like it would impact performance since these will be very large collections of properties.

How would I, if at all possible, go about writing a rule that says: "users cannot grab the entire properties collection, only individually by key".  Also, if I were able to write this rule, would it be safe? I'm unclear on difficult it would be to guess the keys generated by firebase push().

答:
While Firebase push IDs are hard to guess, they are definitely guessable. You should not rely on the user not being able to guess a push ID for security.

Given that though, it is very easy to do precisely that:

```<code>{
  "rules": {
    "properties": {
      "$uniqueId": {
        ".read": true,
        ".write": true
      }
    }
  }
}
</code>```

These rules allow any user to read any specific property, as long as they know that property exists. So no-one can read /properties, but everyone can read /properties/uniqueId1 and /properties/uniqueId2.

But again: this is not secure as push IDs are at some level reasonably guessable.

From the Firebase blog post explaining push IDs:

We also get questions on whether developers can rely on push IDs to be unguessable by others, which can be important if you're trying to do security via unguessable Firebase paths. While push IDs are generally very hard to guess, if you’re relying on unguessable IDs you should generate them yourself using a more secure mechanism.

Title: Are Firebase Object Keys Guessable?

Body:
Say I have data like so:

users{
 $authId: {
     name:"",
     propertiesById:{
          uniqueId1:true,
          uniqueId2:true
     }
 }
},
properties:{
     uniqueId1:{
        key:val
     },
     uniqueId2:{
        key:val
     }
 }

Assuming that I have the proper rules in place for users to be able to only read/write their own user object, how do I go about reading my properties safely?

I know that in rules, I can go to root, find the user object and ensure that the property that I'm trying to read exists in the propertiesById, but that seems like it would impact performance since these will be very large collections of properties.

How would I, if at all possible, go about writing a rule that says: "users cannot grab the entire properties collection, only individually by key".  Also, if I were able to write this rule, would it be safe? I'm unclear on difficult it would be to guess the keys generated by firebase push().

Body:
While Firebase push IDs are hard to guess, they are definitely guessable. You should not rely on the user not being able to guess a push ID for security.

Given that though, it is very easy to do precisely that:

{
  "rules": {
    "properties": {
      "$uniqueId": {
        ".read": true,
        ".write": true
      }
    }
  }
}

These rules allow any user to read any specific property, as long as they know that property exists. So no-one can read /properties, but everyone can read /properties/uniqueId1 and /properties/uniqueId2.

But again: this is not secure as push IDs are at some level reasonably guessable.

From the Firebase blog post explaining push IDs:

We also get questions on whether developers can rely on push IDs to be unguessable by others, which can be important if you're trying to do security via unguessable Firebase paths. While push IDs are generally very hard to guess, if you’re relying on unguessable IDs you should generate them yourself using a more secure mechanism.


问:
What's the right way to include Android native binaries (.so files) in nugets for consumption in Xamarin?
We build nugets containing our app-specific native binaries.  We're pretty much just using nugets as a file transport mechanism though; we adjust the Xamarin projects to point to the the extracted libWhatever.so files in the packages/ directory, and mark them as EmbeddedNativeLibraries.

This works, but it feels much more like a hack than an actual solution.

So what is the right way to do this?  All the existing nuget documentation I've found assumes that native binaries are Windows dlls - certainly not useful in an Android context.

We need to be able include multiple architectures in the nugets, of course; armeabi, armeabi-v7a, x86, etc.  Can't include Windows nastiness like powershell, either, since we mostly work on macs (Some threads I've seen in other places thought that fixing things up with powershell scripts embedded in the nuget might be the way to go).

Update:  there's a relevant discussion at https://forums.xamarin.com/discussion/35517/is-it-possible-to-include-native-libraries-automatically-from-a-nuget-package

答:
Do it with a custom .targets in your Nuget's build directory that adds your shared library into your Android project's as AndroidNativeLibrary items. When you add the Nuget to your project, the target gets added to your .csproj and you are all set...

Example:

To include libDNAGenetics.so into an Xamarin.Android project's as AndroidNativeLibrary build items, create a .targets that includes:

```<code>  <PropertyGroup>
    <_DNAGeneticNugetNativePath Condition="'$(_DNAGeneticNugetNativePath)' == ''">$(MSBuildThisFileDirectory)..\native\</_DNAGeneticNugetNativePath>
  </PropertyGroup>

  <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == 'MonoAndroid'">
    <AndroidNativeLibrary Include="$(_DNAGeneticNugetNativePath)android\armeabi-v7a\libDNAGenetics.so">
      <Link>$(_DNAGeneticNugetNativePath)android\armeabi-v7a\libDNAGenetics.so</Link>
    </AndroidNativeLibrary>
    <AndroidNativeLibrary Include="$(_DNAGeneticNugetNativePath)android\x86\libDNAGenetics.so">
      <Link>$(_DNAGeneticNugetNativePath)android\x86\libDNAGenetics.so</Link>
    </AndroidNativeLibrary>
    <AndroidNativeLibrary Include="$(_DNAGeneticNugetNativePath)android\arm64-v8a\libDNAGenetics.so">
      <Link>$(_DNAGeneticNugetNativePath)android\arm64-v8a\libDNAGenetics.so</Link>
    </AndroidNativeLibrary>
    <AndroidNativeLibrary Include="$(_DNAGeneticNugetNativePath)android\x86_64\libDNAGenetics.so">
      <Link>$(_DNAGeneticNugetNativePath)android\x86_64\libDNAGenetics.so</Link>
    </AndroidNativeLibrary>
  </ItemGroup>
</code>```

Body:
Do it with a custom .targets in your Nuget's build directory that adds your shared library into your Android project's as AndroidNativeLibrary items. When you add the Nuget to your project, the target gets added to your .csproj and you are all set...

Example:

To include libDNAGenetics.so into an Xamarin.Android project's as AndroidNativeLibrary build items, create a .targets that includes:

  <PropertyGroup>
    <_DNAGeneticNugetNativePath Condition="'$(_DNAGeneticNugetNativePath)' == ''">$(MSBuildThisFileDirectory)..\native\</_DNAGeneticNugetNativePath>
  </PropertyGroup>

  <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == 'MonoAndroid'">
    <AndroidNativeLibrary Include="$(_DNAGeneticNugetNativePath)android\armeabi-v7a\libDNAGenetics.so">
      <Link>$(_DNAGeneticNugetNativePath)android\armeabi-v7a\libDNAGenetics.so</Link>
    </AndroidNativeLibrary>
    <AndroidNativeLibrary Include="$(_DNAGeneticNugetNativePath)android\x86\libDNAGenetics.so">
      <Link>$(_DNAGeneticNugetNativePath)android\x86\libDNAGenetics.so</Link>
    </AndroidNativeLibrary>
    <AndroidNativeLibrary Include="$(_DNAGeneticNugetNativePath)android\arm64-v8a\libDNAGenetics.so">
      <Link>$(_DNAGeneticNugetNativePath)android\arm64-v8a\libDNAGenetics.so</Link>
    </AndroidNativeLibrary>
    <AndroidNativeLibrary Include="$(_DNAGeneticNugetNativePath)android\x86_64\libDNAGenetics.so">
      <Link>$(_DNAGeneticNugetNativePath)android\x86_64\libDNAGenetics.so</Link>
    </AndroidNativeLibrary>
  </ItemGroup>


问:
Where to find JavaScript documentation?
I think theres one https://developer.mozilla.org/en/JavaScript/Reference but for for things like what properties/functions a Textarea object will have, where can I get it?

I know textarea have properties like selectionStart, selectionEnd but what others? where can I find that info?

答:
If you need to know anything about javascript

Search for it in google and add the word "mdc" on the end. I personally find the internal MDC search bar annoying and unhelpful.

in your case :

https://developer.mozilla.org/en/DOM/HTMLTextAreaElement

[Edit]

I actaully do this for everything. For example rather then wading through the MSDN website if I need to know anything about a transact sql command. I search for the command in google and add "t sql msdn". If only people used the google search engine internally on their websites rather then their own half baked search engine.

Title: Where to find JavaScript documentation?


问:
Can foreign keys act as a primary key?
If a table has a composite primary key made of attribute A, B and this composite primary key is referenced in another table, can that other table have attribute A as a primary key and NOT attribute b? And maybe, Attribute A with some other attribute in the same table as another composite primary key?</p>

答:
Yes.  One fairly common example is a general ledger.  The Item table has a composite key, consisting of Transaction Number and Item Number (within transaction). The Transaction table has a key of Transaction Number, referenced by one of the key fields in Item.
General ledger systems aren't always designed this way, but they often are.</p>

Title: Can foreign keys act as a primary key?


问:
AWS ALB - Error during WebSocket handshake
I am running a tomcat/java web app on aws behind an application load balancer.

I have an WebSocket endpoint set up at "/socketserver". Locally everything works, but when web app is deployed to aws, creating an websocket client through javascript
(e.g. var exampleSocket = new WebSocket("ws://www.example.com/socketserver");
returns 404 error during Websocket handshake.

Is there any additional setup required? I heard ALB supports websockets natively. Thanks.

some things I tried:

creating a separate target group with path to "/socketserver", and adding additional http rule, and enabled session stickiness.

changing maven websocket dependency scope to provided.

checked access log, found
127.0.0.1 - - [26/Mar/2017:13:31:29 +0000] "GET /socketserver HTTP/1.1" 404 1002

答: If you are using ALB and are experiencing this problem try updating your security policy, I ran into the same problem even though it was working perfectly fine in the same setup for another website but noticed the security policy was about 1 year behind. Updating it to a newer one seems to have solved the problem.</p>


问:
ifelse in R to determine 2 conditions; one simple the other composite
Background:

I have two elements in an R function (see my R code below), type and width. The type element simply can be 1 or 2. But width can take any number.

Question:

Suppose there there two specific numbers that act as criteria for width. First number is 1. Second number is sqrt(2) / 2.

How can I say:

IF "type" is 1 AND "width" is NOT 1 AND ALSO (i.e., still type is 1) "width" is NOT sqrt(2) / 2,  THEN "do ..."?

Can I use:

```<code> type = 1
 width = sqrt(2)/ 2

ifelse(type == 1 & width != 1 & width != sqrt(2)/2, "do nothing", "the critera" )
</code>```

答:
It depends on what you want to do.  ifelse() has the slight oddity of returning something of the same length as the logical condition.  Hence, it can be great (simple) for assignment statements such as

```<code>a <- 1
b <- ifelse(a==1,1,2)
b
[1] 1
</code>```

or even

```<code>a <- c(1,3,5,7)
b <- ifelse(a<4,1,2)
b
[1] 1 1 2 2
</code>```

However, this makes ifelse() a bad choice for other things, such as flow, in which case, you're better off with something like

```<code>if(type == 1 & width != 1 & width != sqrt(2)/2) {
  answer <- "yes, this is the criteria"
  doSomeStuff(width)
}
else {
  answer <- "I'm sorry, but the princess is in another castle"
  doSomeOtherStuffInstead(width)
}
</code>```

It's worth pointing out that weird things can happen if the lengths don't match up.  Such as...

```<code>a <- 1:4
b <- 5:9
c <- ifelse(1<2,a,b)
c
[1] 1
</code>```

You'd think c would now contain all the elements of a but it doesn't - only the first element.

Hope this helps!

Body:
Background:

I have two elements in an R function (see my R code below), type and width. The type element simply can be 1 or 2. But width can take any number.

Question:

Suppose there there two specific numbers that act as criteria for width. First number is 1. Second number is sqrt(2) / 2.

How can I say:

IF "type" is 1 AND "width" is NOT 1 AND ALSO (i.e., still type is 1) "width" is NOT sqrt(2) / 2,  THEN "do ..."?

Can I use:

 type = 1
 width = sqrt(2)/ 2

ifelse(type == 1 & width != 1 & width != sqrt(2)/2, "do nothing", "the critera" )

Body:
It depends on what you want to do.  ifelse() has the slight oddity of returning something of the same length as the logical condition.  Hence, it can be great (simple) for assignment statements such as

a <- 1
b <- ifelse(a==1,1,2)
b
[1] 1

or even

a <- c(1,3,5,7)
b <- ifelse(a<4,1,2)
b
[1] 1 1 2 2

However, this makes ifelse() a bad choice for other things, such as flow, in which case, you're better off with something like

if(type == 1 & width != 1 & width != sqrt(2)/2) {
  answer <- "yes, this is the criteria"
  doSomeStuff(width)
}
else {
  answer <- "I'm sorry, but the princess is in another castle"
  doSomeOtherStuffInstead(width)
}

It's worth pointing out that weird things can happen if the lengths don't match up.  Such as...

a <- 1:4
b <- 5:9
c <- ifelse(1<2,a,b)
c
[1] 1

You'd think c would now contain all the elements of a but it doesn't - only the first element.

Hope this helps!


问:
Google app script trigger not working
I have a google app script which sends email, and i have set a trigger such that it sends email on every form submit. The problem is the trigger works perfectly fine for initial few minutes, but later even after entering correct data. The script does not send the mail, i have to manually press the execution button of the script. Here is my code

```<code>var EMAIL_SENT = "EMAIL_SENT";
function sendEmailsapp() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = sheet.getLastRow();   // Number of rows to process
  // Fetch the range of cells A2:B3

  var dataRange = sheet.getRange(startRow, 1, numRows,8)
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var emailAddress = row[4];  // First column
    var message = row[5];       // Second column
    var emailSent = row[7];  // Third column
    var money=row[6]
    if (emailSent != EMAIL_SENT) {  // Prevents sending duplicates
      var subject = "You have been registered for follwoing events:-";
      var event;

      MailApp.sendEmail(emailAddress, subject, "Please bring your college id and copy of this mail either in phone or printed paper"+
                        "\n\n"+"Name:-"+row[1]+"\n"+"USN:-"+row[2]+"\n"+"Mobile:-"+row[3]+"\n"+"Event:-"+ message+"\nMoney status:-"+money+"You registered on"+row[0]);
        sheet.getRange(startRow + i, 8).setValue(EMAIL_SENT);

      // Make sure the cell is updated right away in case the script is interrupted
      SpreadsheetApp.flush();
    }
  }
}
</code>```

The code works fine. The only problem is triggers.

Here is the image of my trigger. sendEmailsapp is the trigger, and sendEmailsweb is another trigger which also suffers from same problem.

here is the log

My only Problem is the trigger is not getting triggered, it is not with the email being sent.

答:
My trigger wasn't working just like yours, even though the script was correct.

The solution was very stupid. I deleted the trigger and added a new one. Exactly the same trigger.

Title: Google app script trigger not working

Body:
I have a google app script which sends email, and i have set a trigger such that it sends email on every form submit. The problem is the trigger works perfectly fine for initial few minutes, but later even after entering correct data. The script does not send the mail, i have to manually press the execution button of the script. Here is my code

var EMAIL_SENT = "EMAIL_SENT";
function sendEmailsapp() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = sheet.getLastRow();   // Number of rows to process
  // Fetch the range of cells A2:B3

  var dataRange = sheet.getRange(startRow, 1, numRows,8)
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var emailAddress = row[4];  // First column
    var message = row[5];       // Second column
    var emailSent = row[7];  // Third column
    var money=row[6]
    if (emailSent != EMAIL_SENT) {  // Prevents sending duplicates
      var subject = "You have been registered for follwoing events:-";
      var event;

      MailApp.sendEmail(emailAddress, subject, "Please bring your college id and copy of this mail either in phone or printed paper"+
                        "\n\n"+"Name:-"+row[1]+"\n"+"USN:-"+row[2]+"\n"+"Mobile:-"+row[3]+"\n"+"Event:-"+ message+"\nMoney status:-"+money+"You registered on"+row[0]);
        sheet.getRange(startRow + i, 8).setValue(EMAIL_SENT);

      // Make sure the cell is updated right away in case the script is interrupted
      SpreadsheetApp.flush();
    }
  }
}

The code works fine. The only problem is triggers.

Here is the image of my trigger. sendEmailsapp is the trigger, and sendEmailsweb is another trigger which also suffers from same problem.

here is the log

My only Problem is the trigger is not getting triggered, it is not with the email being sent.


问:
MYSQL SELECT ... FOR UPDATE Not working?
I am having issues with MySQL's SELECT .. FOR UPDATE, here is the query I am trying to run:

```<code>SQL = "SELECT * " +
      "FROM " + TableName + " " +
      "WHERE out_status IN ("+outSStatus+") AND queued <= NOW() " +
      "ORDER BY out_status, id_queue ASC "+ limitSql+
      "FOR UPDATE";
</code>```

After this, the thread will do an UPDATE and change the out_status to 99, which is then it should unlock the row.

I am running a multi-threaded java application, so 3 threads are running this SQL statement, but when thread 1 runs this, it doesn't lock (hide) its results from thread 2 & 3. Therefore threads 2 & 3 are getting the same results.

Also each thread is on its own mysql connection.

Can anybody please help me with this? OR perhaps have a better solution?

Much Appreciated.

答:
It might be working, and you are unable to notice. Say thread 1 executed the statement, and committed the transaction automatically, because auto-commit was on. Then of course thread 2 would be able to run that too.

Try setting auto-commit off, using this method of Connection class and then see the result.

Body:
I am having issues with MySQL's SELECT .. FOR UPDATE, here is the query I am trying to run:

SQL = "SELECT * " +
      "FROM " + TableName + " " +
      "WHERE out_status IN ("+outSStatus+") AND queued <= NOW() " +
      "ORDER BY out_status, id_queue ASC "+ limitSql+
      "FOR UPDATE";

After this, the thread will do an UPDATE and change the out_status to 99, which is then it should unlock the row.

I am running a multi-threaded java application, so 3 threads are running this SQL statement, but when thread 1 runs this, it doesn't lock (hide) its results from thread 2 & 3. Therefore threads 2 & 3 are getting the same results.

Also each thread is on its own mysql connection.

Can anybody please help me with this? OR perhaps have a better solution?

Much Appreciated.


问:
i need help on "this" keyword and inheritance
```<code>abstract class BaseClass
{
    public virtual void Accept(IVisitor visitor)
    {
        visitor.Visit(this);
    }
}

class DerivedClass: BaseClass
{
}

interface IVisitor
{
    void Visit(BaseClass baseEntity);
    void Visit(DerivedClass derivedEntity);
}

class Visitor : IVisitor
{
    public void Visit(DerivedClass derivedEntity)
    {
        Debug.WriteLine("Derived Entity visited");
    }

    public void Visit(BaseClass baseEntity)
    {
        Debug.WriteLine("Base Entity visited");
    }
}
</code>```

After above declerations

```<code>class Program
{
    static void Main(string[] args)
    {
        DerivedClass derived = new DerivedClass();
        Visitor visitor = new Visitor();
        derived.Accept(visitor);
    }
}
</code>```

produces

```<code>"Base Entity visited"
</code>```

however i expect it to produce

```<code>"Derived Entity visited"
</code>```

Can anyone explain why?

What should i do to produce "Derived Entity visited"? I don't want to override "Accept" function.

答:
Overloads are resolved at compile time, so the when compiling your BaseClass, the compiler is going to pick the Visitor.Visit overload that matches its compile time type (BaseClass).

When using the Visitor pattern, you typically will want to override the Accept method in derived classes.

While you can avoid this using dynamic, you will lose the advantage of static type checking if you do so.

This article shows an example of the visitor pattern in C# where the Accept method is overridden in derived classes.

Body:
abstract class BaseClass
{
    public virtual void Accept(IVisitor visitor)
    {
        visitor.Visit(this);
    }
}

class DerivedClass: BaseClass
{
}

interface IVisitor
{
    void Visit(BaseClass baseEntity);
    void Visit(DerivedClass derivedEntity);
}

class Visitor : IVisitor
{
    public void Visit(DerivedClass derivedEntity)
    {
        Debug.WriteLine("Derived Entity visited");
    }

    public void Visit(BaseClass baseEntity)
    {
        Debug.WriteLine("Base Entity visited");
    }
}

After above declerations

class Program
{
    static void Main(string[] args)
    {
        DerivedClass derived = new DerivedClass();
        Visitor visitor = new Visitor();
        derived.Accept(visitor);
    }
}

produces

"Base Entity visited"

however i expect it to produce

"Derived Entity visited"

Can anyone explain why?

What should i do to produce "Derived Entity visited"? I don't want to override "Accept" function.


问:
Add elements to sub-array recursively
I'm trying to add elements to a sub array of the sub array where they were added in the previous iteration, i.e. transforming this:

```<code>$a = array('a', 'b', 'c');
</code>```

Into this:

```<code>$new_array = array(
    'a' => array(
        'b' => array(
            'c' => array()
        )
    )
);
</code>```

答:
```<code>$a = array('a', 'b', 'c');

$tmp = array_reverse($a);

$new_array = array();
foreach ($tmp as $item) { $new_array = array($item => $new_array); }
</code>```

Title: Add elements to sub-array recursively

Body:
I'm trying to add elements to a sub array of the sub array where they were added in the previous iteration, i.e. transforming this:

$a = array('a', 'b', 'c');

Into this:

$new_array = array(
    'a' => array(
        'b' => array(
            'c' => array()
        )
    )
);


问:
Add a new user in a table row using angular
I have an angular admin project, in this project the user can add/delete users in the data base. The thing is, i have a list of all users showing at the same page as are the delete button and the add new user fields; so, when i delete/add i want this new user to show immediately at the screen or to vanish of the screen(in the case of delete);

Here is my controller of the add user:

```<code>(function(){
    angular.module("agendaRaiar").controller('findUserController', ['$scope','UserWsService', function($scope, UserWsService){
        $scope.passTheScope = function(user){
            $scope.objectUser = user; //isso é feito para ter o id dentro do deletecontroller
        }

        $scope.getUsersAtParse = function(){
                UserWsService.getUsersAtParse().then(function(resultArray) {
                    $scope.users = resultArray;
                    console.log(resultArray);
                });
        };
    }]);
}());
</code>```

someone can help me? Thanks a lot!

答:
Have you tried using $scope.user.push(resultArray)? this will add the newly created user in your view. for delete, try on $scope.user.splice

```<code> $http.post(...).then(function(response){
  $scope.myarrayObj.push(response);
});
</code>```

Body:
I have an angular admin project, in this project the user can add/delete users in the data base. The thing is, i have a list of all users showing at the same page as are the delete button and the add new user fields; so, when i delete/add i want this new user to show immediately at the screen or to vanish of the screen(in the case of delete);

Here is my controller of the add user:

(function(){
    angular.module("agendaRaiar").controller('findUserController', ['$scope','UserWsService', function($scope, UserWsService){
        $scope.passTheScope = function(user){
            $scope.objectUser = user; //isso é feito para ter o id dentro do deletecontroller
        }

        $scope.getUsersAtParse = function(){
                UserWsService.getUsersAtParse().then(function(resultArray) {
                    $scope.users = resultArray;
                    console.log(resultArray);
                });
        };
    }]);
}());

someone can help me? Thanks a lot!

Body:
Have you tried using $scope.user.push(resultArray)? this will add the newly created user in your view. for delete, try on $scope.user.splice

 $http.post(...).then(function(response){
  $scope.myarrayObj.push(response);
});


问:
Trouble getting total count using .Take() and .Skip()
I'm having some trouble implementing some paging using Linq and I've read the various questions (this and this for example) on here but I'm still getting the error;

System.InvalidOperationException: The result of a query cannot be enumerated more than once.

My (slightly obfuscated) code is;

```<code>public List<Thing> GetThings(ObjectParameter[] params, int count, int pageIndex)
{
    var things = from t in Context.ExecuteFunction<Something>("function", params)
                 select new Thing
                 {
                     ID = t.ID
                 });

    var pagedThings = things;

    if (pageIndex == 0)
        pagedThings = things.Take(count);
    else if (pageIndex > 0)
        pagedThings = things.Skip(count * pageIndex).Take(count);

    var countOfThings = things.Count();

    return pagedThings.ToList();
}
</code>```

As soon as the final .ToList() is called, the error is thrown but I can't see why - are the calls to things.Count() and pagedThings.ToList() enumerating the same thing?

Edit: I'm using Entity Framework if that makes any difference

答:
In general, Linq is able to do that. In LinqPad, I wrote the following code and successfully executed it:

```<code>void Main()
{
    var sampleList = new List<int>();
    for (int i = 0; i < 100; i++){
        sampleList.Add(i);
    }

    var furtherQuery = sampleList.Take(3).Skip(4);
    var count = furtherQuery.Count();
    var cache = furtherQuery.ToList();
</code>```

}

Note, as your error mentions, this will execute the query twice. Once for Count() and once for ToList().

It must be that the Linq provider that you are representing as Context.ExecuteFunction<Something>("function", params) is protecting you from making multiple expensive calls. You should look for a way to iterate over the results only once. As written, for example, you could .Count() on the List that you had already generated.

Body:
I'm having some trouble implementing some paging using Linq and I've read the various questions (this and this for example) on here but I'm still getting the error;

System.InvalidOperationException: The result of a query cannot be enumerated more than once.

My (slightly obfuscated) code is;

public List<Thing> GetThings(ObjectParameter[] params, int count, int pageIndex)
{
    var things = from t in Context.ExecuteFunction<Something>("function", params)
                 select new Thing
                 {
                     ID = t.ID
                 });

    var pagedThings = things;

    if (pageIndex == 0)
        pagedThings = things.Take(count);
    else if (pageIndex > 0)
        pagedThings = things.Skip(count * pageIndex).Take(count);

    var countOfThings = things.Count();

    return pagedThings.ToList();
}

As soon as the final .ToList() is called, the error is thrown but I can't see why - are the calls to things.Count() and pagedThings.ToList() enumerating the same thing?

Edit: I'm using Entity Framework if that makes any difference

Body:
In general, Linq is able to do that. In LinqPad, I wrote the following code and successfully executed it:

void Main()
{
    var sampleList = new List<int>();
    for (int i = 0; i < 100; i++){
        sampleList.Add(i);
    }

    var furtherQuery = sampleList.Take(3).Skip(4);
    var count = furtherQuery.Count();
    var cache = furtherQuery.ToList();

}

Note, as your error mentions, this will execute the query twice. Once for Count() and once for ToList().

It must be that the Linq provider that you are representing as Context.ExecuteFunction<Something>("function", params) is protecting you from making multiple expensive calls. You should look for a way to iterate over the results only once. As written, for example, you could .Count() on the List that you had already generated.


答:
The problem you are facing here is with multiple dispatching. Compiler selects the base class because you are calling it from the base class. One quick solution you can add is to use dynamic:

```<code>public virtual void Accept(IVisitor visitor)
{
    visitor.Visit(this as dynamic);
}
</code>```

You trick the compiler to not know the actual type of the object - and call the correct Visit overload.

And here is some extra reading from MSND

Title: i need help on "this" keyword and inheritance

Body:
The problem you are facing here is with multiple dispatching. Compiler selects the base class because you are calling it from the base class. One quick solution you can add is to use dynamic:

public virtual void Accept(IVisitor visitor)
{
    visitor.Visit(this as dynamic);
}

You trick the compiler to not know the actual type of the object - and call the correct Visit overload.

And here is some extra reading from MSND


问:
how to add --auth for mongodb image when using docker-compose?
I'm using docker-compose to run my project created by node,mongodb,nginx;

and I have build the project using docker build

and then I use docker up -d nginx to start my project. but I haven't found the config to run mongodb image with '--auth', so how to add '--auth' when compose start the mongodb?

here is my docker-compose.yml:

```<code>version: "2"
services:
  mongodb:
    image: mongo:latest
    expose:
        - "27017"
    volumes:
        - "/home/open/mymongo:/data/db"
  nginx:
    build: /home/open/mynginx/
    ports:
        - "8080:8080"
        - "80:80"
    links:
        - node_server:node
  node_server:
    build: /home/laoqiren/workspace/isomorphic-redux-CNode/
    links:
        - mongodb:mongo
    expose:
        - "3000"
</code>```

答:
Supply a command to the container including the --auth option.

```<code>  mongodb:
    image: mongo:latest
    expose:
        - "27017"
    volumes:
        - "/home/open/mymongo:/data/db"
    command: mongod --auth
</code>```

The latest mongo containers come with "root" auth initialisation via environment variables too, modelled on the postgres setup.

Body:
I'm using docker-compose to run my project created by node,mongodb,nginx;

and I have build the project using docker build

and then I use docker up -d nginx to start my project. but I haven't found the config to run mongodb image with '--auth', so how to add '--auth' when compose start the mongodb?

here is my docker-compose.yml:

version: "2"
services:
  mongodb:
    image: mongo:latest
    expose:
        - "27017"
    volumes:
        - "/home/open/mymongo:/data/db"
  nginx:
    build: /home/open/mynginx/
    ports:
        - "8080:8080"
        - "80:80"
    links:
        - node_server:node
  node_server:
    build: /home/laoqiren/workspace/isomorphic-redux-CNode/
    links:
        - mongodb:mongo
    expose:
        - "3000"

Body:
Supply a command to the container including the --auth option.

  mongodb:
    image: mongo:latest
    expose:
        - "27017"
    volumes:
        - "/home/open/mymongo:/data/db"
    command: mongod --auth

The latest mongo containers come with "root" auth initialisation via environment variables too, modelled on the postgres setup.


问:
bxslider show more than 1 image on mobile
I am using bxslider on this site and I am trying to edit the number of images to be shown on the slider on mobile (site here), from 1 to 3 (from 768px to 320px). I think I am looking in the right place, but I'm not sure how to change the # of slides shown.

HTML

```<code><ul class="patient-slider">
   <?php
   $patients = get_post_meta($post->ID, 'ub_pmeta_1', true);
   foreach($patients as $patient){
   ?>
    <li><a href="<?php echo $patient['p_url']; ?>">
      <div class="thumbnail2">
        <p><img src="<?php echo $patient['p_image']; ?>" /></p>
        <div class="overlay">
          <h3><?php echo $patient['p_name']; ?></h3>
        </div>
      </div>
      </a></li>
    <?php } ?>
  </ul>
</code>```

jQuery

```<code>jQuery('.patient-slider').bxSlider({minSlides: 6,maxSlides: maxSlides ,moveSlides:1,slideWidth: 335,slideMargin: 1,pager : false });
</code>```

答: You'll need to set minSlides to 3 and maxSlides to 6 in the bxSlider settings. That will ensure there are always 3 slides shown no matter the screen size and up 6 shown on larger screen sizes. There is some interplay with slideWidth setting. That should probably be called slideMAXWidth as it governs the max width for a slide, not its actual width. The actual width will be calculated based on the screen size and minSlides.

Body:
I am using bxslider on this site and I am trying to edit the number of images to be shown on the slider on mobile (site here), from 1 to 3 (from 768px to 320px). I think I am looking in the right place, but I'm not sure how to change the # of slides shown.

HTML

   <?php
   $patients = get_post_meta($post->ID, 'ub_pmeta_1', true);
   foreach($patients as $patient){
   ?>

<a href="<?php echo $patient['p_url']; ?>">

<img src="<?php echo $patient['p_image']; ?>" />

<?php echo $patient['p_name']; ?>

    <?php } ?>

jQuery

jQuery('.patient-slider').bxSlider({minSlides: 6,maxSlides: maxSlides ,moveSlides:1,slideWidth: 335,slideMargin: 1,pager : false });


问:
How do I write a simple auto completer for a php form?
I have an html/php form that takes 2 inputs from the user and displays the search results by running a query on the database. How I can enable auto complete for the 2 user inputs where the results are searched from the database using AJAX calls?</p>

答: If 'enable-auto-complete' = Show a possible list of values in a drop down, then there is a jquery plugin with the same name. You can use with an array of values in javascript or in conjunction with Ajax.</p>


问:
read txt file with scientifc notations to pandas dataframe in scientific notation
is there a way to keep scientific notation consistent in txt file and after reading it to pandas dataframe.

pd.read_csv(physio_files[1], sep=" ", header = None)

above command is suppressing scientific notation.

Body:
Consider the dataframe df

df = pd.DataFrame(1000000., range(5), range(5))
print(df)

           0          1          2          3          4
0  1000000.0  1000000.0  1000000.0  1000000.0  1000000.0
1  1000000.0  1000000.0  1000000.0  1000000.0  1000000.0
2  1000000.0  1000000.0  1000000.0  1000000.0  1000000.0
3  1000000.0  1000000.0  1000000.0  1000000.0  1000000.0
4  1000000.0  1000000.0  1000000.0  1000000.0  1000000.0

You can control the formatting using pandas 'displat.float_format' option.  You can also assume a value for that option temporarily using pd.option_context

Use '{:0.4e}'.format as your custom formatter.  Change the 4 to suit your needs.

with pd.option_context('display.float_format', '{:0.4e}'.format):
    print(df)

           0          1          2          3          4
0 1.0000e+06 1.0000e+06 1.0000e+06 1.0000e+06 1.0000e+06
1 1.0000e+06 1.0000e+06 1.0000e+06 1.0000e+06 1.0000e+06
2 1.0000e+06 1.0000e+06 1.0000e+06 1.0000e+06 1.0000e+06
3 1.0000e+06 1.0000e+06 1.0000e+06 1.0000e+06 1.0000e+06
4 1.0000e+06 1.0000e+06 1.0000e+06 1.0000e+06 1.0000e+06


问:
Getting wordpress author image url issue
I am having trouble understanding why I can't get the author url to work.
I am getting the gravatar uri but the image is not showing.

Here is what is being displayed in the html code:

```<code><div class="authorBackgroundImg slick-slide" style="background: url("http://1.gravatar.com/avatar/d098d4e8?s=96&d=mm&r=g") 0% 0% / cover no-repeat; height: 445px; position: relative; width: 217px;" data-slick-index="5" aria-hidden="true" tabindex="-1" role="option" aria-describedby="slick-slide05">
</code>```

Here is what the php code looks like to retrieve the avatar url:

```<code>$profileImgUrl = get_avatar_url( $userId, '500' );
</code>```

Here is the query for the wordpress database:

```<code>$queryAuthorVals = "
                SELECT DISTINCT {$wpdb->prefix}users.display_name, {$wpdb->prefix}users.ID, {$wpdb->prefix}posts.post_author
                FROM {$wpdb->prefix}users, {$wpdb->prefix}posts
                LEFT JOIN {$wpdb->prefix}term_relationships rel ON rel.object_id = {$wpdb->prefix}posts.ID
                LEFT JOIN {$wpdb->prefix}term_taxonomy tax ON tax.term_taxonomy_id = rel.term_taxonomy_id
                LEFT JOIN {$wpdb->prefix}terms t ON t.term_id = tax.term_id
                WHERE {$wpdb->prefix}posts.post_author = {$wpdb->prefix}users.ID
                AND {$wpdb->prefix}posts.post_type = 'post'
                ORDER BY {$wpdb->prefix}users.display_name ASC
            ";

            $postAuthors = $wpdb->get_results($queryAuthorVals, OBJECT);
</code>```

"Note" I have removed part of the id from the users avatar url 'http://1.gravatar.com/avatar/d098d4e8?s=96&d=mm&r=g' but it shows the avatar when I put the url in the browser.
Also I can display the  element with get_avatar( $userId, '500' ); but this is not what I want to do.

Anyone know how to fix this, I can't seem to find a solution on google.

Cheers

答:
OK so I figured it out, because I'm using the ultimate member plugin I have got it to work by using the ultimate member functions

```<code>$ultimatemember->user->set( $userId );//set the user id
$userAvatar = um_get_avatar_uri( um_profile('profile_photo'), 400 );//get the user avatar based on the current user id.
</code>```

I tried this earlier but didn't use the set user function $ultimatemember->user->set( $userId ); so it was grabbing my avatar for each author image as I'm building a custom authors slider.

Hope this helps someone else :)

Body:
I am having trouble understanding why I can't get the author url to work.
I am getting the gravatar uri but the image is not showing.

Here is what is being displayed in the html code:

Here is what the php code looks like to retrieve the avatar url:

$profileImgUrl = get_avatar_url( $userId, '500' );

Here is the query for the wordpress database:

$queryAuthorVals = "
                SELECT DISTINCT {$wpdb->prefix}users.display_name, {$wpdb->prefix}users.ID, {$wpdb->prefix}posts.post_author
                FROM {$wpdb->prefix}users, {$wpdb->prefix}posts
                LEFT JOIN {$wpdb->prefix}term_relationships rel ON rel.object_id = {$wpdb->prefix}posts.ID
                LEFT JOIN {$wpdb->prefix}term_taxonomy tax ON tax.term_taxonomy_id = rel.term_taxonomy_id
                LEFT JOIN {$wpdb->prefix}terms t ON t.term_id = tax.term_id
                WHERE {$wpdb->prefix}posts.post_author = {$wpdb->prefix}users.ID
                AND {$wpdb->prefix}posts.post_type = 'post'
                ORDER BY {$wpdb->prefix}users.display_name ASC
            ";

            $postAuthors = $wpdb->get_results($queryAuthorVals, OBJECT);

"Note" I have removed part of the id from the users avatar url 'http://1.gravatar.com/avatar/d098d4e8?s=96&d=mm&r=g' but it shows the avatar when I put the url in the browser.
Also I can display the  element with get_avatar( $userId, '500' ); but this is not what I want to do.

Anyone know how to fix this, I can't seem to find a solution on google.

Cheers

Body:
OK so I figured it out, because I'm using the ultimate member plugin I have got it to work by using the ultimate member functions

$ultimatemember->user->set( $userId );//set the user id
$userAvatar = um_get_avatar_uri( um_profile('profile_photo'), 400 );//get the user avatar based on the current user id.

I tried this earlier but didn't use the set user function $ultimatemember->user->set( $userId ); so it was grabbing my avatar for each author image as I'm building a custom authors slider.

Hope this helps someone else :)


问:
array, std::list, std::vector inserting time
I am making a test program to measure time for storage of each container. The following is my code for the test.

```<code>#include <list>
#include <vector>
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;

void insert(list<short>& l, const short& value);
void insert(vector<short>& v, const short& value);
void insert(short arr[], int& logicalSize, const int& physicalSize, const short& value);

int main() {
    clock_t start, end;
    srand(time(nullptr));

    const int SIZE = 50000;
    const short RANGE = 10000;
    list<short> l;
    vector<short> v;
    short* arr = new short[SIZE];
    int logicalSize = 0;

    // array
    start = clock();
    cout << "Array storage time test...";
    for (int i = 0; i < SIZE; i++) {
        try {
            insert(arr, logicalSize, SIZE, (short)(rand() % (2 * RANGE + 1) - RANGE));
        } catch (string s) {
            cout << s << endl;
            system("pause");
            exit(-1);
        }
    }
    end = clock();
    cout << "Time: " << difftime(end, start) << endl << endl;

    // list
    cout << "List storage time test...";
    start = clock();
    for (int i = 0; i < SIZE; i++) {
        insert(l, (short)(rand() % (2 * RANGE + 1) - RANGE));
    }
    end = clock();
    cout << "Time: " << difftime(end, start) << endl << endl;

    // vector
    cout << "Vector storage time test...";
    start = clock();
    for (int i = 0; i < SIZE; i++) {
        insert(v, (short)(rand() % (2 * RANGE + 1) - RANGE));
    }
    end = clock();
    cout << "Time: " << difftime(end, start) << endl << endl;

    delete[] arr;
    system("pause");
    return 0;
}

void insert(list<short>& l, const short& value) {
    for (auto it = l.begin(); it != l.end(); it++) {
        if (value < *it) {
            l.insert(it, value);
            return;
        }
    }
    l.push_back(value);
}

void insert(vector<short>& v, const short& value) {
    for (auto it = v.begin(); it != v.end(); it++) {
        if (value < *it) {
            v.insert(it, value);
            return;
        }
    }
    v.push_back(value);
}

void insert(short arr[], int& logicalSize, const int& physicalSize, const short& value) {
    if (logicalSize == physicalSize) throw string("No spaces in array.");
    for (int i = 0; i < logicalSize; i++) {
        if (value < arr[i]) {
            for (int j = logicalSize - 1; j >= i; j--) {
                arr[j + 1] = arr[j];
            }
            arr[i] = value;
            logicalSize++;
            return;
        }
    }
    arr[logicalSize] = value;
    logicalSize++;
}
</code>```

However, when I execute the code, the result seems a little different from the theory. The list should be fastest, but the result said that insertion in the list is slowest. Can you tell me why?

答:
Inserting into a vector or array requires moving everything after it; so if at a random spot, requires an average of 1.5 accesses to each element.  0.5 to find the spot, and 0.5*2 (read and write) to do the insert.

Inserting into a list requires 0.5 accesses per element (to find the spot).

This means the vector is only 3 times more element accesses.

Lists nodes are 5 to 9 times larger than vector "nodes" (which are just elements).  Forward iteration requires reading 3 to 5 times as much memory (element 16 bits and pointer 32 to 64 bits).

So the list solution reads/writes more memory!  Worse, it is sparser (with the back pointer), and it may not be arranged in a cache-friendly way in memory (vectors are contiguous; list nodes may be a mess in linear space) thus messing with cpu memory cache predictions and loads and etc.

List is very rarely faster than vector; you have to be inserting/deleting many times more often than you iterate over the list.

Finally vector uses exponential allocation with reserved unused space.  List allocates each time.  Calling new is slow, and often not much slower when you ask for bigger chunks than when you ask for smaller ones.  Growing a vector by 1 at a time 1000 times results in about 15 allocations (give or take); for list, 1000 allocations.

Body:
I am making a test program to measure time for storage of each container. The following is my code for the test.

#include <list>
#include <vector>
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;

void insert(list<short>& l, const short& value);
void insert(vector<short>& v, const short& value);
void insert(short arr[], int& logicalSize, const int& physicalSize, const short& value);

int main() {
    clock_t start, end;
    srand(time(nullptr));

    const int SIZE = 50000;
    const short RANGE = 10000;
    list<short> l;
    vector<short> v;
    short* arr = new short[SIZE];
    int logicalSize = 0;

    // array
    start = clock();
    cout << "Array storage time test...";
    for (int i = 0; i < SIZE; i++) {
        try {
            insert(arr, logicalSize, SIZE, (short)(rand() % (2 * RANGE + 1) - RANGE));
        } catch (string s) {
            cout << s << endl;
            system("pause");
            exit(-1);
        }
    }
    end = clock();
    cout << "Time: " << difftime(end, start) << endl << endl;

    // list
    cout << "List storage time test...";
    start = clock();
    for (int i = 0; i < SIZE; i++) {
        insert(l, (short)(rand() % (2 * RANGE + 1) - RANGE));
    }
    end = clock();
    cout << "Time: " << difftime(end, start) << endl << endl;

    // vector
    cout << "Vector storage time test...";
    start = clock();
    for (int i = 0; i < SIZE; i++) {
        insert(v, (short)(rand() % (2 * RANGE + 1) - RANGE));
    }
    end = clock();
    cout << "Time: " << difftime(end, start) << endl << endl;

    delete[] arr;
    system("pause");
    return 0;
}

void insert(list<short>& l, const short& value) {
    for (auto it = l.begin(); it != l.end(); it++) {
        if (value < *it) {
            l.insert(it, value);
            return;
        }
    }
    l.push_back(value);
}

void insert(vector<short>& v, const short& value) {
    for (auto it = v.begin(); it != v.end(); it++) {
        if (value < *it) {
            v.insert(it, value);
            return;
        }
    }
    v.push_back(value);
}

void insert(short arr[], int& logicalSize, const int& physicalSize, const short& value) {
    if (logicalSize == physicalSize) throw string("No spaces in array.");
    for (int i = 0; i < logicalSize; i++) {
        if (value < arr[i]) {
            for (int j = logicalSize - 1; j >= i; j--) {
                arr[j + 1] = arr[j];
            }
            arr[i] = value;
            logicalSize++;
            return;
        }
    }
    arr[logicalSize] = value;
    logicalSize++;
}

However, when I execute the code, the result seems a little different from the theory. The list should be fastest, but the result said that insertion in the list is slowest. Can you tell me why?


问:
How to perform case-insensitive sorting array of string in JavaScript?
I have an array of strings I need to sort in JavaScript, but in a case-insensitive way. How to perform this?</p>

答:
I wrapped the top answer in a polyfill so I can call .sortIgnoreCase() on string arrays</p>

```<code>// Array.sortIgnoreCase() polyfill
if (!Array.prototype.sortIgnoreCase) {
    Array.prototype.sortIgnoreCase = function () {
        return this.sort(function (a, b) {
            return a.toLowerCase().localeCompare(b.toLowerCase());
        });
    };
}
</code>```

Body:
I wrapped the top answer in a polyfill so I can call .sortIgnoreCase() on string arrays

// Array.sortIgnoreCase() polyfill
if (!Array.prototype.sortIgnoreCase) {
    Array.prototype.sortIgnoreCase = function () {
        return this.sort(function (a, b) {
            return a.toLowerCase().localeCompare(b.toLowerCase());
        });
    };
}


问:
Adwords API report options
I'm looking into the Adwords API and I'm having trouble to find how to get reports without parsing them after downloading.

I spent significant amount of time but the only real option for getting keywords data between dates is with reports, but looks like you have to download and then parse them, am I right?

Thanks in advance

答:
I am pretty sure there isn't a way to access reports in a true "API" manner, you're basically stuck parsing a CSV.  One trick though, is that now you can at least get the response as string, rather than writing/reading from the local filesystem with:</p>

```<code>                $response = $reportDownloadResult->getAsString();
</code>```

Title: Adwords API report options

Body:
I am pretty sure there isn't a way to access reports in a true "API" manner, you're basically stuck parsing a CSV.  One trick though, is that now you can at least get the response as string, rather than writing/reading from the local filesystem with:

                $response = $reportDownloadResult->getAsString();


问:
Show/Hide events on fullcalendar using javascript
I'm making a religious calendar for a project that shows different events for all major religions. I'm using full calendar, and I have a "religion key" at the top of the calendar, and I want to make it so that when I click, for example, Jewish, it will hide all religious events/holidays on the calendar that don't pertain to the Jewish faith. I'm having some trouble. My thinking was that I would set the ".fc-event" class in css to display:none" and then have a class called .show that would be display:block. and toggle that class / remove that class when the user clicks the menu item that pertains to the holiday. Is there a better / easier way to do this? would love some guidance/tips/help :) thank you.

Here is my code for the calendar js (using made up dates obviously):

```<code>events: [
        {
            title: 'xmas',
            start: '2017-03-19',
            className: 'catholic show',
            description: 'blablablablabla'
        },
        {
            title: 'Hanukkah',
            start: '2017-03-19',
            className: 'jewish show',
            description: 'blablablabla'
        },
        {
            title: 'Hindu Holiday',
            start: '2017-03-24',
            end: '2017-03-27',
            className: 'hindu show',
            description: 'blablablabla'
        }
    ]
});

$('.calendar-nav a').each(function() {

    $(this).on('click', function(e) {
        e.preventDefault();

        var x = $(this).attr('rel');

        $('.fc-event-container').each(function() {

            $(this).removeClass('show');

            if($(this).hasClass(x)) {

                $(this).addClass('show');
            }
        });
    })
});

$('.show-all a').on('click', function() {
    $('.fc-event-container').each(function() {
        if(!$(this).hasClass('show')) {
            $(this).toggleClass('show');
        }
    });
});
});
</code>```

And the php code for the calendar and calendar-key:

```<code><nav class="calendar-nav">
<ul class="menu">
    <li class="christianity-text"><a href="#" rel="christian">><img src="/images/calendar/christianity.png" />CHRISTIAN</a>
        <ul class="sub-menu">
            <li><a href="#">Catholic</a></li>
            <li><a href="#">Protestant</a></li>
            <li><a href="#">Coptic</a></li>
            <li><a href="#">Mormon</a></li>
            <li><a href="#">Neo</a></li>
            <li><a href="#">Anglican</a></li>
            <li><a href="#">Celtic</a></li>
            <li><a href="#">Jehova's Witness</a></li>
        </ul>
    </li>
    <li class="buddhist-text"><a  href="#" rel="buddhist"><img src="/images/calendar/buddhism.png" />BUDDHIST</a></li>
    <li class="hindu-text"><a  href="#" rel="hindu"><img src="/images/calendar/hindu.png" />HINDU</a></li>
    <li class="jewish-text"><a  href="#" rel="jewish"><img src="/images/calendar/jewish.png" />JEWISH</a></li>
    <li class="islam-text"><a  href="#" rel="islam"><img src="/images/calendar/islam.png" />ISLAM</a></li>
    <li class="sikh-text"><a  href="#" rel="sikh"><img src="/images/calendar/sikh.png" />SIKH</a></li>

    <li class="pagan-text"><a  href="#" rel="pagan"><img src="/images/calendar/pagan.png" />PAGAN</a></li>
    <li class="wiccan-text"><a  href="#" rel="wiccan"><img src="/images/calendar/wiccan.png" />WICCAN</a></li>
    <li class="other-text"><a  href="#" rel="other"><img src="/images/calendar/other.png" />OTHER</a></li>
    <li class="all-text"><a href="#" rel="all">ALL</a></li>
</ul>
</nav>

<div id='calendar'></div>
</code>```

答:
You can do the following,

A. You can add/remove a class that has display:none and display:block

$(this).addClass('hideClass'); and $(this).addClass('showClass');

css

```<code>hideClass
{ display:none; }

showClass
{ display:block; }
</code>```

B. you can toggle hide and show

$(this).hide(); and $(this).show();

C. You can change the css property itself via using css variables. This is the better option, especially when you are redrawing your elements asynchronously.. the changes with the css stay.

be warned that chrome does not support this though, which leads us to...

D. Appending CSS files to override class

you can add a .css file with classes that have !important to override your current settings

$("head").append("<link id='yournewcss' href='hi-res.css' type='text/css' rel='stylesheet' />");

This is to ensure that if you redraw the page asynchronously, the property stays.

Body:
I'm making a religious calendar for a project that shows different events for all major religions. I'm using full calendar, and I have a "religion key" at the top of the calendar, and I want to make it so that when I click, for example, Jewish, it will hide all religious events/holidays on the calendar that don't pertain to the Jewish faith. I'm having some trouble. My thinking was that I would set the ".fc-event" class in css to display:none" and then have a class called .show that would be display:block. and toggle that class / remove that class when the user clicks the menu item that pertains to the holiday. Is there a better / easier way to do this? would love some guidance/tips/help :) thank you.

Here is my code for the calendar js (using made up dates obviously):

events: [
        {
            title: 'xmas',
            start: '2017-03-19',
            className: 'catholic show',
            description: 'blablablablabla'
        },
        {
            title: 'Hanukkah',
            start: '2017-03-19',
            className: 'jewish show',
            description: 'blablablabla'
        },
        {
            title: 'Hindu Holiday',
            start: '2017-03-24',
            end: '2017-03-27',
            className: 'hindu show',
            description: 'blablablabla'
        }
    ]
});

$('.calendar-nav a').each(function() {

    $(this).on('click', function(e) {
        e.preventDefault();

        var x = $(this).attr('rel');

        $('.fc-event-container').each(function() {

            $(this).removeClass('show');

            if($(this).hasClass(x)) {

                $(this).addClass('show');
            }
        });
    })
});

$('.show-all a').on('click', function() {
    $('.fc-event-container').each(function() {
        if(!$(this).hasClass('show')) {
            $(this).toggleClass('show');
        }
    });
});
});

And the php code for the calendar and calendar-key:

>CHRISTIAN

Catholic

Protestant

Coptic

Mormon

Neo

Anglican

Celtic

Jehova's Witness

BUDDHIST

HINDU

JEWISH

ISLAM

SIKH

PAGAN

WICCAN

OTHER

ALL

Body:
You can do the following,

A. You can add/remove a class that has display:none and display:block

$(this).addClass('hideClass'); and $(this).addClass('showClass');

css

hideClass
{ display:none; }

showClass
{ display:block; }

B. you can toggle hide and show

$(this).hide(); and $(this).show();

C. You can change the css property itself via using css variables. This is the better option, especially when you are redrawing your elements asynchronously.. the changes with the css stay.

be warned that chrome does not support this though, which leads us to...

D. Appending CSS files to override class

you can add a .css file with classes that have !important to override your current settings

$("head").append("<link id='yournewcss' href='hi-res.css' type='text/css' rel='stylesheet' />");

This is to ensure that if you redraw the page asynchronously, the property stays.


问:
Google Maps V3 2017 still slow when adding markers/circles
Google Maps API on Android still has an issue where it takes a long time to load many markers/circles. In my case I am drawing 130+ circles with Lat/Lng to the Google Map. This process takes 20s to complete. Here is the code for adding the circles which is called after @Override public void onMapLoaded:

```<code>List<Crime> crimes = mCrimeManager.getListOfCrimes();
Log.d("CRIME SIZE TAG", "   " + crimes.size());

for(Crime crime:crimes)
{
    if(!(getLocationOfCrime(crime) == null))
    {
        Circle circle = googleMap.addCircle(new CircleOptions()
               .clickable(true)
                .radius(5)
                .center(getLocationOfCrime(crime)));
        circle.setTag(crime);
</code>```

I know that this is the issue because removing this code causes everything to run smoothly with no delay.

I have looked at multiple questions in the past but most are using clustering or loading only with a certain range which can not be applied to my case. I have tried running this on AsyncTask with a runOnUiThread(); in doInBackground(); but that still yields same performance.

答:
Okay guys here is the solution. It turns out adding the markers is not processor intensive. Geolocating is the issue. If you are running into this issue it is because you are geolocating on the main thread. The way I fixed my problem was putting geolocation calculations on AsyncTask (doInBackground();) then on onPostExecute adding the markers.

Still there is an issue where geolocation takes time(UI running smoothly but no markers), but this is a Google Maps API issue. I sorta fixed this by doing the geolocation once at startup then storing everything into SQLiteDataBase then reading in from there after each time.

Thanks

Body:
Google Maps API on Android still has an issue where it takes a long time to load many markers/circles. In my case I am drawing 130+ circles with Lat/Lng to the Google Map. This process takes 20s to complete. Here is the code for adding the circles which is called after @Override public void onMapLoaded:

List<Crime> crimes = mCrimeManager.getListOfCrimes();
Log.d("CRIME SIZE TAG", "   " + crimes.size());

for(Crime crime:crimes)
{
    if(!(getLocationOfCrime(crime) == null))
    {
        Circle circle = googleMap.addCircle(new CircleOptions()
               .clickable(true)
                .radius(5)
                .center(getLocationOfCrime(crime)));
        circle.setTag(crime);

I know that this is the issue because removing this code causes everything to run smoothly with no delay.

I have looked at multiple questions in the past but most are using clustering or loading only with a certain range which can not be applied to my case. I have tried running this on AsyncTask with a runOnUiThread(); in doInBackground(); but that still yields same performance.


问:
Spark DataFrame nulls to Dataset
When importing data from a MS SQL database, there is the potential for null values. In Spark, DataFrames are able to handle the null values. But when I try to convert the DataFrame to a strongly typed Dataset, I receive encoder errors.

Here's a simple example:

```<code>case class optionTest(var a: Option[Int], var b: Option[Int])

object testObject {
  def main(args: Array[String]): Unit = {
    import spark.implicits._
    val df = spark.sparkContext.parallelize(Seq(input)).toDF()

    val df2 = Seq((1, 3), (3, Option(null)))
                 .toDF("a", "b")
                 .as[optionTest]

    df2.show()
  }
}
</code>```

Here is the error for this case:

```<code>No Encoder found for Any
- field (class: "java.lang.Object", name: "_2")
- root class: "scala.Tuple2"
java.lang.UnsupportedOperationException: No Encoder found for Any
- field (class: "java.lang.Object", name: "_2")
- root class: "scala.Tuple2"
</code>```

What is the recommended approach to handle nullable values when creating a Dataset from a DataFrame?

答:
If you wan to use Option you have to use it for all records. You should also use None instead of Option(null):

```<code>Seq((1, Some(3)), (3, None)).toDF("a", "b").as[optionTest]
</code>```

Title: Spark DataFrame nulls to Dataset

Body:
When importing data from a MS SQL database, there is the potential for null values. In Spark, DataFrames are able to handle the null values. But when I try to convert the DataFrame to a strongly typed Dataset, I receive encoder errors.

Here's a simple example:

case class optionTest(var a: Option[Int], var b: Option[Int])

object testObject {
  def main(args: Array[String]): Unit = {
    import spark.implicits._
    val df = spark.sparkContext.parallelize(Seq(input)).toDF()

    val df2 = Seq((1, 3), (3, Option(null)))
                 .toDF("a", "b")
                 .as[optionTest]

    df2.show()
  }
}

Here is the error for this case:

No Encoder found for Any
- field (class: "java.lang.Object", name: "_2")
- root class: "scala.Tuple2"
java.lang.UnsupportedOperationException: No Encoder found for Any
- field (class: "java.lang.Object", name: "_2")
- root class: "scala.Tuple2"

What is the recommended approach to handle nullable values when creating a Dataset from a DataFrame?

Body:
If you wan to use Option you have to use it for all records. You should also use None instead of Option(null):

Seq((1, Some(3)), (3, None)).toDF("a", "b").as[optionTest]