问:
Symfony 3 - subform and element name
I want to create form with composition pattern like this:
https://symfony.com/doc/current/form/inherit_data_option.html

I use Symfony 3.

and it's working. I have each element like single object and add this.

but finally my form elements names have name like

```<code>form[subform][element]
</code>```

How to make flat structure without subform in name attribute?

```<code>use AppBundle\Base\Form\NickType;
use AppBundle\Base\Form\MailType;
use AppBundle\Base\Form\PassType;
use AppBundle\Base\Form\UserType;

class RegisterType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('nick', NickType::class)
            ->add('mail', MailType::class)
            ->add('password', PassType::class)
            ->add('repeat_password', PassType::class)
(etc...)
</code>```

and SINGLE ELEMENT

```<code>class NickType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('nick', TextType::class);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'inherit_data' => true
        ));
    }

}
</code>```

答:
You don't need to define a NickType if it only inherits a TextType. You can remove NickType, MailType, etc.

You can just do:

```<code>class RegisterType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('nick', TextType::class)
        ;
(etc...)
</code>```

If you want to reuse a form field, you have to create a Custom Form Field Type:

```<code>class NickType extends AbstractType
{
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            //...
        ));
    }

    public function getParent()
    {
        return TextType::class;
    }
}
</code>```

You can remove form[] from the element name, but removing this is not really recommended, because when you read the request to populate form data you can identify the form by its form name. (via)

You can set the name of the root form to empty, then your field name
  will be just form. Do so via

```<code>// the first argument to createNamedBuilder() is the name
$form = $this->get('form.factory')->createNamedBuilder(null, 'form', $defaultData)
    ->add('from', 'date', array(
        'required' => false,
        'widget' => 'single_text',
        'format' => 'dd.MM.yyyy'
    ));
</code>```

(via)

Title: Symfony 3 - subform and element name

Body:
I want to create form with composition pattern like this:
https://symfony.com/doc/current/form/inherit_data_option.html

I use Symfony 3.

and it's working. I have each element like single object and add this.

but finally my form elements names have name like

form[subform][element]

How to make flat structure without subform in name attribute?

use AppBundle\Base\Form\NickType;
use AppBundle\Base\Form\MailType;
use AppBundle\Base\Form\PassType;
use AppBundle\Base\Form\UserType;

class RegisterType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('nick', NickType::class)
            ->add('mail', MailType::class)
            ->add('password', PassType::class)
            ->add('repeat_password', PassType::class)
(etc...)

and SINGLE ELEMENT

class NickType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('nick', TextType::class);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'inherit_data' => true
        ));
    }

}

Body:
You don't need to define a NickType if it only inherits a TextType. You can remove NickType, MailType, etc.

You can just do:

class RegisterType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('nick', TextType::class)
        ;
(etc...)

If you want to reuse a form field, you have to create a Custom Form Field Type:

class NickType extends AbstractType
{
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            //...
        ));
    }

    public function getParent()
    {
        return TextType::class;
    }
}

You can remove form[] from the element name, but removing this is not really recommended, because when you read the request to populate form data you can identify the form by its form name. (via)

You can set the name of the root form to empty, then your field name
  will be just form. Do so via

// the first argument to createNamedBuilder() is the name
$form = $this->get('form.factory')->createNamedBuilder(null, 'form', $defaultData)
    ->add('from', 'date', array(
        'required' => false,
        'widget' => 'single_text',
        'format' => 'dd.MM.yyyy'
    ));

(via)


来源: stackexchange

问:
Keras Input add dimension autoly error
I am a new hand of using Keras. After searching without results. Please Please save me!
Here is my problem:

```<code>print(input_shape)

X_input = Input(input_shape)

print(X_input)
</code>```

result in

```<code>(600, 64, 64, 3)
Tensor("input_5:0", shape=(?, 600, 64, 64, 3), dtype=float32)
</code>```

It add one dimension autoly and error

```<code>ValueError: Input 0 is incompatible with layer conv0: expected ndim=4, found ndim=5
</code>```

答:
Your problem lies in the fact that in keras a first dimension is connected to a number of samples (I guess it's 600 in your case) and it's skipped while defining an input shape. So try:

```<code>X_input = Input(input_shape[1:])
</code>```

in order to skip a sample dimension.

ContentLicense: CC BY-SA 3.0

Title: Keras Input add dimension autoly error

Body:
I am a new hand of using Keras. After searching without results. Please Please save me!
Here is my problem:

print(input_shape)

X_input = Input(input_shape)

print(X_input)

result in

(600, 64, 64, 3)
Tensor("input_5:0", shape=(?, 600, 64, 64, 3), dtype=float32)

It add one dimension autoly and error

ValueError: Input 0 is incompatible with layer conv0: expected ndim=4, found ndim=5

Body:
Your problem lies in the fact that in keras a first dimension is connected to a number of samples (I guess it's 600 in your case) and it's skipped while defining an input shape. So try:

X_input = Input(input_shape[1:])

in order to skip a sample dimension.


问:
C# + WPF : how should I do proper checks/guards/casts when accessing control values?
This is probably pretty basic, but I'm just picking up C# after many years working with other languages, and I've unfortunately grown used to loose and dynamic typing.  Now, in building a WPF form with a lot of checkboxes, I notice that my code to do simple things like determine whether a checkbox is checked is actually quite complicated due to the need to check for nulls and cast the results.  I end up with helper functions like:

```<code>    private bool isChecked(CheckBox control) {
        return control != null && control.IsChecked != null && control.IsChecked.HasValue && (bool)control.IsChecked;
    }
</code>```

so that in my logic code, I can just do

```<code>    if (isChecked(opticsCheckBox))
    {
        // whatever I need to do if opticsCheckBox is checked
    }
</code>```

Is this the normal way of doing things in C# (with WPF), or am I missing something simple?  Basically I'm finding the nested layers of conditionals to check every object for null all the time to be a warning sign of bad code (and the fact that I could forget a check).  Not sure what I should be doing though.

Should I be using try ... catch everywhere even though the control not being present or checked isn't really an exceptional condition?  That seems to me like it would end up being just as cluttered.

Another example to clarify:
When I would like to write something like:

```<code>    maxWeight = (int)maxWeightComboBox.SelectedItem;
</code>```

I find myself instead writing:

```<code>    if (maxWeightComboBox != null && maxWeightComboBox.SelectedItem != null)
    {
        ComboBoxItem item = (ComboBoxItem)maxWeightComboBox.SelectedItem;
        maxWeight = Int32.Parse(item.Content.ToString());
    }
</code>```

答:
WPF provides such features as notifications on property changes, dependency propeties, and binding.
So the good practice in WPF is to use PresentationModel-View pattern or MVC pattern instead of direct access to controls.

Your presentation model (or contoller) have to handle all business logic, and view just reflect actual state of model.

In your case model looks like:

```<code>public class SampleModel : ObservableObject
{
    private bool? _isFirstChecked;
    public bool? IsFirstChecked
    {
        get
        {
            return this._isFirstChecked;
        }
        set
        {
            if (this._isFirstChecked != value)
            {
                this._isFirstChecked = value;
                this.OnPropertyChanged("IsFirstChecked");
            }
        }
    }

    private int _maxWeight;
    public int MaxWeight
    {
        get
        {
            return this._maxWeight;
        }
        set
        {
            if (this._maxWeight != value)
            {
                this._maxWeight = value;
                this.OnPropertyChanged("MaxWeight");
            }
        }
    }

    public IEnumerable<int> ComboBoxItems
    {
        get
        {
            yield return 123;
            yield return 567;
            yield return 999;
            yield return 567;
            yield return 1999;
            yield return 5767;
            yield return 9990;
        }
    }
}
</code>```

As we have to notify view with property changed event, we add Observable class, which implement this logic:

```<code>public class ObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        var safePropertyChanged = this.PropertyChanged;
        if (safePropertyChanged != null)
        {
            safePropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
</code>```

So, now we have presentation model with declaration of necessary properties, let's see at view:

```<code><Window x:Class="Test.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:self ="clr-namespace:Test"
    Title="MainWindow"
    Height="350" Width="525">
<Window.Resources>
    <self:NullableBoolToStringConvreter x:Key="nullableBoolToStringConverter" />
</Window.Resources>
<Grid>
    <StackPanel>
        <StackPanel Orientation="Horizontal">
            <Label VerticalAlignment="Center">IsFirstChecked:</Label>
            <CheckBox VerticalAlignment="Center"
                      IsChecked="{Binding Path=IsFirstChecked}" />
        </StackPanel>

        <StackPanel Orientation="Horizontal">
            <Label VerticalAlignment="Center">Max Weight:</Label>
            <ComboBox ItemsSource="{Binding Path=ComboBoxItems}"
                      VerticalAlignment="Center"
                      SelectedValue="{Binding Path=MaxWeight}">
            </ComboBox>
        </StackPanel>

        <TextBox Text="{Binding Path=MaxWeight}" />
        <TextBox Text="{Binding Path=IsFirstChecked, Converter={StaticResource nullableBoolToStringConverter}}"/>

        <Button Click="Button_Click" Content="Reset combo box to 999 and checkbox to null"/>
    </StackPanel>
</Grid>
</code>```

Also we have to modify this xaml code behind:

```<code>public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        var model = new SampleModel();
        model.MaxWeight = 5767;

        this.Model = model;
    }

    public SampleModel Model
    {
        get
        {
            return (SampleModel)this.DataContext;
        }
        set
        {
            this.DataContext = value;
        }
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        this.Model.MaxWeight = 999;
        this.Model.IsFirstChecked = null;
    }
}
</code>```

As you can see we create SampleModel instance at MainWindow constructor, set up its properties and set model instance as DataContext of view.

After DataContext changed, WPF internal mechanizm starts binding process. For example, for combobox control it extracts model property ComboBoxItems and creates item containers. Then extracts property MaxValue and bind it to SelectedValue, i.e. combobox selection will point at value '5767'.

In demostration purposes I placed two text boxes, which display actual value of "MaxWeight" and "IsFirstChecked" properties. Default binding implementation shows empty strings on null values, so we have to add appropriate converter:

```<code>public class NullableBoolToStringConvreter : IValueConverter
{
    private static readonly string _NullString = "Null";

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value == null ? NullableBoolToStringConvreter._NullString : value.ToString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

You can test application and ensures that changes of UI controls state automatically reflects in model. On the other hand, clicking on the button will reset model properties to defined values and UI immediatly reacts on it.

So with WPF you don't need access to controls. XAML and InitializeComponent() guarantee you that all controls are created.

As for checking:

```<code>control.IsChecked.HasValue && (bool)control.IsChecked
</code>```

as was mentioned you can use expression

```<code>model.IsFirstChecked ?? false
</code>```

or extension method:

```<code>public static class BooleanNullableExtensions
{
    public static bool IsTrue(this Nullable<bool> value)
    {
        return value.HasValue && value.Value;
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
This is probably pretty basic, but I'm just picking up C# after many years working with other languages, and I've unfortunately grown used to loose and dynamic typing.  Now, in building a WPF form with a lot of checkboxes, I notice that my code to do simple things like determine whether a checkbox is checked is actually quite complicated due to the need to check for nulls and cast the results.  I end up with helper functions like:

    private bool isChecked(CheckBox control) {
        return control != null && control.IsChecked != null && control.IsChecked.HasValue && (bool)control.IsChecked;
    }

so that in my logic code, I can just do

    if (isChecked(opticsCheckBox))
    {
        // whatever I need to do if opticsCheckBox is checked
    }

Is this the normal way of doing things in C# (with WPF), or am I missing something simple?  Basically I'm finding the nested layers of conditionals to check every object for null all the time to be a warning sign of bad code (and the fact that I could forget a check).  Not sure what I should be doing though.

Should I be using try ... catch everywhere even though the control not being present or checked isn't really an exceptional condition?  That seems to me like it would end up being just as cluttered.

Another example to clarify:
When I would like to write something like:

    maxWeight = (int)maxWeightComboBox.SelectedItem;

I find myself instead writing:

    if (maxWeightComboBox != null && maxWeightComboBox.SelectedItem != null)
    {
        ComboBoxItem item = (ComboBoxItem)maxWeightComboBox.SelectedItem;
        maxWeight = Int32.Parse(item.Content.ToString());
    }

Body:
WPF provides such features as notifications on property changes, dependency propeties, and binding.
So the good practice in WPF is to use PresentationModel-View pattern or MVC pattern instead of direct access to controls.

Your presentation model (or contoller) have to handle all business logic, and view just reflect actual state of model.

In your case model looks like:

public class SampleModel : ObservableObject
{
    private bool? _isFirstChecked;
    public bool? IsFirstChecked
    {
        get
        {
            return this._isFirstChecked;
        }
        set
        {
            if (this._isFirstChecked != value)
            {
                this._isFirstChecked = value;
                this.OnPropertyChanged("IsFirstChecked");
            }
        }
    }

    private int _maxWeight;
    public int MaxWeight
    {
        get
        {
            return this._maxWeight;
        }
        set
        {
            if (this._maxWeight != value)
            {
                this._maxWeight = value;
                this.OnPropertyChanged("MaxWeight");
            }
        }
    }

    public IEnumerable<int> ComboBoxItems
    {
        get
        {
            yield return 123;
            yield return 567;
            yield return 999;
            yield return 567;
            yield return 1999;
            yield return 5767;
            yield return 9990;
        }
    }
}

As we have to notify view with property changed event, we add Observable class, which implement this logic:

public class ObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        var safePropertyChanged = this.PropertyChanged;
        if (safePropertyChanged != null)
        {
            safePropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

So, now we have presentation model with declaration of necessary properties, let's see at view:

<Window x:Class="Test.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:self ="clr-namespace:Test"
    Title="MainWindow"
    Height="350" Width="525">
<Window.Resources>
    <self:NullableBoolToStringConvreter x:Key="nullableBoolToStringConverter" />
</Window.Resources>
<Grid>
    <StackPanel>
        <StackPanel Orientation="Horizontal">
            <Label VerticalAlignment="Center">IsFirstChecked:</Label>
            <CheckBox VerticalAlignment="Center"
                      IsChecked="{Binding Path=IsFirstChecked}" />
        </StackPanel>

        <StackPanel Orientation="Horizontal">
            <Label VerticalAlignment="Center">Max Weight:</Label>
            <ComboBox ItemsSource="{Binding Path=ComboBoxItems}"
                      VerticalAlignment="Center"
                      SelectedValue="{Binding Path=MaxWeight}">
            </ComboBox>
        </StackPanel>

        <TextBox Text="{Binding Path=MaxWeight}" />
        <TextBox Text="{Binding Path=IsFirstChecked, Converter={StaticResource nullableBoolToStringConverter}}"/>

        <Button Click="Button_Click" Content="Reset combo box to 999 and checkbox to null"/>
    </StackPanel>
</Grid>

Also we have to modify this xaml code behind:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        var model = new SampleModel();
        model.MaxWeight = 5767;

        this.Model = model;
    }

    public SampleModel Model
    {
        get
        {
            return (SampleModel)this.DataContext;
        }
        set
        {
            this.DataContext = value;
        }
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        this.Model.MaxWeight = 999;
        this.Model.IsFirstChecked = null;
    }
}

As you can see we create SampleModel instance at MainWindow constructor, set up its properties and set model instance as DataContext of view.

After DataContext changed, WPF internal mechanizm starts binding process. For example, for combobox control it extracts model property ComboBoxItems and creates item containers. Then extracts property MaxValue and bind it to SelectedValue, i.e. combobox selection will point at value '5767'.

In demostration purposes I placed two text boxes, which display actual value of "MaxWeight" and "IsFirstChecked" properties. Default binding implementation shows empty strings on null values, so we have to add appropriate converter:

public class NullableBoolToStringConvreter : IValueConverter
{
    private static readonly string _NullString = "Null";

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value == null ? NullableBoolToStringConvreter._NullString : value.ToString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

You can test application and ensures that changes of UI controls state automatically reflects in model. On the other hand, clicking on the button will reset model properties to defined values and UI immediatly reacts on it.

So with WPF you don't need access to controls. XAML and InitializeComponent() guarantee you that all controls are created.

As for checking:

control.IsChecked.HasValue && (bool)control.IsChecked

as was mentioned you can use expression

model.IsFirstChecked ?? false

or extension method:

public static class BooleanNullableExtensions
{
    public static bool IsTrue(this Nullable<bool> value)
    {
        return value.HasValue && value.Value;
    }
}


问:
Getting Error With GROUP BY when Converting Query to Dynamic SQL
I'm trying to convert the following query to dynamic SQL to allow for variations:

```<code>UPDATE T
SET SumCount = J.SUM
FROM #temp T
    JOIN (SELECT Count_99221 + COUNT_99222 + Count_99223 [SUM], t2.userID
          FROM #temp t2
          GROUP BY t2.userID, Count_99221 + COUNT_99222 + Count_99223
          ) J ON T.userID = J.UserID
</code>```

This is what I have for the Dynamic SQL:

```<code>DECLARE @sql3 nvarchar(2000) =
'UPDATE T ' +
'SET SumCount = J.SumOfColumns ' +
'FROM #temp T ' +
'JOIN (SELECT ' + @columnSumString + ' [SumOfColumns], t2.userID ' +
'FROM #temp t2 ' +
'GROUP BY t2.userID, ' + @columnSumString +
' ) J ON T.userID = J.UserID'

EXEC sp_executesql @sql3
</code>```

I am receiving the following error only when I run the query as Dynamic SQL:

Each GROUP BY expression must contain at least one column that is not
  an outer reference.

Can somebody help explain why this is happening? I am new to Dynamic SQL so I'm not privy to any limitations for running queries this way.

Thank you in advance.

EDIT:

The variable @columnString is a string made by concatenating several other column names, created in the following way:

```<code>DECLARE @Cursor Cursor
DECLARE @code varchar(20)
DECLARE @ID INT

SET @cptCursor = CURSOR FOR
SELECT * FROM dbo.Split(@UserInput,CHAR(44))

OPEN @cptCursor
FETCH NEXT FROM @cptCursor INTO @ID, @code
WHILE @@FETCH_STATUS = 0
BEGIN

DECLARE @colName varchar(50) = 'Count_' + cast(@code as varchar(10))
DECLARE @sql nvarchar(50) = 'ALTER TABLE #temp ADD ' + @colName + ' int'
EXEC sp_executesql @sql

--Code that adds values to each column that is created.....

SET @columnSumString = @colName + ' + ' + @columnSumString
--SET @columnSumString = @code + ' + ' + @columnSumString

FETCH NEXT FROM @cptCursor INTO @ID, @code
END
CLOSE @Cursor
DEALLOCATE @Cursor

SET @columnSumString = SUBSTRING(@columnSumString,1,LEN(@columnSumString)-2)
SELECT @columnSumString
</code>```

The user input is a comma separated string. "Count_99221 + COUNT_99222 + Count_99223" is just one example of columns created from the user input "99221, 99222, 99223".

I also realized I was concatenating the @code variable into @columnSumString instead of @colName. Now when I run the query I don't get the error (even though I don't understand how the above error message relates to that mistake) but every value of SumCount is NULL.

答:
IMHO you must re-write your query as follow:

```<code>UPDATE #temp
SET SumCount =
    (SELECT Count_99221 + COUNT_99222 + Count_99223
    FROM #temp t2
    WHERE t2.userID = #temp.userID)
</code>```

So the dynamic SQL will become:

```<code>DECLARE @columnString varchar(200)
SET @columnString = Count_99221 + COUNT_99222 + Count_99223

DECLARE @sql3 nvarchar(2000) =
N'UPDATE #temp ' +
'SET SumCount = (SELECT ' + @columnString +
    ' FROM #temp t2 WHERE t2.userID = #temp.userID)'

EXEC sp_executesql @sql3
</code>```

Body:
I'm trying to convert the following query to dynamic SQL to allow for variations:

UPDATE T
SET SumCount = J.SUM
FROM #temp T
    JOIN (SELECT Count_99221 + COUNT_99222 + Count_99223 [SUM], t2.userID
          FROM #temp t2
          GROUP BY t2.userID, Count_99221 + COUNT_99222 + Count_99223
          ) J ON T.userID = J.UserID

This is what I have for the Dynamic SQL:

DECLARE @sql3 nvarchar(2000) =
'UPDATE T ' +
'SET SumCount = J.SumOfColumns ' +
'FROM #temp T ' +
'JOIN (SELECT ' + @columnSumString + ' [SumOfColumns], t2.userID ' +
'FROM #temp t2 ' +
'GROUP BY t2.userID, ' + @columnSumString +
' ) J ON T.userID = J.UserID'

EXEC sp_executesql @sql3

I am receiving the following error only when I run the query as Dynamic SQL:

Each GROUP BY expression must contain at least one column that is not
  an outer reference.

Can somebody help explain why this is happening? I am new to Dynamic SQL so I'm not privy to any limitations for running queries this way.

Thank you in advance.

EDIT:

The variable @columnString is a string made by concatenating several other column names, created in the following way:

DECLARE @Cursor Cursor
DECLARE @code varchar(20)
DECLARE @ID INT

SET @cptCursor = CURSOR FOR
SELECT * FROM dbo.Split(@UserInput,CHAR(44))

OPEN @cptCursor
FETCH NEXT FROM @cptCursor INTO @ID, @code
WHILE @@FETCH_STATUS = 0
BEGIN

DECLARE @colName varchar(50) = 'Count_' + cast(@code as varchar(10))
DECLARE @sql nvarchar(50) = 'ALTER TABLE #temp ADD ' + @colName + ' int'
EXEC sp_executesql @sql

--Code that adds values to each column that is created.....

SET @columnSumString = @colName + ' + ' + @columnSumString
--SET @columnSumString = @code + ' + ' + @columnSumString

FETCH NEXT FROM @cptCursor INTO @ID, @code
END
CLOSE @Cursor
DEALLOCATE @Cursor

SET @columnSumString = SUBSTRING(@columnSumString,1,LEN(@columnSumString)-2)
SELECT @columnSumString

The user input is a comma separated string. "Count_99221 + COUNT_99222 + Count_99223" is just one example of columns created from the user input "99221, 99222, 99223".

I also realized I was concatenating the @code variable into @columnSumString instead of @colName. Now when I run the query I don't get the error (even though I don't understand how the above error message relates to that mistake) but every value of SumCount is NULL.

Body:
IMHO you must re-write your query as follow:

UPDATE #temp
SET SumCount =
    (SELECT Count_99221 + COUNT_99222 + Count_99223
    FROM #temp t2
    WHERE t2.userID = #temp.userID)

So the dynamic SQL will become:

DECLARE @columnString varchar(200)
SET @columnString = Count_99221 + COUNT_99222 + Count_99223

DECLARE @sql3 nvarchar(2000) =
N'UPDATE #temp ' +
'SET SumCount = (SELECT ' + @columnString +
    ' FROM #temp t2 WHERE t2.userID = #temp.userID)'

EXEC sp_executesql @sql3


问:
Output JSON from Bash script
So I have a bash script which outputs details on servers. The problem is that I need the output to be JSON. What is the best way to go about this? Here is the bash script:

```<code># Get hostname
hostname=`hostname -A` 2> /dev/null

# Get distro
distro=`python -c 'import platform ; print platform.linux_distribution()[0] + " " +        platform.linux_distribution()[1]'` 2> /dev/null

# Get uptime
if [ -f "/proc/uptime" ]; then
uptime=`cat /proc/uptime`
uptime=${uptime%%.*}
seconds=$(( uptime%60 ))
minutes=$(( uptime/60%60 ))
hours=$(( uptime/60/60%24 ))
days=$(( uptime/60/60/24 ))
uptime="$days days, $hours hours, $minutes minutes, $seconds seconds"
else
uptime=""
fi

echo $hostname
echo $distro
echo $uptime
</code>```

So the output I want is something like:

```<code>{"hostname":"server.domain.com", "distro":"CentOS 6.3", "uptime":"5 days, 22 hours, 1 minutes, 41 seconds"}
</code>```

Thanks.

答:
@Jimilian script was very helpful for me. I changed it a bit to send data to zabbix auto discovery

```<code>arr=()

while read x y;
do
    arr=("${arr[@]}" $x $y)
done

vars=(${arr[@]})
len=${#arr[@]}

printf "{\n"
printf "\t"data":[\n"

for (( i=0; i<len; i+=2 ))
do
     printf "\t{  "{#VAL1}":\"${vars[i]}\",\t"{#VAL2}":\"${vars[i+1]}\"  }"

    if [ $i -lt $((len-2)) ] ; then
        printf ",\n"
    fi
done
printf "\n"
printf "\t]\n"
printf "}\n"
echo
</code>```

Output:

```<code>    $ echo "A 1 B 2 C 3 D 4 E 5" | ./testjson.sh
{
    data:[
    {  {#VAL1}:"A", {#VAL2}:"1"  },
    {  {#VAL1}:"B", {#VAL2}:"2"  },
    {  {#VAL1}:"C", {#VAL2}:"3"  },
    {  {#VAL1}:"D", {#VAL2}:"4"  },
    {  {#VAL1}:"E", {#VAL2}:"5"  }
    ]
}
</code>```

Title: Output JSON from Bash script

Body:
So I have a bash script which outputs details on servers. The problem is that I need the output to be JSON. What is the best way to go about this? Here is the bash script:

# Get hostname
hostname=`hostname -A` 2> /dev/null

# Get distro
distro=`python -c 'import platform ; print platform.linux_distribution()[0] + " " +        platform.linux_distribution()[1]'` 2> /dev/null

# Get uptime
if [ -f "/proc/uptime" ]; then
uptime=`cat /proc/uptime`
uptime=${uptime%%.*}
seconds=$(( uptime%60 ))
minutes=$(( uptime/60%60 ))
hours=$(( uptime/60/60%24 ))
days=$(( uptime/60/60/24 ))
uptime="$days days, $hours hours, $minutes minutes, $seconds seconds"
else
uptime=""
fi

echo $hostname
echo $distro
echo $uptime

So the output I want is something like:

{"hostname":"server.domain.com", "distro":"CentOS 6.3", "uptime":"5 days, 22 hours, 1 minutes, 41 seconds"}

Thanks.

Body:
@Jimilian script was very helpful for me. I changed it a bit to send data to zabbix auto discovery

arr=()

while read x y;
do
    arr=("${arr[@]}" $x $y)
done

vars=(${arr[@]})
len=${#arr[@]}

printf "{\n"
printf "\t"data":[\n"

for (( i=0; i<len; i+=2 ))
do
     printf "\t{  "{#VAL1}":\"${vars[i]}\",\t"{#VAL2}":\"${vars[i+1]}\"  }"

    if [ $i -lt $((len-2)) ] ; then
        printf ",\n"
    fi
done
printf "\n"
printf "\t]\n"
printf "}\n"
echo

Output:

    $ echo "A 1 B 2 C 3 D 4 E 5" | ./testjson.sh
{
    data:[
    {  {#VAL1}:"A", {#VAL2}:"1"  },
    {  {#VAL1}:"B", {#VAL2}:"2"  },
    {  {#VAL1}:"C", {#VAL2}:"3"  },
    {  {#VAL1}:"D", {#VAL2}:"4"  },
    {  {#VAL1}:"E", {#VAL2}:"5"  }
    ]
}


问:
merge several images make android very slow
I wrote a code in java for android device, to merge some png images and create one bitmap and show in an Imageview. it works but after that the application will be too slow. what is the problem of my code? I think it is some thing like memory leak! is it right? and how to fix the code?</p>

```<code> public Drawable merge(Drawable a, String uri){
        Drawable[] layers = new Drawable[2];
        layers[0] = a;
        int imageResource = getResources().getIdentifier(uri, null, getPackageName());
        layers[1] = getResources().getDrawable(imageResource);
        LayerDrawable layerDrawable = new LayerDrawable(layers);
        return layerDrawable.mutate();

    }

 public void ShowImage(ArrayList<String> states) {

        img1.setImageDrawable(null);

        Drawable map = getResources().getDrawable(R.drawable.emptymap);

        int i = 1;
        for (String state : states) {
            String layerName = state;

            String uri = "drawable/"+layerName;
            try {
                map = merge(map ,uri);
            }
            catch(Exception e){}
        }

        img1.setImageDrawable(map);
}
</code>```

答:
LayerDrawable can be really slow for multiple high-res png drawables because it draws layers one by one in its draw() function:

```<code> @Override
    public void draw(Canvas canvas) {
        final ChildDrawable[] array = mLayerState.mChildren;
        final int N = mLayerState.mNumChildren;
        for (int i = 0; i < N; i++) {
            final Drawable dr = array[i].mDrawable;
            if (dr != null) {
                dr.draw(canvas);
            }
        }
    }
</code>```

It would be better to cache the emission of LayerDrawable into bitmap, and then use this bitmap.

```<code>Bitmap bmp = Bitmap.createBitmap(layeredDrawable.getIntrinsicWidth(),
layeredDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
layeredDrawable.setBounds(0, 0, layeredDrawable.getIntrinsicWidth(), layeredDrawable.getIntrinsicHeight());
layerDrawable.draw(new Canvas(bmp));
</code>```

Another thing to check would be the png drawables size after loading them from resources. They might be too large if positioned in wrong resource folder (For example, 500x500 png located in drawable/ folder after loading for density = 3 screen would constitute to be 1500x1500).

Body:
I wrote a code in java for android device, to merge some png images and create one bitmap and show in an Imageview. it works but after that the application will be too slow. what is the problem of my code? I think it is some thing like memory leak! is it right? and how to fix the code?

 public Drawable merge(Drawable a, String uri){
        Drawable[] layers = new Drawable[2];
        layers[0] = a;
        int imageResource = getResources().getIdentifier(uri, null, getPackageName());
        layers[1] = getResources().getDrawable(imageResource);
        LayerDrawable layerDrawable = new LayerDrawable(layers);
        return layerDrawable.mutate();

    }

 public void ShowImage(ArrayList<String> states) {

        img1.setImageDrawable(null);

        Drawable map = getResources().getDrawable(R.drawable.emptymap);

        int i = 1;
        for (String state : states) {
            String layerName = state;

            String uri = "drawable/"+layerName;
            try {
                map = merge(map ,uri);
            }
            catch(Exception e){}
        }

        img1.setImageDrawable(map);
}

Body:
LayerDrawable can be really slow for multiple high-res png drawables because it draws layers one by one in its draw() function:

 @Override
    public void draw(Canvas canvas) {
        final ChildDrawable[] array = mLayerState.mChildren;
        final int N = mLayerState.mNumChildren;
        for (int i = 0; i < N; i++) {
            final Drawable dr = array[i].mDrawable;
            if (dr != null) {
                dr.draw(canvas);
            }
        }
    }

It would be better to cache the emission of LayerDrawable into bitmap, and then use this bitmap.

Bitmap bmp = Bitmap.createBitmap(layeredDrawable.getIntrinsicWidth(),
layeredDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
layeredDrawable.setBounds(0, 0, layeredDrawable.getIntrinsicWidth(), layeredDrawable.getIntrinsicHeight());
layerDrawable.draw(new Canvas(bmp));

Another thing to check would be the png drawables size after loading them from resources. They might be too large if positioned in wrong resource folder (For example, 500x500 png located in drawable/ folder after loading for density = 3 screen would constitute to be 1500x1500).


问:
get all today's event where the date is stored as int
i need help on this code..Im a newbie on this thing

i would like to query a table to get all today's event where the date&time is stored as int (eg: 1510876800)

i tried it like this

```<code>$time = time();
$changedate=date("Y-m-d", strval($time));
$today=strtotime($changedate);

$sql = "SELECT * FROM " . $xoopsDB->prefix('extcal_event') . " WHERE event_start='$today' ORDER BY event_organisateur ASC";
</code>```

its not working because of the date in event_start have different time

How do i solve this ?

答:
You are comparing unix timestamps so that will only match on the exact same second of that specific day.

If you have a unix timestamp stored, first you need to convert it to a mysql datetime value and then you can get the date part of it:

```<code>... WHERE DATE(FROM_UNIXTIME(event_start)) = :today ...
</code>```

Here the value you bind to :today should have the Y-m-d format.

Note that I have used a placeholder for your variable as you should use prepared statements instead of injecting values directly into your query.

Body:
i need help on this code..Im a newbie on this thing

i would like to query a table to get all today's event where the date&time is stored as int (eg: 1510876800)

i tried it like this

$time = time();
$changedate=date("Y-m-d", strval($time));
$today=strtotime($changedate);

$sql = "SELECT * FROM " . $xoopsDB->prefix('extcal_event') . " WHERE event_start='$today' ORDER BY event_organisateur ASC";

its not working because of the date in event_start have different time

How do i solve this ?

Body:
You are comparing unix timestamps so that will only match on the exact same second of that specific day.

If you have a unix timestamp stored, first you need to convert it to a mysql datetime value and then you can get the date part of it:

... WHERE DATE(FROM_UNIXTIME(event_start)) = :today ...

Here the value you bind to :today should have the Y-m-d format.

Note that I have used a placeholder for your variable as you should use prepared statements instead of injecting values directly into your query.


问:
How to check in Java color of text when I have .html and .css files?
I have html with css and I want to check what is real color (and other visual text attributes) of specified text in html document. Can I do this with JSoup or must I look for some real-like html engine/processor? Speed of processing this operation is one of main factor.</p>

答: Though it is still in beta, the Cobra HTML parser has this capability.</p>


问:
Parsing the column values dynamically in the same table
I have a stored procedure which accepts the InputTable as a parameter:

```<code>create table inputTable (id int, ItemQty varchar(100))

insert into inputTable(id, ItemQty)
values (1, 'a,b,c'), (2, 'x,y'), (3, 'l,m,n,o,p'),
       (4, 'a,b'), (5, 'm')
</code>```

The stored procedure I have written is like this:

```<code>ALTER PROCEDURE [dbo].[dynamic_tbl]
    (@tablename VARCHAR(50))
AS
BEGIN
    /* To get the maximum value of ItemQty with comma's [IN THIS CASE IT IS 5 ] */
    DECLARE @ColumnCount int
    DECLARE @rowcount TABLE (Value int);

    INSERT INTO @rowcount
        EXEC('SELECT MAX(len(ITEMQTY) - len(replace(ITEMQTY, '','', '''')) +1) from '+@tablename);

    SELECT @ColumnCount = Value FROM @rowcount;

    DECLARE @ColumnName NVARCHAR(10)='qty_'
    DECLARE @count INT = 0

    IF (@ColumnCount > 0)
    BEGIN
        SET @count = @count + 1;

        WHILE (@ColumnCount >= @count)
        BEGIN
            SET @ColumnName = 'qty_'+CONVERT(varchar(2),@count)
            EXEC ('ALTER TABLE '+@tablename+' ADD ['+@ColumnName +'] varchar(20)')

            DECLARE @myvar AS VARCHAR(MAX)

            --set @myvar='update '+@tablename+' set '+@ColumnName +' =itemQty'

            /* HERE ACTUALLY I AM GETTING PROBLEM, BECAUSE I WANT TO PARSE VALUES IN THE RESPECTIVE COLUMNS. */
           EXEC(@myvar)

           /* HERE, I wish to write the Actual update statement DYNAMICALLY*/
           EXEC ('UPDATE '+@tablename+' set'+@ColumnName+'=     ' )
           SET @count = @count + 1;
       END
   END
END
</code>```

My input and (desired Output should be like below figures)

Output :

something like this in dynamic way to the code

```<code> declare @myvar as varchar(max)

                SET @MYVAR= 'update '+@tablename+ 'set' +@ColumnName+'=case  when '+@count+' = 1 then itemQty else  end'

                exec(@myvar)
</code>```

答:
The variant where ItemQty contains items only with one symbol 'a,b,c'

```<code>ALTER PROCEDURE [dbo].[dynamic_tbl] (@tablename varchar(50))
AS

CREATE TABLE #inputTable(id int,ItemQty varchar(100))

-- insert all the data into temp table
DECLARE @copyScript varchar(MAX)
SET @copyScript='SELECT id,ItemQty FROM '+@tablename

INSERT #inputTable(id,ItemQty)
EXEC(@copyScript)

-- add columns and update data in #inputTable
DECLARE @maxColNum int
SET @maxColNum=(SELECT (MAX(LEN(ItemQty))+1)/2 FROM #inputTable)

DECLARE @curColNum int
SET @curColNum=1

DECLARE @updateScript varchar(MAX)
DECLARE @alterScript varchar(MAX)

WHILE @curColNum<=@maxColNum
BEGIN

  -- add new column
  SET @alterScript='ALTER TABLE '+@tablename+' ADD qty'+CAST(@curColNum AS varchar(5))+' varchar(100)'

  --PRINT @alterScript
  EXEC(@alterScript)

  -- update data in new column
  SET @updateScript='UPDATE i
SET
  qty'+CAST(@curColNum AS varchar(5))+'=q.word
FROM '+@tablename+' i
JOIN
  (
    SELECT id,SUBSTRING(ItemQty,'+CAST((@curColNum-1)*2+1 AS varchar(5))+',1) word
    FROM #inputTable
    WHERE LEN(ItemQty)+1>='+CAST(@curColNum*2 AS varchar(5))+'
  ) q
ON i.ID=q.ID'

  --PRINT @updateScript
  EXEC(@updateScript)

  SET @curColNum=@curColNum+1
END

DROP TABLE #inputTable
GO

-- test
EXEC dynamic_tbl 'inputTable'

-- show result
SELECT *
FROM inputTable
</code>```

The next variant can have strings like 'a,bb,ccc'.

```<code>ALTER PROCEDURE [dbo].[dynamic_tbl] (@tablename varchar(50))
AS

CREATE TABLE #inputTable(id int,ItemQty varchar(100))

-- insert all the data into temp table
DECLARE @copyScript varchar(MAX)
SET @copyScript='SELECT id,ItemQty FROM '+@tablename

INSERT #inputTable(id,ItemQty)
EXEC(@copyScript)

-- get all the words for each ID and put them into #words
;WITH wordsCTE AS(
  SELECT
    id,
    ItemQty,
    1 StartPosition,
    CASE WHEN CHARINDEX(',',ItemQty)>0 THEN CHARINDEX(',',ItemQty) ELSE LEN(ItemQty)+1 END CommaPos,
    1 WordNum
  FROM #inputTable

  UNION ALL

  SELECT
    i.id,
    i.ItemQty,
    c.CommaPos+1 StartPosition,
    CASE WHEN CHARINDEX(',',c.ItemQty,c.CommaPos+1)>0 THEN CHARINDEX(',',c.ItemQty,c.CommaPos+1) ELSE LEN(c.ItemQty)+1 END CommaPos,
    c.WordNum+1
  FROM #inputTable i
  JOIN wordsCTE c ON i.id=c.id
  WHERE c.CommaPos<LEN(c.ItemQty)
)
--SELECT *,SUBSTRING(ItemQty,StartPosition,CommaPos-StartPosition) word
SELECT id,SUBSTRING(ItemQty,StartPosition,CommaPos-StartPosition) word,WordNum INTO #words
FROM wordsCTE
--ORDER BY id,word

-- add columns and update data in #inputTable
DECLARE @maxColNum int
SET @maxColNum=(SELECT MAX(WordNum) FROM #words)

DECLARE @curColNum int
SET @curColNum=1

DECLARE @updateScript varchar(MAX)
DECLARE @alterScript varchar(MAX)

WHILE @curColNum<=@maxColNum
BEGIN

  -- add new column
  SET @alterScript='ALTER TABLE '+@tablename+' ADD qty'+CAST(@curColNum AS varchar(5))+' varchar(100)'

  --PRINT @alterScript
  EXEC(@alterScript)

  -- update data in new column
  SET @updateScript='UPDATE i
SET
  qty'+CAST(@curColNum AS varchar(5))+'=q.word
FROM '+@tablename+' i
JOIN
  (
    SELECT *
    FROM #words
    WHERE WordNum='+CAST(@curColNum AS varchar(5))+'
  ) q
ON i.ID=q.ID'

  --PRINT @updateScript
  EXEC(@updateScript)

  SET @curColNum=@curColNum+1
END

DROP TABLE #words
DROP TABLE #inputTable
GO

-- test
EXEC dynamic_tbl 'inputTable'

-- show result
SELECT *
FROM inputTable
</code>```

You can test it as script if you do the following

```<code>--ALTER PROCEDURE [dbo].[dynamic_tbl] (@tablename varchar(50))
--AS
DECLARE @tablename varchar(50)='inputTable'
...
</code>```

Body:
I have a stored procedure which accepts the InputTable as a parameter:

create table inputTable (id int, ItemQty varchar(100))

insert into inputTable(id, ItemQty)
values (1, 'a,b,c'), (2, 'x,y'), (3, 'l,m,n,o,p'),
       (4, 'a,b'), (5, 'm')

The stored procedure I have written is like this:

ALTER PROCEDURE [dbo].[dynamic_tbl]
    (@tablename VARCHAR(50))
AS
BEGIN
    /* To get the maximum value of ItemQty with comma's [IN THIS CASE IT IS 5 ] */
    DECLARE @ColumnCount int
    DECLARE @rowcount TABLE (Value int);

    INSERT INTO @rowcount
        EXEC('SELECT MAX(len(ITEMQTY) - len(replace(ITEMQTY, '','', '''')) +1) from '+@tablename);

    SELECT @ColumnCount = Value FROM @rowcount;

    DECLARE @ColumnName NVARCHAR(10)='qty_'
    DECLARE @count INT = 0

    IF (@ColumnCount > 0)
    BEGIN
        SET @count = @count + 1;

        WHILE (@ColumnCount >= @count)
        BEGIN
            SET @ColumnName = 'qty_'+CONVERT(varchar(2),@count)
            EXEC ('ALTER TABLE '+@tablename+' ADD ['+@ColumnName +'] varchar(20)')

            DECLARE @myvar AS VARCHAR(MAX)

            --set @myvar='update '+@tablename+' set '+@ColumnName +' =itemQty'

            /* HERE ACTUALLY I AM GETTING PROBLEM, BECAUSE I WANT TO PARSE VALUES IN THE RESPECTIVE COLUMNS. */
           EXEC(@myvar)

           /* HERE, I wish to write the Actual update statement DYNAMICALLY*/
           EXEC ('UPDATE '+@tablename+' set'+@ColumnName+'=     ' )
           SET @count = @count + 1;
       END
   END
END

My input and (desired Output should be like below figures)

Output :

something like this in dynamic way to the code

 declare @myvar as varchar(max)

                SET @MYVAR= 'update '+@tablename+ 'set' +@ColumnName+'=case  when '+@count+' = 1 then itemQty else  end'

                exec(@myvar)

Body:
The variant where ItemQty contains items only with one symbol 'a,b,c'

ALTER PROCEDURE [dbo].[dynamic_tbl] (@tablename varchar(50))
AS

CREATE TABLE #inputTable(id int,ItemQty varchar(100))

-- insert all the data into temp table
DECLARE @copyScript varchar(MAX)
SET @copyScript='SELECT id,ItemQty FROM '+@tablename

INSERT #inputTable(id,ItemQty)
EXEC(@copyScript)

-- add columns and update data in #inputTable
DECLARE @maxColNum int
SET @maxColNum=(SELECT (MAX(LEN(ItemQty))+1)/2 FROM #inputTable)

DECLARE @curColNum int
SET @curColNum=1

DECLARE @updateScript varchar(MAX)
DECLARE @alterScript varchar(MAX)

WHILE @curColNum<=@maxColNum
BEGIN

  -- add new column
  SET @alterScript='ALTER TABLE '+@tablename+' ADD qty'+CAST(@curColNum AS varchar(5))+' varchar(100)'

  --PRINT @alterScript
  EXEC(@alterScript)

  -- update data in new column
  SET @updateScript='UPDATE i
SET
  qty'+CAST(@curColNum AS varchar(5))+'=q.word
FROM '+@tablename+' i
JOIN
  (
    SELECT id,SUBSTRING(ItemQty,'+CAST((@curColNum-1)*2+1 AS varchar(5))+',1) word
    FROM #inputTable
    WHERE LEN(ItemQty)+1>='+CAST(@curColNum*2 AS varchar(5))+'
  ) q
ON i.ID=q.ID'

  --PRINT @updateScript
  EXEC(@updateScript)

  SET @curColNum=@curColNum+1
END

DROP TABLE #inputTable
GO

-- test
EXEC dynamic_tbl 'inputTable'

-- show result
SELECT *
FROM inputTable

The next variant can have strings like 'a,bb,ccc'.

ALTER PROCEDURE [dbo].[dynamic_tbl] (@tablename varchar(50))
AS

CREATE TABLE #inputTable(id int,ItemQty varchar(100))

-- insert all the data into temp table
DECLARE @copyScript varchar(MAX)
SET @copyScript='SELECT id,ItemQty FROM '+@tablename

INSERT #inputTable(id,ItemQty)
EXEC(@copyScript)

-- get all the words for each ID and put them into #words
;WITH wordsCTE AS(
  SELECT
    id,
    ItemQty,
    1 StartPosition,
    CASE WHEN CHARINDEX(',',ItemQty)>0 THEN CHARINDEX(',',ItemQty) ELSE LEN(ItemQty)+1 END CommaPos,
    1 WordNum
  FROM #inputTable

  UNION ALL

  SELECT
    i.id,
    i.ItemQty,
    c.CommaPos+1 StartPosition,
    CASE WHEN CHARINDEX(',',c.ItemQty,c.CommaPos+1)>0 THEN CHARINDEX(',',c.ItemQty,c.CommaPos+1) ELSE LEN(c.ItemQty)+1 END CommaPos,
    c.WordNum+1
  FROM #inputTable i
  JOIN wordsCTE c ON i.id=c.id
  WHERE c.CommaPos<LEN(c.ItemQty)
)
--SELECT *,SUBSTRING(ItemQty,StartPosition,CommaPos-StartPosition) word
SELECT id,SUBSTRING(ItemQty,StartPosition,CommaPos-StartPosition) word,WordNum INTO #words
FROM wordsCTE
--ORDER BY id,word

-- add columns and update data in #inputTable
DECLARE @maxColNum int
SET @maxColNum=(SELECT MAX(WordNum) FROM #words)

DECLARE @curColNum int
SET @curColNum=1

DECLARE @updateScript varchar(MAX)
DECLARE @alterScript varchar(MAX)

WHILE @curColNum<=@maxColNum
BEGIN

  -- add new column
  SET @alterScript='ALTER TABLE '+@tablename+' ADD qty'+CAST(@curColNum AS varchar(5))+' varchar(100)'

  --PRINT @alterScript
  EXEC(@alterScript)

  -- update data in new column
  SET @updateScript='UPDATE i
SET
  qty'+CAST(@curColNum AS varchar(5))+'=q.word
FROM '+@tablename+' i
JOIN
  (
    SELECT *
    FROM #words
    WHERE WordNum='+CAST(@curColNum AS varchar(5))+'
  ) q
ON i.ID=q.ID'

  --PRINT @updateScript
  EXEC(@updateScript)

  SET @curColNum=@curColNum+1
END

DROP TABLE #words
DROP TABLE #inputTable
GO

-- test
EXEC dynamic_tbl 'inputTable'

-- show result
SELECT *
FROM inputTable

You can test it as script if you do the following

--ALTER PROCEDURE [dbo].[dynamic_tbl] (@tablename varchar(50))
--AS
DECLARE @tablename varchar(50)='inputTable'
...


问:
How to get primary and secondary DNS servers in Qt?
I have configured on a Windows machine primary DNS server = 8.8.8.8 and secondary DNS server = 8.8.4.4. How can I find these addresses using Qt?</p>

答:
There is no Qt functionality to doing this. You need to use your OS specific API to do this.
For linux you can read /etc/resolv.conf file or do check IPs with sockets programming.

On Windows you can use GetAdapterAdresses <- C++ example code included


问:
Effect of tweaking numFolds parameter on REPTree classifier on Weka
I use REPTree as classifier on Weka. I got 93% for correctly classified instances. When i change the numFold value from 3 to 5, the correctly classified instances increase to 94%. Can i know whats the significance of numFold in this matter ?</p>

答:
(Click on the "More" Button within the window where you've changed 3 to 5.)

The documentation says "numFolds -- Determines the amount of data used for pruning. One fold is used for pruning, the rest for growing the rules."

To my understanding, "pruning" means automatically cutting back many intermediate,  sparsely populated tree-leaves in order to make the decision tree more simple and understandable.

If you want to even more severely restrict tree size, set maxDepth to 3 or so.


问:
SAS Cumulative sum in a do until loop
Hi I want to create a cumulative sum using group by on a variable, but I want to nest it in a do until loop. But I'm not able to get the right value of sum.

I want to increase calls incrementally from 1 to 8(being max) till the condition in "do until" is satisfied. Basically I want to know the total added calls(cumulative) and then compare it with the condition

```<code>DATA DAS.UNDER_2;
SET UNDER_1;
BY TERR;
  DO i = 1 TO 8 UNTIL (CUMM >= (285 - ADJUSTED_WL));

  CALLS = i;

  IF FIRST.TERR THEN CUMM = CALLS;
  ELSE CUMM + CALLS;

  IF (CUMM > (285 - ADJUSTED_WL)) THEN  CALLS = 0;
 END;
</code>```

This is the result I'm getting:

```<code>+------+-------------+-------+------+
| TERR | ADJUSTED_WL | CALLS | CUMM |
+------+-------------+-------+------+
| A    |          10 |     2 |    2 |
| A    |          10 |     2 |    5 |
| A    |          10 |     2 |    8 |
| B    |          20 |     2 |    2 |
| B    |          20 |     2 |    5 |
| B    |          20 |     2 |    8 |
| C    |          30 |     2 |    2 |
| C    |          30 |     2 |    5 |
| C    |          30 |     2 |    8 |
+------+-------------+-------+------+
</code>```

Whereas, the CUMM should be cumulative sum of the Calls column like 2, 4, 6, 8..

答:
I found easily an example here :
https://communities.sas.com/t5/SAS-Procedures/How-do-I-create-a-cumulative-total-column-subset-by-another/td-p/91118

Data input :

```<code>data have;
input ID  AMT;
cards;
10 150
10 100
25 150
25 150
25 150
30 600
30 300
run;
</code>```

With another column sumbyid:

```<code>data want;
  set have;
  by id notsorted;
  if first.id then sumbyid=0;
    sumbyid+amt;
run;
</code>```

Result:

```<code>                    Obs    ID    AMT    sumbyid

                     1     10    150      150

                     2     10    100      250

                     3     25    150      150

                     4     25    150      300

                     5     25    150      450

                     6     30    600      600

                     7     30    300      900
</code>```

Regards

Title: SAS Cumulative sum in a do until loop

Body:
Hi I want to create a cumulative sum using group by on a variable, but I want to nest it in a do until loop. But I'm not able to get the right value of sum.

I want to increase calls incrementally from 1 to 8(being max) till the condition in "do until" is satisfied. Basically I want to know the total added calls(cumulative) and then compare it with the condition

DATA DAS.UNDER_2;
SET UNDER_1;
BY TERR;
  DO i = 1 TO 8 UNTIL (CUMM >= (285 - ADJUSTED_WL));

  CALLS = i;

  IF FIRST.TERR THEN CUMM = CALLS;
  ELSE CUMM + CALLS;

  IF (CUMM > (285 - ADJUSTED_WL)) THEN  CALLS = 0;
 END;

This is the result I'm getting:

+------+-------------+-------+------+
| TERR | ADJUSTED_WL | CALLS | CUMM |
+------+-------------+-------+------+
| A    |          10 |     2 |    2 |
| A    |          10 |     2 |    5 |
| A    |          10 |     2 |    8 |
| B    |          20 |     2 |    2 |
| B    |          20 |     2 |    5 |
| B    |          20 |     2 |    8 |
| C    |          30 |     2 |    2 |
| C    |          30 |     2 |    5 |
| C    |          30 |     2 |    8 |
+------+-------------+-------+------+

Whereas, the CUMM should be cumulative sum of the Calls column like 2, 4, 6, 8..

Body:
I found easily an example here :
https://communities.sas.com/t5/SAS-Procedures/How-do-I-create-a-cumulative-total-column-subset-by-another/td-p/91118

Data input :

data have;
input ID  AMT;
cards;
10 150
10 100
25 150
25 150
25 150
30 600
30 300
run;

With another column sumbyid:

data want;
  set have;
  by id notsorted;
  if first.id then sumbyid=0;
    sumbyid+amt;
run;

Result:

                    Obs    ID    AMT    sumbyid

                     1     10    150      150

                     2     10    100      250

                     3     25    150      150

                     4     25    150      300

                     5     25    150      450

                     6     30    600      600

                     7     30    300      900

Regards


问:
Hiding Scrolling activity title in android studio
I have created a Scrolling activity.

I want to hide this activity title (Banglalink Latest Offers).

But

I want to show activity title at this stage (Banglalink Latest Offers).

Is it possible to do?
If yes, how?

答:
You have to remove the line android:theme="@style/AppTheme.AppBarOverlay"in your XML. Once you removed the title will go to background. So you able hide title of the activity. as an example, you can place a placeholder to hide it.

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:fitsSystemWindows="true">

<android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar"
    android:layout_width="match_parent"
    android:layout_height="220dp"
    android:fitsSystemWindows="true"
    >
   <!--android:theme="@style/AppTheme.AppBarOverlay"-->

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/toolbar_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        app:contentScrim="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed"
        app:toolbarId="@+id/toolbar">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                app:layout_collapseMode="pin"
                app:srcCompat="@drawable/place_holder" />

            <ImageButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginLeft="6dp"
                android:layout_marginStart="6dp"
                android:layout_marginTop="8dp"
                android:src="@mipmap/next"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

        </android.support.constraint.ConstraintLayout>

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>
    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_display_shop" />
</android.support.design.widget.CoordinatorLayout>
</code>```

Body:
You have to remove the line android:theme="@style/AppTheme.AppBarOverlay"in your XML. Once you removed the title will go to background. So you able hide title of the activity. as an example, you can place a placeholder to hide it.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:fitsSystemWindows="true">

<android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar"
    android:layout_width="match_parent"
    android:layout_height="220dp"
    android:fitsSystemWindows="true"
    >
   <!--android:theme="@style/AppTheme.AppBarOverlay"-->

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/toolbar_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        app:contentScrim="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed"
        app:toolbarId="@+id/toolbar">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                app:layout_collapseMode="pin"
                app:srcCompat="@drawable/place_holder" />

            <ImageButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginLeft="6dp"
                android:layout_marginStart="6dp"
                android:layout_marginTop="8dp"
                android:src="@mipmap/next"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

        </android.support.constraint.ConstraintLayout>

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>
    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_display_shop" />
</android.support.design.widget.CoordinatorLayout>


问:
Java: Clear console of NetBeans, through my program
I want to clear the console output of the NetBeans console. We can clear it manually by using Ctrl+L.

Is it possible to do this programmatically, in Java?

Thank you very much

答:
I think that it's not so simple.

The Netbeans console is not really a full system console.

I'd see a proper option - like getting the console reference using the Netbeans RPC binding, but your application would need to run as a Netbeans plugin or bundle. (so - don't do that, keep it simple)

For a shortcut (workaround) - you may try to use java.awt.Robot class to send a keyRelease event (Ctrl+L) while being focused in the console (effectively sending the Ctrl+L event to the focused component)


问:
Replacing Swiper pagination with text from html
Am having a hard time with my swiper pagination, i changed my pagination to text, the click event works well but the active class does not cycle through other pagination and auto play does not work too. but if i replace it with only (index + 1) every thing works well. Any help is appreciated.

```<code><div class="swiper-pagination swiper-pagination-clickable swiper-pagination-
bullets" style="background: #fff">
    <div class="swiper-pagination-bullet swiper-pagination-bullet-active">
     <div class="">1</div>
     hello there you are
    </div>
    <div class="swiper-pagination-bullet">active not</div>
    <div class="swiper-pagination-bullet">active not</div>
    <div class="swiper-pagination-bullet ">active not</div>
</div>

var swiper = new Swiper('.swiper1',{
autoplay: {
    delay: 1000,
    disableOnInteraction: true,
  },
disableDraggable: true,
pagination: {
    el: '.swiper-pagination',
    clickable: true,
    renderBullet: function (index, className) {
      return '<div class="' + className + '">' + (text) + (index + 1) +
     '</div>';

    },
  },
loop: true
});
</code>```

答:
It wont work because it'll throw a ReferenceError: text is not defined.
Where did it came from?

if you're trying to add custom text inside the bullets you can try:

```<code>let labels = ['label1', 'label2', 'label3'];
</code>```

and on your renderBullet function you can do:

```<code>renderBullet: function (index, className) {
  return '<div class="' + className + '">' + (labels[index]) + (index + 1) +
 '</div>';

},
</code>```

Here's a working fiddle

Body:
Am having a hard time with my swiper pagination, i changed my pagination to text, the click event works well but the active class does not cycle through other pagination and auto play does not work too. but if i replace it with only (index + 1) every thing works well. Any help is appreciated.

1

     hello there you are

active not

active not

active not

var swiper = new Swiper('.swiper1',{
autoplay: {
    delay: 1000,
    disableOnInteraction: true,
  },
disableDraggable: true,
pagination: {
    el: '.swiper-pagination',
    clickable: true,
    renderBullet: function (index, className) {
      return '
' + (text) + (index + 1) +
     '
';

    },
  },
loop: true
});

Body:
It wont work because it'll throw a ReferenceError: text is not defined.
Where did it came from?

if you're trying to add custom text inside the bullets you can try:

let labels = ['label1', 'label2', 'label3'];

and on your renderBullet function you can do:

renderBullet: function (index, className) {
  return '<div class="' + className + '">' + (labels[index]) + (index + 1) +
 '</div>';

},

Here's a working fiddle


问:
difference between withRegion() and withEndpointConfiguration() method in aws s3 or sqs client
what is difference between withRegion() and withEndpointConfiguration() method in aws S3 or SQS client.

UsingEndpointConfiguration needs endPoint and signingRegion. Is this signingRegion same as of s3 bucket? If yes, then why we need to specify it twice as region will be part of endpoint also.
Example: us-west-2 in s3-us-west-2.amazonaws.com

答:
withEndpointConfiguration() is used with S3 clones (either on your localhost, Minio, etc.). It is also used with DynamoDB when installed on your local system.

Here is an example using Minio. The region "us-east-1" is just emulated for this API call.

```<code>EndpointConfiguration endpointConfiguration = new EndpointConfiguration(
                "http://192.168.178.84:9000", "us-east-1");
</code>```

Body:
withEndpointConfiguration() is used with S3 clones (either on your localhost, Minio, etc.). It is also used with DynamoDB when installed on your local system.

Here is an example using Minio. The region "us-east-1" is just emulated for this API call.

EndpointConfiguration endpointConfiguration = new EndpointConfiguration(
                "http://192.168.178.84:9000", "us-east-1");


问:
Two way databinding in angular js
I am very new in angular js. I am confused what is the 2 way data binding in angularjs. Suppose In my mvc4 application i have bind the model with the view and user changes the value of a textbox which is binded with a model class property.

After clicking the update button, model is passed to the controller with the changed value.Then the value is passed to the database to update the database. i.e. Model is updating with new values.

In my angularjs application I have also binded the same textbox with the model. To update the model user puts a new value to the textbox and model changes. The new model is passed through the web api controller to update the database.

My QUESTION is : What is the difference between this two type of binding mechanism.In both cases view and model is updated. So what is 2 way binding in angularjs. Please help me to clear this concept.

答:
Two way DataBinding keeps the model and view in sync at all the times,that is change in the model updates the view and a change in the view updates the model.

Binding expression updates the view when the model changes.

ng-model directive updates the model when the view changes.

Title: Two way databinding in angular js


问:
How to get system date in SQL Server with the format of 'MM dd, yyyy'
How to get the system date in SQL Server with the format of MM dd, yyyy?

I tried everything but I couldn't get the correct format MM dd, yyyy

答:
SELECT CONVERT(VARCHAR(12), GETDATE(), 107)

try this query this will help you.


问:
Avoid broadcasting on an argument in Julia
Consider this toy version of a very real-life problem:

```<code>julia> foo(a,b) = sum(a) + b
foo (generic function with 1 method)

julia> foo.([1,2],[3,4,5])
ERROR: DimensionMismatch("arrays could not be broadcast to a common size")
Stacktrace:
 [1] _bcs1(::Base.OneTo{Int64}, ::Base.OneTo{Int64}) at ./broadcast.jl:70
 [2] _bcs at ./broadcast.jl:63 [inlined]
 [3] broadcast_shape at ./broadcast.jl:57 [inlined] (repeats 2 times)
 [4] broadcast_indices at ./broadcast.jl:53 [inlined]
 [5] broadcast_c at ./broadcast.jl:311 [inlined]
 [6] broadcast(::Function, ::Array{Int64,1}, ::Array{Int64,1}) at ./broadcast.jl:434
</code>```

I want the above code to return [6,7,8], but that's not happening because the broadcast implied by the dot tries to match up the input vectors of length 2 and 3 and feed scalars into both arguments of foo. How can I avoid this?

答:
Simply wrap the arguments you don't want to broadcast on into a Ref:

```<code>julia> foo.(Ref([1,2]),[3,4,5])
3-element Array{Int64,1}:
 6
 7
 8
</code>```

Body:
Consider this toy version of a very real-life problem:

julia> foo(a,b) = sum(a) + b
foo (generic function with 1 method)

julia> foo.([1,2],[3,4,5])
ERROR: DimensionMismatch("arrays could not be broadcast to a common size")
Stacktrace:
 [1] _bcs1(::Base.OneTo{Int64}, ::Base.OneTo{Int64}) at ./broadcast.jl:70
 [2] _bcs at ./broadcast.jl:63 [inlined]
 [3] broadcast_shape at ./broadcast.jl:57 [inlined] (repeats 2 times)
 [4] broadcast_indices at ./broadcast.jl:53 [inlined]
 [5] broadcast_c at ./broadcast.jl:311 [inlined]
 [6] broadcast(::Function, ::Array{Int64,1}, ::Array{Int64,1}) at ./broadcast.jl:434

I want the above code to return [6,7,8], but that's not happening because the broadcast implied by the dot tries to match up the input vectors of length 2 and 3 and feed scalars into both arguments of foo. How can I avoid this?

Body:
Simply wrap the arguments you don't want to broadcast on into a Ref:

julia> foo.(Ref([1,2]),[3,4,5])
3-element Array{Int64,1}:
 6
 7
 8

ContentLicense: CC BY-SA 4.0


问:
multiple checkbox filter in ng-repeat
So i have a search bar that have multiple checkbox that will filter the ng-repeat when i check any of the checkbox they will filter it but when i select another one it doesn't return anything ?

Example

Cancelled checkbox and Pending Approval has been checked!

Am i missing something ?

displayedCollection value

```<code>displayedCollection:[{ "employeeName" : "test user","status" : "Pending Approval"}]
</code>```

ng-repeat

```<code><label class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" ng-model="cancelled" ng-true-value="'Cancelled'" ng-false-value="">
<span class="custom-control-indicator"></span>
<span class="custom-control-description">Cancelled</span>
</code>```

```<code><label class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" ng-model="pa" ng-true-value="'Pending Approval'" ng-false-value="">
<span class="custom-control-indicator"></span>
<span class="custom-control-description">Pending Approval</span>
</code>```

html

```<code><tr ng-repeat="leave in displayedCollection | dateRanges:from:to | filter:cancelled | filter:pa">
<td class="text-capitalize">{{ leave.fullName }}</td>
<td>{{ leave.fromDate | date: 'MM/dd/yyyy'}} - {{ leave.toDate | date: 'MM/dd/yyyy' }}</td>
<td>{{ leave.leaveType }}</td>
<td>{{ }}</td>
<td class="text-center">{{ leave.leaveDays }}</td>
<td class="text-center">{{ leave.leaveStatus }}</td>
<td class="text-center">
    <i class="fa fa-comment-o" aria-hidden="true" data-target="#modalComment" data-toggle="modal" ng-click="vm.getComment(leave)"></i>
</td>
<td class="text-center">
    <button type="button" class="btn btn-trans-blue btn-raised btn-xs btn-circle">
        <strong>
            <i class="fa fa-ellipsis-h fa-1x" aria-hidden="true"></i>
        </strong>
    </button>
    <button type="button" class="btn btn-trans-red btn-raised btn-xs btn-circle" ng-click="vm.deleteLeave(leave)">
        <i class="fa fa-trash-o fa-1x" aria-hidden="true"></i>
    </button>
</td></tr>
</code>```

答:
use the || (OR) operator on the filter.

```<code><tr ng-repeat="leave in displayedCollection | dateRanges:from:to | filter: (cancelled || pa)">
</code>```

Filter the data set according to the status property also

```<code><li ng-repeat="account in accounts | filter:{status : pa ||cancelled  }">{{account}}</li>
</code>```

Demo

Title: multiple checkbox filter in ng-repeat

Body:
So i have a search bar that have multiple checkbox that will filter the ng-repeat when i check any of the checkbox they will filter it but when i select another one it doesn't return anything ?

Example

Cancelled checkbox and Pending Approval has been checked!

Am i missing something ?

displayedCollection value

displayedCollection:[{ "employeeName" : "test user","status" : "Pending Approval"}]

ng-repeat

<input type="checkbox" class="custom-control-input" ng-model="cancelled" ng-true-value="'Cancelled'" ng-false-value="">

Cancelled

<input type="checkbox" class="custom-control-input" ng-model="pa" ng-true-value="'Pending Approval'" ng-false-value="">

Pending Approval

html

{{ leave.fullName }}
{{ leave.fromDate | date: 'MM/dd/yyyy'}} - {{ leave.toDate | date: 'MM/dd/yyyy' }}
{{ leave.leaveType }}
{{ }}
{{ leave.leaveDays }}
{{ leave.leaveStatus }}

    <button type="button" class="btn btn-trans-blue btn-raised btn-xs btn-circle">

    </button>
    <button type="button" class="btn btn-trans-red btn-raised btn-xs btn-circle" ng-click="vm.deleteLeave(leave)">

    </button>

Body:
use the || (OR) operator on the filter.

<tr ng-repeat="leave in displayedCollection | dateRanges:from:to | filter: (cancelled || pa)">

Filter the data set according to the status property also

<li ng-repeat="account in accounts | filter:{status : pa ||cancelled  }">{{account}}</li>

Demo


问:
Lengthy jQuery AJAX request freezes browser
I have an AJAX request, processing of AJAX request is complex and lengthy. The problem is that this lengthy request freezes browser. I mean when AJAX request is in process then no matter if I click any link/button from page or type some Url of same website in browser address bar it does nothing and keep waiting fro AJAX request response, once AJAX response arrives back other processes start working. I am using async: true with AJAX request.
Here is the code I am using. Its a simple page having nothing else but this jQuery AJAX request. My server side PHP.

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Test Page</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
    <script type="text/javascript">
        $(document).ready(function() {
            $.ajax({
                url: 'http://www.mywebsite.com/doprocessing',
                async: true,
                success: function () {
                    alert('done');
                }
            });
        });
    </script>
</body>
</code>```

Why this is happening? How can I solve this?

PS: Before you mark this duplicate, I have checked almost all similar questions on StackOverflow. No solution is working in my case (though solution in most cases was using async: true which I am already doing.

Thanks in advance,

答:
The reason, why any of the links of the same website are not working during ajax, is that your script is locking the session in the server.

You could either not to use session for this script, or finish session after you are sure that this is correct user etc, but before starting sending emails (or doing anything else lengthy).

Use session_write_close() before starting sending emails in PHP for this.

Alternatively you can implement your own asynchronous session handler.

Body:
I have an AJAX request, processing of AJAX request is complex and lengthy. The problem is that this lengthy request freezes browser. I mean when AJAX request is in process then no matter if I click any link/button from page or type some Url of same website in browser address bar it does nothing and keep waiting fro AJAX request response, once AJAX response arrives back other processes start working. I am using async: true with AJAX request.
Here is the code I am using. Its a simple page having nothing else but this jQuery AJAX request. My server side PHP.

<!DOCTYPE html>

    <title>Test Page</title>

Why this is happening? How can I solve this?

PS: Before you mark this duplicate, I have checked almost all similar questions on StackOverflow. No solution is working in my case (though solution in most cases was using async: true which I am already doing.

Thanks in advance,


问:
How to save data in private and can't be deleted by clear data in settings
I know there are couples of way to save data for application in android recommend by Google, such as SharePreference, SQLite, Storage data-storage

But, the data store by those methods will be delete once user clear data in application detail in settings.

I prefer to save data in Settings.Global or Settings.Secure, but I don't know it can feasible, as the API said:"Applications can read these but are not allowed to write".

```<code>    /**
 * Global system settings, containing preferences that always apply identically
 * to all defined users.  Applications can read these but are not allowed to write;
 * like the "Secure" settings, these are for preferences that the user must
 * explicitly modify through the system UI or specialized APIs for those values.
 */
public static final class Global extends NameValueTable {
</code>```

答:
Just save date in a file which is stored in sdcard
https://developer.android.com/guide/topics/data/data-storage.html#filesExternal</p>

Body:
I know there are couples of way to save data for application in android recommend by Google, such as SharePreference, SQLite, Storage data-storage

But, the data store by those methods will be delete once user clear data in application detail in settings.

I prefer to save data in Settings.Global or Settings.Secure, but I don't know it can feasible, as the API said:"Applications can read these but are not allowed to write".

    /**
 * Global system settings, containing preferences that always apply identically
 * to all defined users.  Applications can read these but are not allowed to write;
 * like the "Secure" settings, these are for preferences that the user must
 * explicitly modify through the system UI or specialized APIs for those values.
 */
public static final class Global extends NameValueTable {


问:
Jmeter giving dos in response instead of loading original page
"Why" and "When" we get this code in JMeter response instead of the real/original page and how to get rid of it?

Script is running successfully but getting this in response & this appears randomly.

Code which i get in response against my request is as displayed in this screenshot:

答:
In View Results Tree the default is showing the response as text file.

The default Text view shows all of the text contained in the response.

You want it to render as Html so choose in drop down of component as HTML or HTML (download resources) and JMeter will render it similar to browser

If the HTML (download resources) view option is selected, the renderer may download images, style-sheets, etc.


问:
Show the active parent menuitem on hover in bootstrap dropdpwn menu
I have a simple 2 level dropdown nav in bootsrap with the code below:

```<code>    <div class="collapse navbar-collapse" id="main-nav">
   <ul class="nav navbar-nav pull-left">
      <li><a href="/" title="Főoldal" class="top_menu_to_link">Főoldal</a></li>
      <li class="dropdown">
         <a href="#" title="Iskolánk" class="top_menu_to_link dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Iskolánk</a>
         <ul class="dropdown-menu">
            <li><a href="/alapadatok" title="Alapadatok" class="submenu_link">Alapadatok</a></li>
            <li><a href="/" title="Még egy teszt menü" class="submenu_link">Még egy teszt menü</a></li>
            <li><a href="/osztalyok" title="Osztályok" class="submenu_link">Osztályok</a></li>
            <li><a href="/" title="Teszt menüpont valami" class="submenu_link">Teszt menüpont valami</a></li>
         </ul>
      </li>
      <li class="dropdown">
         <a href="#" title="Információk" class="top_menu_to_link dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Információk</a>
         <ul class="dropdown-menu">
            <li><a href="/" title="Teszt, infók menüpontba" class="submenu_link">Teszt, infók menüpontba</a></li>
         </ul>
      </li>
      <li><a href="/arlista" title="Árlista" class="top_menu_to_link">Árlista</a></li>
      <li><a href="/hirek" title="Hírek" class="top_menu_to_link">Hírek</a></li>
      <li><a href="/kepgaleria" title="Képgaléria" class="top_menu_to_link">Képgaléria</a></li>
      <li><a href="/dokumentumok" title="Dokumentumok" class="top_menu_to_link">Dokumentumok</a></li>
      <li><a href="/kapcsolatfelvetel" title="Kapcsolatfelvétel" class="top_menu_to_link">Kapcsolatfelvétel</a></li>
   </ul>
</div>
</code>```

I added this css to the style file, because i want to show the submenu on hover, not clicking a nav item.

```<code>    .dropdown:hover .dropdown-menu {
    display: block;
    margin-top: 0;
 }
</code>```

When i click the "iskolánk" nav item, and move the cursor to the submenu, the "Iskolánk" nav item will get a white background, that shows me, that this is the active item, and also shows the submenu.

If i dont click the "Iskolánk" nav item, only just hover it, the submenu shows up, but if i move the cursor to the submenu, the "Iskolánk" nav item looses the white background, and it doesnt show that that is the active nav item.

How can i do that? I want to show the submenus always on hover, and not by clicking the parent. The bootstrap css and js file is from the bootstrap website, i dont change anything in them.

答:
The problem is when you are moving to the submenu, cursor leaves the menu (parent) so the CSS hover does not work on it. So to solve this you can write a simple jquery code which keeps the hover effect on the parent(menu) when you are moving to the submenu. but remember, when you are leaving that submenu, you have to remove that effect from the parent.

Add this code snippet to your HTML file.

```<code><script type="text/javascript">
   $(document).ready(function(){
      $('.dropdown-menu').hover(function(){
         $(this).parent().css({background:'#eee'});
      })
      $('.dropdown-menu').mouseleave(function(){
         $(this).parent().css({background:'#fff'});
      })
   })
</script>
</code>```

Body:
I have a simple 2 level dropdown nav in bootsrap with the code below:

Főoldal

         Iskolánk

Alapadatok

Még egy teszt menü

Osztályok

Teszt menüpont valami

         Információk

Teszt, infók menüpontba

Árlista

Hírek

Képgaléria

Dokumentumok

Kapcsolatfelvétel

I added this css to the style file, because i want to show the submenu on hover, not clicking a nav item.

    .dropdown:hover .dropdown-menu {
    display: block;
    margin-top: 0;
 }

When i click the "iskolánk" nav item, and move the cursor to the submenu, the "Iskolánk" nav item will get a white background, that shows me, that this is the active item, and also shows the submenu.

If i dont click the "Iskolánk" nav item, only just hover it, the submenu shows up, but if i move the cursor to the submenu, the "Iskolánk" nav item looses the white background, and it doesnt show that that is the active nav item.

How can i do that? I want to show the submenus always on hover, and not by clicking the parent. The bootstrap css and js file is from the bootstrap website, i dont change anything in them.

Body:
The problem is when you are moving to the submenu, cursor leaves the menu (parent) so the CSS hover does not work on it. So to solve this you can write a simple jquery code which keeps the hover effect on the parent(menu) when you are moving to the submenu. but remember, when you are leaving that submenu, you have to remove that effect from the parent.

Add this code snippet to your HTML file.

<script type="text/javascript">
   $(document).ready(function(){
      $('.dropdown-menu').hover(function(){
         $(this).parent().css({background:'#eee'});
      })
      $('.dropdown-menu').mouseleave(function(){
         $(this).parent().css({background:'#fff'});
      })
   })
</script>


问:
The module has been successfully installed but then it's not found when imported? - Python
I'm trying to use the graphviz Python module and I've run into this problem:
I pip installed it in my command prompt, but it's not showing up in IPython.  I have additionally a Python 3.5 (32-bit) interpreter where it IS showing up, but I'm trying to figure out how to have it installed so it works in IPython.

I've been recommended to include the sys.path for each of the interpreters.

Anyone have any ideas as to how I'd change it?

答:
Can't test it now, but what if install graphviz from IPython with "!":

```<code>! pip install graphviz
</code>```

And restart IPython.

Body:
Can't test it now, but what if install graphviz from IPython with "!":

! pip install graphviz

And restart IPython.


问:
How can I setup a default mapping in Elastic Search when it creates a new Patterned Index?
I have been able to fix my conflicting fields problem as found in this question.

But it won't fix my problem going forward when more log entries come in that will cause a field to be conflicting (as in Long instead of Float in my case), especially when it rolls over to create a new Index of a specific pattern (i.e. the next day), for example: log-20170101 on the 1st of January 2017, but on the next day it will become 20170102 which won't have the applied mapping that I applied on the previous indexes.

How can I setup Elastic Search to apply a mapping on newly created Indexes that start with "log"?

答:
I came across this concept called Index Templates.

By taking my mappings that I defined in the Re-Index process (see this answer), I was able to setup a Template for the Indexes that forms part of the Index Pattern "log-*".

The added benefit was that, no matter how many times I told Kibana to refresh my Index Patterns it never added new keywords or changed any of the defined types, so I can finally rest in knowing that my given field that was constantly "conflicting" will now be interpreted as Float as long as the value is numeric.


问:
Splice from array works only in one order
I have a little problem.
I have a checkbox for showing div. I can choose from 6 different checkboxes to select which div I want to show.

When check checkboxes I show div and send to server checked name of div.

```<code> $scope.savesGraphUserDetail = [];
    $scope.addRemoveUserChart = function(checked, value) {
      if (checked) {
        $scope.savesGraphUserDetail.push(value);

        var config = { headers: { "Content-Type": "application/x-www-form-urlencoded", "X-HTTP-Method-Override": "PUT" } };
        var data = {graphsConfig: $scope.savesGraphUserDetail};

        $http
        .post(serviceBase + "blabla", data, config)
          .success(function(data, status, headers, config) {
          })
          .error(function(data, status, header, config) {
          });
      }else {
        var index = $scope.savesGraphUserDetail.indexOf(value);
        $scope.savesGraphUserDetail.splice(index);

        var config = { headers: { "Content-Type": "application/x-www-form-urlencoded", "X-HTTP-Method-Override": "PUT" } };
        var data = {graphsConfig: $scope.savesGraphUserDetail};

        $http
          .post(serviceBase + "blabla", data, config)
          .success(function(data, status, headers, config) {
          })
          .error(function(data, status, header, config) {
          });
      }
</code>```

And this is ok,
but when I uncheck checkboxes I get a problem, because if I check in this order
first click "A", second "C" and third "D" I push in my array like this

```<code>myArray = ["A", "C", "D"]
</code>```

And if I uncheck in reverse order,
first uncheck "D"

```<code>myArray = ["A", "C"]
</code>```

second uncheck "C"

```<code>myArray = ["A"]
</code>```

and last "A"

```<code>myArray = []
</code>```

and this is perfect, but if I change order when unchecking checkboxes

```<code>myArray = ["A", "C", "D"]
</code>```

if I first uncheck "C", my array remove "C" and "D", i get this

```<code>myArray = ["A"]
</code>```

if I first uncheck "A", my array remove "A" and "C" and "D", I get this

```<code>myArray = []
</code>```

How to remove an only unchecked item?

答:
You need to specify the deleteCount of Array#splice, because without all elements starting with the actual index are deleted.

Parameters

deleteCount Optional

An integer indicating the number of old array elements to remove. If deleteCount is 0, no elements are removed. In this case, you should specify at least one new element. If deleteCount is greater than the number of elements left in the array starting at start, then all of the elements through the end of the array will be deleted.

If deleteCount is omitted, or if its value is larger than array.length - start, then all of the elements beginning with start index on through the end of the array will be deleted.

```<code>$scope.savesGraphUserDetail.splice(index, 1);
//                                        ^
</code>```

Body:
I have a little problem.
I have a checkbox for showing div. I can choose from 6 different checkboxes to select which div I want to show.

When check checkboxes I show div and send to server checked name of div.

 $scope.savesGraphUserDetail = [];
    $scope.addRemoveUserChart = function(checked, value) {
      if (checked) {
        $scope.savesGraphUserDetail.push(value);

        var config = { headers: { "Content-Type": "application/x-www-form-urlencoded", "X-HTTP-Method-Override": "PUT" } };
        var data = {graphsConfig: $scope.savesGraphUserDetail};

        $http
        .post(serviceBase + "blabla", data, config)
          .success(function(data, status, headers, config) {
          })
          .error(function(data, status, header, config) {
          });
      }else {
        var index = $scope.savesGraphUserDetail.indexOf(value);
        $scope.savesGraphUserDetail.splice(index);

        var config = { headers: { "Content-Type": "application/x-www-form-urlencoded", "X-HTTP-Method-Override": "PUT" } };
        var data = {graphsConfig: $scope.savesGraphUserDetail};

        $http
          .post(serviceBase + "blabla", data, config)
          .success(function(data, status, headers, config) {
          })
          .error(function(data, status, header, config) {
          });
      }

And this is ok,
but when I uncheck checkboxes I get a problem, because if I check in this order
first click "A", second "C" and third "D" I push in my array like this

myArray = ["A", "C", "D"]

And if I uncheck in reverse order,
first uncheck "D"

myArray = ["A", "C"]

second uncheck "C"

myArray = ["A"]

and last "A"

myArray = []

and this is perfect, but if I change order when unchecking checkboxes

myArray = ["A", "C", "D"]

if I first uncheck "C", my array remove "C" and "D", i get this

myArray = ["A"]

if I first uncheck "A", my array remove "A" and "C" and "D", I get this

myArray = []

How to remove an only unchecked item?

Body:
You need to specify the deleteCount of Array#splice, because without all elements starting with the actual index are deleted.

Parameters

deleteCount Optional

An integer indicating the number of old array elements to remove. If deleteCount is 0, no elements are removed. In this case, you should specify at least one new element. If deleteCount is greater than the number of elements left in the array starting at start, then all of the elements through the end of the array will be deleted.

If deleteCount is omitted, or if its value is larger than array.length - start, then all of the elements beginning with start index on through the end of the array will be deleted.

$scope.savesGraphUserDetail.splice(index, 1);
//                                        ^


问:
Using CSS to hide the last row conditionally
```<code><table>
<tbody>
<tr class = "row">
  <td class = "A"> </td>
  <td class = "A"> </td>
  <td class = "A B"> </td>
</tr>

<tr class = "row">
  <td class = "A B"> </td>
  <td class = "A B"> </td>
  <td class = "A B"> </td>
</tr>
</tbody>
</table>
</code>```

How to hide the last row if all of its children td contains class B.

I have a calendar that dynamically generate the row and I want to hide the  cell that does not belong to this current month (indicate by class "B"). I want to hide the entire row if all of its children satisfy this condition.

Currently I have

```<code>  tbody {
    tr:last-child {
      display: none;
    }
  }
</code>```

But this will not work as sometimes the last row is partially filled and I dont want to hide it.

Not sure if it is possible with pure CSS selector.

答:
CSS stands for Cascading Style Sheets, so there is no way to style parent node.
But upcoming CSS4 might come with solution with :has() pseudoclass so your code might just look like this:

```<code>tr:last-child:has( :first-child.B ){
    display : none;
}
</code>```

If the first  in last
 has class B then entire row will not be displayed.

That's the future, for now you might use JS or server-sider solution.

Body:
How to hide the last row if all of its children td contains class B.

I have a calendar that dynamically generate the row and I want to hide the  cell that does not belong to this current month (indicate by class "B"). I want to hide the entire row if all of its children satisfy this condition.

Currently I have

  tbody {
    tr:last-child {
      display: none;
    }
  }

But this will not work as sometimes the last row is partially filled and I dont want to hide it.

Not sure if it is possible with pure CSS selector.

Body:
CSS stands for Cascading Style Sheets, so there is no way to style parent node.
But upcoming CSS4 might come with solution with :has() pseudoclass so your code might just look like this:

tr:last-child:has( :first-child.B ){
    display : none;
}

If the first <td> in last <tr> has class B then entire row will not be displayed.

That's the future, for now you might use JS or server-sider solution.


问:
Default values in Haskell data types
When you define a class in a object-oriented language it usually sets the default values for the member variables. Is there any mechanism in Haskell to do the same thing in record types? And a follow up question: If we don't know from the very start all the values for a data constructor but we obtain them from IO interaction can we build the type using something like the builder pattern from OOP?

Thanks in advance

答:
There's already good answers here, so this answer is only meant as a supplement to the fine answers from chi and Willem Van Onsem.

In mainstream object-oriented languages like Java and C#, it's not that a default object is uninitialised; rather, a default object is normally initialised with default values for their types, and it just happens that for reference types, the default is a null reference.

Haskell doesn't have null references, so records can't be initialised with nulls. The most direct translation of objects would be records where every single constituent element is a Maybe. That's not particularly useful, however, but it highlights how hard it is to protect invariants in OOP.

The Builder pattern doesn't solve that problem at all. Any Builder has to start with an initial Builder object, and that object is going to have to have default values as well.

For more details, and lots of examples, I wrote an article series about this. The article series specifically focuses on the Test Data Builder pattern, but you should be able to see how it generalises to the Fluent Builder pattern in general.

Title: Default values in Haskell data types


问:
c# linq to xml
I have an xml string that I wish to traverse using LINQ to XML (I have never used this, so wish to learn).  However when I try to use

```<code>XDocument xDoc = XDocument.Load(adminUsersXML);
        var users = from result in xDoc.Descendants("Result")
                    select new
                    {
                        test = result.Element("USER_ID").Value
                    };
</code>```

I get an error message saying illegal characters in path.  reading up on it, it's because I cannot pass a standard string in this way.  Is there a way to use XML LINQ qith a standard string?

Thanks.

答:
My guess is that adminUsersXML is the XML itself rather than a path to a file containing XML. If that's the case, just use:

```<code>XDocument doc = XDocument.Parse(adminUsersXML);
</code>```

Title: c# linq to xml

Body:
I have an xml string that I wish to traverse using LINQ to XML (I have never used this, so wish to learn).  However when I try to use

XDocument xDoc = XDocument.Load(adminUsersXML);
        var users = from result in xDoc.Descendants("Result")
                    select new
                    {
                        test = result.Element("USER_ID").Value
                    };

I get an error message saying illegal characters in path.  reading up on it, it's because I cannot pass a standard string in this way.  Is there a way to use XML LINQ qith a standard string?

Thanks.

Body:
My guess is that adminUsersXML is the XML itself rather than a path to a file containing XML. If that's the case, just use:

XDocument doc = XDocument.Parse(adminUsersXML);