问:
Still able to select disabled dates in date picker
I want to disable the past dates of date picker in android.
i can do it by using

```<code>dialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
</code>```

This is working fine and the past dates in date picker looks disabled. But I can still click on a previous date and select it.
How to not let that happen ?
below is the screenshot of my date picker :-

And here is my code where I am disabling the past dates :-

```<code>@Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        mActivity = new WeakReference<CreateEvent>(
                (CreateEvent) getActivity());

        DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);

        if(callingView==fromDate){
            dialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
        }else if (callingView==toDate){
            dialog.getDatePicker().setMinDate(fromD);
        }

        // Create a new instance of DatePickerDialog and return it
        return dialog;
    }
</code>```

答:
To resolve bug for Android Lollipop you can validate date as below:</p>

```<code>    int mYear,mMonth,mDay;
    Calendar mcurrentDate = Calendar.getInstance();
    mYear = mcurrentDate.get(Calendar.YEAR);
    mMonth = mcurrentDate.get(Calendar.MONTH);
    mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);

    DatePickerDialog mDatePicker = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
        // TODO Auto-generated method stub

        // validate here with condition to avoid to select past dates
            if (selectedyear == mYear && (selectedmonth+1) == mMonth+1) {
                if(selectedday < mDay){
                    Toast.makeText(context, "invalid date", Toast.LENGTH_LONG).show();
                    return;
                }
            }

                textview.setText(selectedday + "/" + (selectedmonth+1) + "/" + selectedyear);

        }
    }, mYear, mMonth, mDay);

    mDatePicker.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
    if(!mDatePicker.isShowing()){
        mDatePicker.show();
    }
</code>```

Body:
I want to disable the past dates of date picker in android.
i can do it by using

dialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);

This is working fine and the past dates in date picker looks disabled. But I can still click on a previous date and select it.
How to not let that happen ?
below is the screenshot of my date picker :-

And here is my code where I am disabling the past dates :-

@Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        mActivity = new WeakReference<CreateEvent>(
                (CreateEvent) getActivity());

        DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);

        if(callingView==fromDate){
            dialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
        }else if (callingView==toDate){
            dialog.getDatePicker().setMinDate(fromD);
        }

        // Create a new instance of DatePickerDialog and return it
        return dialog;
    }

Body:
To resolve bug for Android Lollipop you can validate date as below:

    int mYear,mMonth,mDay;
    Calendar mcurrentDate = Calendar.getInstance();
    mYear = mcurrentDate.get(Calendar.YEAR);
    mMonth = mcurrentDate.get(Calendar.MONTH);
    mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);

    DatePickerDialog mDatePicker = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
        // TODO Auto-generated method stub

        // validate here with condition to avoid to select past dates
            if (selectedyear == mYear && (selectedmonth+1) == mMonth+1) {
                if(selectedday < mDay){
                    Toast.makeText(context, "invalid date", Toast.LENGTH_LONG).show();
                    return;
                }
            }

                textview.setText(selectedday + "/" + (selectedmonth+1) + "/" + selectedyear);

        }
    }, mYear, mMonth, mDay);

    mDatePicker.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
    if(!mDatePicker.isShowing()){
        mDatePicker.show();
    }


来源: stackexchange

问:
Website Versioning Practices
I tried searching, but I couldn't really figure out the best search terms to find my answer.

I have a Ubuntu 10.04 server with Apache. I want to set up a site that will be versioned, so my file structure will look like:

```<code>/var/www/MyApp1.0
/var/www/MyApp1.1
/var/www/dev -> /var/www/html/MyApp1.1
/var/www/test -> /var/www/html/MyApp1.0
</code>```

Where "dev" and "test" are symbolic links to the other folders. So my URL for those two environments will be "http://my-url.com/dev" or "http://my-url.com/test". For my prod environment, I want the URL in the browser to be just "http://my-url.com", without redirecting to something like "http://my-url.com/prod".

How can I set it up so that the base URL points to a specific version without a redirect changing the URL?

By the way, we use MS SourceSafe for version control, so we have older versions backed up as well, but I need multiple environments for dev, test, and prod.

Thanks,

Travis

答:
I think you can just check out the right development version to each of your dev, test and 'live' folder. I think it would be easier to just get the right version into the dev folder, than change the symbolic link. Ofcourse you could create a .htaccess file that redirects /dev to a specific version folder, but doing this will just cause you to keep a large amount of different folders for different versions, while what you should be doing is put the website in a version control system, develop features and commit them, update the test folder, and if everything's alright, update your production folder as well.
To do this right you may need to drop SourceSafe.

ContentLicense: CC BY-SA 2.5

Title: Website Versioning Practices

Body:
I tried searching, but I couldn't really figure out the best search terms to find my answer.

I have a Ubuntu 10.04 server with Apache. I want to set up a site that will be versioned, so my file structure will look like:

/var/www/MyApp1.0
/var/www/MyApp1.1
/var/www/dev -> /var/www/html/MyApp1.1
/var/www/test -> /var/www/html/MyApp1.0

Where "dev" and "test" are symbolic links to the other folders. So my URL for those two environments will be "http://my-url.com/dev" or "http://my-url.com/test". For my prod environment, I want the URL in the browser to be just "http://my-url.com", without redirecting to something like "http://my-url.com/prod".

How can I set it up so that the base URL points to a specific version without a redirect changing the URL?

By the way, we use MS SourceSafe for version control, so we have older versions backed up as well, but I need multiple environments for dev, test, and prod.

Thanks,

Travis


问:
knife bootstrap is failing --node-ssl-verify-mode none is not working
```<code>knife ec2 server create -E staging --node-name temp-chef-upgrade-test -f t2.small -r "recipe[base]"  -g xxxx -x ubuntu -I ami-49c9295f --subnet xxx -S xxxx -i xxxx --server-connect-attribute private_ip_address --node-ssl-verify-mode none  --no-node-verify-api-cert
</code>```

I have set both of the below flags to my knife.rb as well

```<code>ssl_verify_mode          :verify_none
verify_api_cert          false
</code>```

chef-client version

```<code>Chef 12.19.36
</code>```

chef-server

```<code>12.13
</code>```

Error

```<code>xx.xx.xx.xx [2017-03-28T10:02:03+00:00] ERROR: SSL Validation failure connecting to host: xx.xx.xx.xx - hostname "xx.xx.xx.xx" does not match the server certificate
xx.xx.xx.xx [2017-03-28T10:02:03+00:00] ERROR: SSL Error connecting to https://xx.xx.xx.xx/clients, retry 1/5
</code>```

答:
Well first I am okay if don't verify ssl, which should work with --node-ssl-verify-mode none but some how it didnt adding ssl_verify_mode :verify_none in client.rb and chef-client still trying to do ssl verification.(so i assume it can be bug in knife bootstrap)

So i have solved the above problem by using --bootstrap-template

```<code>knife ec2 server create -E $environment --node-name $TMP_NODE_NAME -f $instance_type -r "recipe[base]" --iam-profile $recipe --bootstrap-template ~/.chef/chef-no-ssl.erb $knife_ec2_flag
</code>```

~/.chef/chef-no-ssl.erb

```<code>bash -c '
<%= "export https_proxy=\"#{knife_config[:bootstrap_proxy]}\"" if knife_config[:bootstrap_proxy] -%>

distro=`uname -s`

if test "x$distro" = "xSunOS"; then
  if test -d "/usr/sfw/bin"; then
    PATH=/usr/sfw/bin:$PATH
    export PATH
  fi
fi

exists() {
  if command -v $1 &>/dev/null
  then
    return 0
  else
    return 1
  fi
}

install_sh="https://www.getchef.com/chef/install.sh"
version_string="-v 12.19.36"

if ! exists /usr/bin/chef-client; then
  echo "Installing Chef Client..."
  if exists wget; then
    bash <(wget <%= "--proxy=on " if knife_config[:bootstrap_proxy] %> ${install_sh} -O -) ${version_string}
  elif exists curl; then
    bash <(curl -L <%= "--proxy \"#{knife_config[:bootstrap_proxy]}\" " if knife_config[:bootstrap_proxy] %> ${install_sh}) ${version_string}
  else
    echo "Neither wget nor curl found. Please install one and try again." >&2
    exit 1
  fi
fi

mkdir -p /etc/chef

cat > /etc/chef/validation.pem <<'EOP'
<%= validation_key %>
EOP
chmod 0600 /etc/chef/validation.pem

<% if encrypted_data_bag_secret -%>
cat > /etc/chef/encrypted_data_bag_secret <<'EOP'
<%= encrypted_data_bag_secret %>
EOP
chmod 0600 /etc/chef/encrypted_data_bag_secret
<% end -%>

<%# Generate Ohai Hints -%>
<% unless @chef_config[:knife][:hints].nil? || @chef_config[:knife][:hints].empty? -%>
mkdir -p /etc/chef/ohai/hints

<% @chef_config[:knife][:hints].each do |name, hash| -%>
cat > /etc/chef/ohai/hints/<%= name %>.json <<'EOP'
<%= hash.to_json %>
EOP
<% end -%>
<% end -%>

cat > /etc/chef/client.rb <<'EOP'
<%= config_content.concat "\nssl_verify_mode :verify_none" %>
EOP

cat > /etc/chef/first-boot.json <<'EOP'
<%= first_boot.to_json %>
EOP

echo "Starting first Chef Client run..."

<%= start_chef %>'
</code>```

so if you notice at the end there is client.rb block on which I am concatenating

```<code>cat > /etc/chef/client.rb <<'EOP'
<%= config_content.concat "\nssl_verify_mode :verify_none" %>
EOP
</code>```

ContentLicense: CC BY-SA 4.0

Body:
knife ec2 server create -E staging --node-name temp-chef-upgrade-test -f t2.small -r "recipe[base]"  -g xxxx -x ubuntu -I ami-49c9295f --subnet xxx -S xxxx -i xxxx --server-connect-attribute private_ip_address --node-ssl-verify-mode none  --no-node-verify-api-cert

I have set both of the below flags to my knife.rb as well

ssl_verify_mode          :verify_none
verify_api_cert          false

chef-client version

Chef 12.19.36

chef-server

12.13

Error

xx.xx.xx.xx [2017-03-28T10:02:03+00:00] ERROR: SSL Validation failure connecting to host: xx.xx.xx.xx - hostname "xx.xx.xx.xx" does not match the server certificate
xx.xx.xx.xx [2017-03-28T10:02:03+00:00] ERROR: SSL Error connecting to https://xx.xx.xx.xx/clients, retry 1/5

Body:
Well first I am okay if don't verify ssl, which should work with --node-ssl-verify-mode none but some how it didnt adding ssl_verify_mode :verify_none in client.rb and chef-client still trying to do ssl verification.(so i assume it can be bug in knife bootstrap)

So i have solved the above problem by using --bootstrap-template

knife ec2 server create -E $environment --node-name $TMP_NODE_NAME -f $instance_type -r "recipe[base]" --iam-profile $recipe --bootstrap-template ~/.chef/chef-no-ssl.erb $knife_ec2_flag

~/.chef/chef-no-ssl.erb

bash -c '
<%= "export https_proxy=\"#{knife_config[:bootstrap_proxy]}\"" if knife_config[:bootstrap_proxy] -%>

distro=`uname -s`

if test "x$distro" = "xSunOS"; then
  if test -d "/usr/sfw/bin"; then
    PATH=/usr/sfw/bin:$PATH
    export PATH
  fi
fi

exists() {
  if command -v $1 &>/dev/null
  then
    return 0
  else
    return 1
  fi
}

install_sh="https://www.getchef.com/chef/install.sh"
version_string="-v 12.19.36"

if ! exists /usr/bin/chef-client; then
  echo "Installing Chef Client..."
  if exists wget; then
    bash <(wget <%= "--proxy=on " if knife_config[:bootstrap_proxy] %> ${install_sh} -O -) ${version_string}
  elif exists curl; then
    bash <(curl -L <%= "--proxy \"#{knife_config[:bootstrap_proxy]}\" " if knife_config[:bootstrap_proxy] %> ${install_sh}) ${version_string}
  else
    echo "Neither wget nor curl found. Please install one and try again." >&2
    exit 1
  fi
fi

mkdir -p /etc/chef

cat > /etc/chef/validation.pem <<'EOP'
<%= validation_key %>
EOP
chmod 0600 /etc/chef/validation.pem

<% if encrypted_data_bag_secret -%>
cat > /etc/chef/encrypted_data_bag_secret <<'EOP'
<%= encrypted_data_bag_secret %>
EOP
chmod 0600 /etc/chef/encrypted_data_bag_secret
<% end -%>

<%# Generate Ohai Hints -%>
<% unless @chef_config[:knife][:hints].nil? || @chef_config[:knife][:hints].empty? -%>
mkdir -p /etc/chef/ohai/hints

<% @chef_config[:knife][:hints].each do |name, hash| -%>
cat > /etc/chef/ohai/hints/<%= name %>.json <<'EOP'
<%= hash.to_json %>
EOP
<% end -%>
<% end -%>

cat > /etc/chef/client.rb <<'EOP'
<%= config_content.concat "\nssl_verify_mode :verify_none" %>
EOP

cat > /etc/chef/first-boot.json <<'EOP'
<%= first_boot.to_json %>
EOP

echo "Starting first Chef Client run..."

<%= start_chef %>'

so if you notice at the end there is client.rb block on which I am concatenating

cat > /etc/chef/client.rb <<'EOP'
<%= config_content.concat "\nssl_verify_mode :verify_none" %>
EOP

ContentLicense: CC BY-SA 3.0


问:
redirect angular module to another module
I have 2 different HTML pages with 2 different angular apps.
One page is for landing page and another for home page.The first page is rendered by the keycloak and I want to automatically redirect to another page and also inject the app1 module to 2nd module so, I can reuse app1 details.

```<code>var module = angular.module('product', []);

module.controller('GlobalCtrl', function(login) {
    this.loginService = login;
});

module.factory('login', function($q, $rootScope) {
    var keycloakAuth = new Keycloak('keycloak/keycloak.json');
    var deferred = $q.defer();
    keycloakAuth.init({onLoad: 'login-required'})
        .success(function() {
            console.log('Success', keycloakAuth);
            deferred.resolve()
        })
        .error(function(err) {
            console.error('Error', err, keycloakAuth);
            deferred.reject(err);
        });
    keycloakAuth.ready = deferred.promise
        .then(function() {
            if (keycloakAuth.authenticated) {
                keycloakAuth.loadUserProfile()
                    .success(function() {
                        console.log('User profile loaded');
                        $rootScope.$digest();
                    })
                    .error(function(err) {
                        console.log('Error loading user profile', err);
                    })
            }
        })
        .finally(function() {
            console.log('Finally');
            $rootScope.$digest();
        });
    return keycloakAuth;
});

angular
  .module('themesApp', [
    'theme',
    'theme.demos','product'
  ])
  .config(['$provide', '$routeProvider', function($provide, $routeProvider) {
    'use strict';
    $routeProvider
      .when('/newapp', {
        templateUrl: 'views/index1.html',
        resolve: {
          loadCalendar: ['$ocLazyLoad', function($ocLazyLoad) {
            return $ocLazyLoad.load([
              'bower_components/fullcalendar/fullcalendar.js',
            ]);
          }]
        }
      })
      .when('/:templateFile', {
        templateUrl: function(param) {
          return 'views/' + param.templateFile + '.html';
        }
      })
      .when('#', {
        templateUrl: 'views/index1.html',
      })
      .otherwise({
        redirectTo: '/newapp'
      });
  }]);
</code>```

How do I redirect one module to another?

答:
I think you can use simple javascript reload.

```<code>window.location="file2.html";
</code>```

Please let me know if that is what you're looking for. Thank you.

Body:
I have 2 different HTML pages with 2 different angular apps.
One page is for landing page and another for home page.The first page is rendered by the keycloak and I want to automatically redirect to another page and also inject the app1 module to 2nd module so, I can reuse app1 details.

var module = angular.module('product', []);

module.controller('GlobalCtrl', function(login) {
    this.loginService = login;
});

module.factory('login', function($q, $rootScope) {
    var keycloakAuth = new Keycloak('keycloak/keycloak.json');
    var deferred = $q.defer();
    keycloakAuth.init({onLoad: 'login-required'})
        .success(function() {
            console.log('Success', keycloakAuth);
            deferred.resolve()
        })
        .error(function(err) {
            console.error('Error', err, keycloakAuth);
            deferred.reject(err);
        });
    keycloakAuth.ready = deferred.promise
        .then(function() {
            if (keycloakAuth.authenticated) {
                keycloakAuth.loadUserProfile()
                    .success(function() {
                        console.log('User profile loaded');
                        $rootScope.$digest();
                    })
                    .error(function(err) {
                        console.log('Error loading user profile', err);
                    })
            }
        })
        .finally(function() {
            console.log('Finally');
            $rootScope.$digest();
        });
    return keycloakAuth;
});

angular
  .module('themesApp', [
    'theme',
    'theme.demos','product'
  ])
  .config(['$provide', '$routeProvider', function($provide, $routeProvider) {
    'use strict';
    $routeProvider
      .when('/newapp', {
        templateUrl: 'views/index1.html',
        resolve: {
          loadCalendar: ['$ocLazyLoad', function($ocLazyLoad) {
            return $ocLazyLoad.load([
              'bower_components/fullcalendar/fullcalendar.js',
            ]);
          }]
        }
      })
      .when('/:templateFile', {
        templateUrl: function(param) {
          return 'views/' + param.templateFile + '.html';
        }
      })
      .when('#', {
        templateUrl: 'views/index1.html',
      })
      .otherwise({
        redirectTo: '/newapp'
      });
  }]);

How do I redirect one module to another?

Body:
I think you can use simple javascript reload.

window.location="file2.html";

Please let me know if that is what you're looking for. Thank you.


问:
@ElementCollection get collection throw error 'org.hibernate.LazyInitializationException'
I have Entity

```<code>public class SmsSending implements Serializable {
....

    @ElementCollection
    @CollectionTable(name = "sms_msisdns", joinColumns = @JoinColumn(name = "sms_sending_id"))
    @Column(name = "msisdns")
    private Set<String> msisdns;
</code>```

In main thread I get Set<String> msisdns = smsSending.getMsisdns(); and pass to new thread.

```<code>executor.submit(new Thread(() -> start(msisdns));
</code>```

And sometime I get error in msisdns

```<code>Unable to evaluate the expression Method threw 'org.hibernate.LazyInitializationException' exception.
</code>```

答:
This is a wrong pattern. You want to keep your fetched entities within that thread, otherwise you will get problems as you mentioned. This is because the underlying Hibernate Session object is not thread-safe, thus when you create a new thread, there is no session whatsoever.

Pass the id of your root entity to the thread, make a transaction inside the new thread and fetch the data you need.

Body:
I have Entity

public class SmsSending implements Serializable {
....

    @ElementCollection
    @CollectionTable(name = "sms_msisdns", joinColumns = @JoinColumn(name = "sms_sending_id"))
    @Column(name = "msisdns")
    private Set<String> msisdns;

In main thread I get Set<String> msisdns = smsSending.getMsisdns(); and pass to new thread.

executor.submit(new Thread(() -> start(msisdns));

And sometime I get error in msisdns

Unable to evaluate the expression Method threw 'org.hibernate.LazyInitializationException' exception.


问:
How to change the color of a selected item of a ComboboxItem which includes a TextBlock?
I have the following XAML of a Combobox:

```<code><ComboBox>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="PaleGreen">1</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="Salmon">2</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="PaleTurquoise">3</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="Gold">4</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="Black" Foreground="White">5</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="Gray">6</TextBlock>
    </ComboBoxItem>
</ComboBox>
</code>```

The following pictures shows my problem:

Combobox open

Combobox closed

So you can see in the picture "Combobox closed" that the number "4" has no color, but I want that the text "4" is yellow. Can you help me?

答:
@janonimus: When I add a template as you said it has following code:

```<code><Window.Resources>
    <ControlTemplate x:Key="ComboBoxControlTemplate1" TargetType="{x:Type ComboBox}">
        <Grid x:Name="Placement" SnapsToDevicePixels="True">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>
            <Popup x:Name="PART_Popup" AllowsTransparency="True" Grid.ColumnSpan="2" IsOpen="{Binding IsDropDownOpen, RelativeSource={RelativeSource TemplatedParent}}" PopupAnimation="{DynamicResource {x:Static SystemParameters.ComboBoxPopupAnimationKey}}" Placement="Bottom">
                <Themes:SystemDropShadowChrome x:Name="Shdw" Color="Transparent" MaxHeight="{TemplateBinding MaxDropDownHeight}" MinWidth="{Binding ActualWidth, ElementName=Placement}">
                    <Border x:Name="DropDownBorder" BorderBrush="{DynamicResource {x:Static SystemColors.WindowFrameBrushKey}}" BorderThickness="1" Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}">
                        <ScrollViewer x:Name="DropDownScrollViewer">
                            <Grid RenderOptions.ClearTypeHint="Enabled">
                                <Canvas HorizontalAlignment="Left" Height="0" VerticalAlignment="Top" Width="0">
                                    <Rectangle x:Name="OpaqueRect" Fill="{Binding Background, ElementName=DropDownBorder}" Height="{Binding ActualHeight, ElementName=DropDownBorder}" Width="{Binding ActualWidth, ElementName=DropDownBorder}"/>
                                </Canvas>
                                <ItemsPresenter x:Name="ItemsPresenter" KeyboardNavigation.DirectionalNavigation="Contained" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                            </Grid>
                        </ScrollViewer>
                    </Border>
                </Themes:SystemDropShadowChrome>
            </Popup>
            <Themes:ListBoxChrome x:Name="Border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Grid.ColumnSpan="2" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderFocused="{TemplateBinding IsKeyboardFocusWithin}"/>
            <TextBox x:Name="PART_EditableTextBox" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" IsReadOnly="{Binding IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}" Margin="{TemplateBinding Padding}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}">
                <TextBox.Style>
                    <Style TargetType="{x:Type TextBox}">
                        <Setter Property="OverridesDefaultStyle" Value="True"/>
                        <Setter Property="AllowDrop" Value="True"/>
                        <Setter Property="MinWidth" Value="0"/>
                        <Setter Property="MinHeight" Value="0"/>
                        <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
                        <Setter Property="ScrollViewer.PanningMode" Value="VerticalFirst"/>
                        <Setter Property="Stylus.IsFlicksEnabled" Value="False"/>
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="{x:Type TextBox}">
                                    <ScrollViewer x:Name="PART_ContentHost" Background="Transparent" Focusable="False" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </TextBox.Style>
            </TextBox>
            <ToggleButton Grid.Column="1" IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}">
                <ToggleButton.Style>
                    <Style TargetType="{x:Type ToggleButton}">
                        <Setter Property="OverridesDefaultStyle" Value="True"/>
                        <Setter Property="IsTabStop" Value="False"/>
                        <Setter Property="Focusable" Value="False"/>
                        <Setter Property="ClickMode" Value="Press"/>
                        <Setter Property="Background" Value="Transparent"/>
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="{x:Type ToggleButton}">
                                    <Themes:ButtonChrome x:Name="Chrome" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}" RoundCorners="False" SnapsToDevicePixels="True" Width="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}">
                                        <Path x:Name="Arrow" Data="M0,0L3.5,4 7,0z" Fill="Black" HorizontalAlignment="Center" Margin="0,1,0,0" VerticalAlignment="Center"/>
                                    </Themes:ButtonChrome>
                                    <ControlTemplate.Triggers>
                                        <Trigger Property="IsChecked" Value="True">
                                            <Setter Property="RenderPressed" TargetName="Chrome" Value="True"/>
                                        </Trigger>
                                        <Trigger Property="IsEnabled" Value="False">
                                            <Setter Property="Fill" TargetName="Arrow" Value="#FFAFAFAF"/>
                                        </Trigger>
                                    </ControlTemplate.Triggers>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </ToggleButton.Style>
            </ToggleButton>
        </Grid>
        <ControlTemplate.Triggers>
            <Trigger Property="IsKeyboardFocusWithin" Value="True">
                <Setter Property="Foreground" Value="Black"/>
            </Trigger>
            <Trigger Property="IsDropDownOpen" Value="True">
                <Setter Property="RenderFocused" TargetName="Border" Value="True"/>
            </Trigger>
            <Trigger Property="HasItems" Value="False">
                <Setter Property="Height" TargetName="DropDownBorder" Value="95"/>
            </Trigger>
            <Trigger Property="IsEnabled" Value="False">
                <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                <Setter Property="Background" Value="#FFF4F4F4"/>
            </Trigger>
            <MultiTrigger>
                <MultiTrigger.Conditions>
                    <Condition Property="IsGrouping" Value="True"/>
                    <Condition>
                        <Condition.Value>
                            <System:Boolean>False</System:Boolean>
                        </Condition.Value>
                    </Condition>
                </MultiTrigger.Conditions>
                <Setter Property="ScrollViewer.CanContentScroll" Value="False"/>
            </MultiTrigger>
            <Trigger Property="HasDropShadow" SourceName="PART_Popup" Value="True">
                <Setter Property="Margin" TargetName="Shdw" Value="0,0,5,5"/>
                <Setter Property="Color" TargetName="Shdw" Value="#71000000"/>
            </Trigger>
            <Trigger Property="CanContentScroll" SourceName="DropDownScrollViewer" Value="False">
                <Setter Property="Canvas.Top" TargetName="OpaqueRect" Value="{Binding VerticalOffset, ElementName=DropDownScrollViewer}"/>
                <Setter Property="Canvas.Left" TargetName="OpaqueRect" Value="{Binding HorizontalOffset, ElementName=DropDownScrollViewer}"/>
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>
</Window.Resources>
</code>```

In addition, an error is thrown as soon as I have inserted the template:

InvalidOperationException: Nicht-NULL-Wert für "Property" erforderlich.

EDIT:

I have the solution. It was quite easy :D I don't need a template. I just added triggers:

```<code>                <Style TargetType="ComboBox">
                    <Setter Property="Background" Value="Transparent"/>
                    <Setter Property="FontSize" Value="10"/>
                    <Setter Property="HorizontalAlignment" Value="Center"/>
                    <Setter Property="VerticalAlignment" Value="Center"/>
                    <Setter Property="Width" Value="115"/>
                    <Setter Property="Foreground" Value="Black"/>
                    <Setter Property="BorderBrush" Value="White"/>
                    <Setter Property="SelectedIndex" Value="0"/>
                    <Setter Property="HorizontalContentAlignment" Value="Center"/>
                    <Setter Property="IsEditable" Value="True"/>
                    <EventSetter Event="SelectionChanged" Handler="SelectionChanged"/>
                    <Style.Triggers>
                        <Trigger Property="IsEnabled" Value="False">
                            <Setter Property="Opacity" Value="0.4"/>
                        </Trigger>
                        <Trigger Property="SelectedIndex" Value="0">
                            <Setter Property="Background" Value="PaleGreen"/>
                            <Setter Property="Foreground" Value="Black"/>
                        </Trigger>
                        <Trigger Property="SelectedIndex" Value="1">
                            <Setter Property="Background" Value="Salmon"/>
                            <Setter Property="Foreground" Value="Black"/>
                        </Trigger>
                        <Trigger Property="SelectedIndex" Value="2">
                            <Setter Property="Background" Value="PaleTurquoise"/>
                            <Setter Property="Foreground" Value="Black"/>
                        </Trigger>
                        <Trigger Property="SelectedIndex" Value="3">
                            <Setter Property="Background" Value="Gold"/>
                            <Setter Property="Foreground" Value="Black"/>
                        </Trigger>
                        <Trigger Property="SelectedIndex" Value="4">
                            <Setter Property="Background" Value="Black"/>
                            <Setter Property="Foreground" Value="White"/>
                        </Trigger>
                        <Trigger Property="SelectedIndex" Value="5">
                            <Setter Property="Background" Value="Gray"/>
                            <Setter Property="Foreground" Value="Black"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
</code>```

Body:
I have the following XAML of a Combobox:

<ComboBox>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="PaleGreen">1</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="Salmon">2</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="PaleTurquoise">3</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="Gold">4</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="Black" Foreground="White">5</TextBlock>
    </ComboBoxItem>
    <ComboBoxItem>
        <TextBlock FontWeight="Bold" Background="Gray">6</TextBlock>
    </ComboBoxItem>
</ComboBox>

The following pictures shows my problem:

Combobox open

Combobox closed

So you can see in the picture "Combobox closed" that the number "4" has no color, but I want that the text "4" is yellow. Can you help me?

Body:
@janonimus: When I add a template as you said it has following code:

<Window.Resources>
    <ControlTemplate x:Key="ComboBoxControlTemplate1" TargetType="{x:Type ComboBox}">
        <Grid x:Name="Placement" SnapsToDevicePixels="True">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>
            <Popup x:Name="PART_Popup" AllowsTransparency="True" Grid.ColumnSpan="2" IsOpen="{Binding IsDropDownOpen, RelativeSource={RelativeSource TemplatedParent}}" PopupAnimation="{DynamicResource {x:Static SystemParameters.ComboBoxPopupAnimationKey}}" Placement="Bottom">
                <Themes:SystemDropShadowChrome x:Name="Shdw" Color="Transparent" MaxHeight="{TemplateBinding MaxDropDownHeight}" MinWidth="{Binding ActualWidth, ElementName=Placement}">
                    <Border x:Name="DropDownBorder" BorderBrush="{DynamicResource {x:Static SystemColors.WindowFrameBrushKey}}" BorderThickness="1" Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}">
                        <ScrollViewer x:Name="DropDownScrollViewer">
                            <Grid RenderOptions.ClearTypeHint="Enabled">
                                <Canvas HorizontalAlignment="Left" Height="0" VerticalAlignment="Top" Width="0">
                                    <Rectangle x:Name="OpaqueRect" Fill="{Binding Background, ElementName=DropDownBorder}" Height="{Binding ActualHeight, ElementName=DropDownBorder}" Width="{Binding ActualWidth, ElementName=DropDownBorder}"/>
                                </Canvas>
                                <ItemsPresenter x:Name="ItemsPresenter" KeyboardNavigation.DirectionalNavigation="Contained" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                            </Grid>
                        </ScrollViewer>
                    </Border>
                </Themes:SystemDropShadowChrome>
            </Popup>
            <Themes:ListBoxChrome x:Name="Border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Grid.ColumnSpan="2" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderFocused="{TemplateBinding IsKeyboardFocusWithin}"/>
            <TextBox x:Name="PART_EditableTextBox" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" IsReadOnly="{Binding IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}" Margin="{TemplateBinding Padding}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}">
                <TextBox.Style>
                    <Style TargetType="{x:Type TextBox}">
                        <Setter Property="OverridesDefaultStyle" Value="True"/>
                        <Setter Property="AllowDrop" Value="True"/>
                        <Setter Property="MinWidth" Value="0"/>
                        <Setter Property="MinHeight" Value="0"/>
                        <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
                        <Setter Property="ScrollViewer.PanningMode" Value="VerticalFirst"/>
                        <Setter Property="Stylus.IsFlicksEnabled" Value="False"/>
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="{x:Type TextBox}">
                                    <ScrollViewer x:Name="PART_ContentHost" Background="Transparent" Focusable="False" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </TextBox.Style>
            </TextBox>
            <ToggleButton Grid.Column="1" IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}">
                <ToggleButton.Style>
                    <Style TargetType="{x:Type ToggleButton}">
                        <Setter Property="OverridesDefaultStyle" Value="True"/>
                        <Setter Property="IsTabStop" Value="False"/>
                        <Setter Property="Focusable" Value="False"/>
                        <Setter Property="ClickMode" Value="Press"/>
                        <Setter Property="Background" Value="Transparent"/>
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="{x:Type ToggleButton}">
                                    <Themes:ButtonChrome x:Name="Chrome" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}" RoundCorners="False" SnapsToDevicePixels="True" Width="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}">
                                        <Path x:Name="Arrow" Data="M0,0L3.5,4 7,0z" Fill="Black" HorizontalAlignment="Center" Margin="0,1,0,0" VerticalAlignment="Center"/>
                                    </Themes:ButtonChrome>
                                    <ControlTemplate.Triggers>
                                        <Trigger Property="IsChecked" Value="True">
                                            <Setter Property="RenderPressed" TargetName="Chrome" Value="True"/>
                                        </Trigger>
                                        <Trigger Property="IsEnabled" Value="False">
                                            <Setter Property="Fill" TargetName="Arrow" Value="#FFAFAFAF"/>
                                        </Trigger>
                                    </ControlTemplate.Triggers>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </ToggleButton.Style>
            </ToggleButton>
        </Grid>
        <ControlTemplate.Triggers>
            <Trigger Property="IsKeyboardFocusWithin" Value="True">
                <Setter Property="Foreground" Value="Black"/>
            </Trigger>
            <Trigger Property="IsDropDownOpen" Value="True">
                <Setter Property="RenderFocused" TargetName="Border" Value="True"/>
            </Trigger>
            <Trigger Property="HasItems" Value="False">
                <Setter Property="Height" TargetName="DropDownBorder" Value="95"/>
            </Trigger>
            <Trigger Property="IsEnabled" Value="False">
                <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                <Setter Property="Background" Value="#FFF4F4F4"/>
            </Trigger>
            <MultiTrigger>
                <MultiTrigger.Conditions>
                    <Condition Property="IsGrouping" Value="True"/>
                    <Condition>
                        <Condition.Value>
                            <System:Boolean>False</System:Boolean>
                        </Condition.Value>
                    </Condition>
                </MultiTrigger.Conditions>
                <Setter Property="ScrollViewer.CanContentScroll" Value="False"/>
            </MultiTrigger>
            <Trigger Property="HasDropShadow" SourceName="PART_Popup" Value="True">
                <Setter Property="Margin" TargetName="Shdw" Value="0,0,5,5"/>
                <Setter Property="Color" TargetName="Shdw" Value="#71000000"/>
            </Trigger>
            <Trigger Property="CanContentScroll" SourceName="DropDownScrollViewer" Value="False">
                <Setter Property="Canvas.Top" TargetName="OpaqueRect" Value="{Binding VerticalOffset, ElementName=DropDownScrollViewer}"/>
                <Setter Property="Canvas.Left" TargetName="OpaqueRect" Value="{Binding HorizontalOffset, ElementName=DropDownScrollViewer}"/>
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>
</Window.Resources>

In addition, an error is thrown as soon as I have inserted the template:

InvalidOperationException: Nicht-NULL-Wert für "Property" erforderlich.

EDIT:

I have the solution. It was quite easy :D I don't need a template. I just added triggers:

                <Style TargetType="ComboBox">
                    <Setter Property="Background" Value="Transparent"/>
                    <Setter Property="FontSize" Value="10"/>
                    <Setter Property="HorizontalAlignment" Value="Center"/>
                    <Setter Property="VerticalAlignment" Value="Center"/>
                    <Setter Property="Width" Value="115"/>
                    <Setter Property="Foreground" Value="Black"/>
                    <Setter Property="BorderBrush" Value="White"/>
                    <Setter Property="SelectedIndex" Value="0"/>
                    <Setter Property="HorizontalContentAlignment" Value="Center"/>
                    <Setter Property="IsEditable" Value="True"/>
                    <EventSetter Event="SelectionChanged" Handler="SelectionChanged"/>
                    <Style.Triggers>
                        <Trigger Property="IsEnabled" Value="False">
                            <Setter Property="Opacity" Value="0.4"/>
                        </Trigger>
                        <Trigger Property="SelectedIndex" Value="0">
                            <Setter Property="Background" Value="PaleGreen"/>
                            <Setter Property="Foreground" Value="Black"/>
                        </Trigger>
                        <Trigger Property="SelectedIndex" Value="1">
                            <Setter Property="Background" Value="Salmon"/>
                            <Setter Property="Foreground" Value="Black"/>
                        </Trigger>
                        <Trigger Property="SelectedIndex" Value="2">
                            <Setter Property="Background" Value="PaleTurquoise"/>
                            <Setter Property="Foreground" Value="Black"/>
                        </Trigger>
                        <Trigger Property="SelectedIndex" Value="3">
                            <Setter Property="Background" Value="Gold"/>
                            <Setter Property="Foreground" Value="Black"/>
                        </Trigger>
                        <Trigger Property="SelectedIndex" Value="4">
                            <Setter Property="Background" Value="Black"/>
                            <Setter Property="Foreground" Value="White"/>
                        </Trigger>
                        <Trigger Property="SelectedIndex" Value="5">
                            <Setter Property="Background" Value="Gray"/>
                            <Setter Property="Foreground" Value="Black"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>


问:
Python 3 Dictionary sorted with wrong output
I am currently doing an Assignment; however, I got some interesting output which confused me so much.

I am trying to sort the following dictionary:

```<code>result = {'A1': '9', 'A2': '14', 'A3': '16', 'A4': '0', 'B1': '53', 'B2': '267', 'B3': '75', 'B4': '22', 'C1': '19', 'C2': '407', 'C3': '171', 'C4': '56', 'C5': '10', 'D3': '47', 'D4': '34', 'D5': '10'}
</code>```

My sorting code with Python 3 is the following : (only sorted by value)

```<code>sortedList = [v for v in sorted(result.values())]
</code>```

The output is :

```<code>['0', '10', '10', '14', '16', '171', '19', '22', '267', '34', '407', '47', '53', '56', '75', '9']
</code>```

which is not fully sorted. The output is quite strange.

Why it is happened like this?
I have used another dict to test like this:

```<code>testD = {'A':'5','B': '9','c': '8','d': '6'}
</code>```

the output is right :

```<code>['5', '6', '8', '9']
</code>```

Is there something wrong with my result dictionary or is there something I am missing?

Body:
I am currently doing an Assignment; however, I got some interesting output which confused me so much.

I am trying to sort the following dictionary:

result = {'A1': '9', 'A2': '14', 'A3': '16', 'A4': '0', 'B1': '53', 'B2': '267', 'B3': '75', 'B4': '22', 'C1': '19', 'C2': '407', 'C3': '171', 'C4': '56', 'C5': '10', 'D3': '47', 'D4': '34', 'D5': '10'}

My sorting code with Python 3 is the following : (only sorted by value)

sortedList = [v for v in sorted(result.values())]

The output is :

['0', '10', '10', '14', '16', '171', '19', '22', '267', '34', '407', '47', '53', '56', '75', '9']

which is not fully sorted. The output is quite strange.

Why it is happened like this?
I have used another dict to test like this:

testD = {'A':'5','B': '9','c': '8','d': '6'}

the output is right :

['5', '6', '8', '9']

Is there something wrong with my result dictionary or is there something I am missing?

Body:
You can try this :

result = [{'A1': '9', 'A2': '14', 'A3': '16', 'A4': '0', 'B1': '53', 'B2': '267', 'B3': '75', 'B4': '22', 'C1': '19', 'C2': '407', 'C3': '171', 'C4': '56', 'C5': '10', 'D3': '47', 'D4': '34', 'D5': '10'}]

lst=[]

for item in result:
    for key in item.keys():
        lst.append(int(item.get(key)))

sortedList = [v for v in sorted(lst)]
print(sortedList)

Output: [0, 9, 10, 10, 14, 16, 19, 22, 34, 47, 53, 56, 75, 171, 267,
  407]


问:
How to achieve select and insert item as one transaction in DynamoDB
I am develping one application in which i am using AWS DynamoDB as database. but somewhere i am checking some conditions means selecting data from DynamoDB and check some conditions at java side and based on selected data i am inserting one item in DynamoDB table. I want selection and insertion of data as one transaction because if its not then i might get with two different items in a DynamoDB as it has to be one becuase java application running on multiple Ec2 instances. I am afraid of two simultaneous select requests. I am using Transaction API of dynamodb. Is there any suggestion? Or can it be implemented using DynamoDB Transaction API? I want to deploy java code on AWS EC2 instance.</p>

答: If you only care about atomicity of operations on individual items, use the UpdateItem API with condition expressions.</p>


问:
How can I create a common file between JavaScript and C/C++ for a constant?
I have a C++ program with the following in the header file:
#define VARIABLE_X 100

Also, a JavaScript file with the global: VARIABLE_X = 100;

These values will always need to be the same.

Instead of having to change them in both places (.h and .js), I need a common file where both can get this value, thus only needing to be changed in one place.

How can I create a common file between JavaScript and C/C++........ for a #define/constant ?

Thank You.

答:
You can't, for lots of reasons. However there is a simple solution: have a function that generates a Javascript file out of the constants, and dynamically load that in your Javascript.

Something as simple as:

```<code> printf("VARIABLE_X = %d;\n", VARIABLE_X);
</code>```

If it becomes a maintenance hassle, you can write a simple function to generate both the .h file and the .js file out of some common format.

Body:
You can't, for lots of reasons. However there is a simple solution: have a function that generates a Javascript file out of the constants, and dynamically load that in your Javascript.

Something as simple as:

 printf("VARIABLE_X = %d;\n", VARIABLE_X);

If it becomes a maintenance hassle, you can write a simple function to generate both the .h file and the .js file out of some common format.


问:
How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?
I want to downgrade php version from 7.1.1 to 5.6 in xampp 7.1.1. But I can't find any option.

答:
There is no option to downgrade XAMPP. XAMPP is hardcoded with specific PHP version to make sure all the modules are compatible and working properly. However if your project needs PHP 5.6, you can just install a older version of XAMPP with PHP 5.6 packaged into it.

Source: How to downgrade php from 5.5 to 5.3


问:
TypeError: 'float' object cannot be interpreted as an index
I am facing an issue which was not occurring before, maybe some rules have been changed. </p>

```<code>    Traceback (most recent call last)
    <ipython-input-3-f47687e192a7> in <module>()
          5 n_examples = X.shape[0]
          6 n_train = n_examples * 0.5
    ----> 7 train_idx = np.random.choice(range(0,n_examples), size=n_train, replace=False)
          8 test_idx = list(set(range(0,n_examples))-set(train_idx))
          9 X_train = X[train_idx]

    mtrand.pyx in mtrand.RandomState.choice (numpy/random/mtrand/mtrand.c:18822)()

    TypeError: 'float' object cannot be interpreted as an index
</code>```

答: The issue might be with  the range function, which comes with Python. Its arguments must be integers. n_train gets turned to a float when n_examples is multiplied by 0.5. You just need to reconvert it to an int like int(n_examples * 0.5). This is actually the correct thing to do. If you'd have 11 examples, it wouldn't make sense to have 5.5 training and test examples.

Body:
I am facing an issue which was not occurring before, maybe some rules have been changed.

    Traceback (most recent call last)
    <ipython-input-3-f47687e192a7> in <module>()
          5 n_examples = X.shape[0]
          6 n_train = n_examples * 0.5
    ----> 7 train_idx = np.random.choice(range(0,n_examples), size=n_train, replace=False)
          8 test_idx = list(set(range(0,n_examples))-set(train_idx))
          9 X_train = X[train_idx]

    mtrand.pyx in mtrand.RandomState.choice (numpy/random/mtrand/mtrand.c:18822)()

    TypeError: 'float' object cannot be interpreted as an index


问:
Interfacing Python with Fortran module by ctypes
I have this module in Fortran:

```<code>  MODULE utils
  IMPLICIT NONE
  PUBLIC
  INTEGER :: num_atom ! number of atoms in one configuration
    CONTAINS
      SUBROUTINE readin
      IMPLICIT NONE
      INTEGER :: iargc, ndim, i

     END SUBROUTINE readin

     SUBROUTINE convert
     IMPLICIT NONE
     REAL :: x,y,z
     END SUBROUTINE convert
</code>```

I compile it by:

```<code>gfortran -shared -fPIC -cpp -O2 thiscode.f90 -o somelib.so
</code>```

So, while trying to call the function "readin" from the following python code:

```<code>import os
_path = os.path.dirname(os.path.realpath(__file__)) + "/" + "somelib.so"

from ctypes import cdll, byref, c_int, c_double, c_char
lib_polint = cdll.LoadLibrary(_path)

def A():
    a = lib_polint.readin_

A()
</code>```

I can not identify the name of the function into "somelib.so" and the following error appear:

"undefined symbol: readin_".

If I remove the module and keep just the subroutine "readin", it works.
How to handle this?

答:
Use the Fortran interoperability with C to set the linker symbols to be anything you want

```<code> SUBROUTINE readin bind(C, name="readin")
  INTEGER :: iargc, ndim, i

 END SUBROUTINE readin
</code>```

Now the name of the subroutine as an externally visible C function will be just readin and you don't have to worry about the name mangling.

Without modules, you can sort of bet the name is _readin but it can also be readin_ or _readin_, but not that often.

With modules it is a lottery, the name mangling really differs between compilers. No point using thos _MOD_ symbols.

Body:
I have this module in Fortran:

  MODULE utils
  IMPLICIT NONE
  PUBLIC
  INTEGER :: num_atom ! number of atoms in one configuration
    CONTAINS
      SUBROUTINE readin
      IMPLICIT NONE
      INTEGER :: iargc, ndim, i

     END SUBROUTINE readin

     SUBROUTINE convert
     IMPLICIT NONE
     REAL :: x,y,z
     END SUBROUTINE convert

I compile it by:

gfortran -shared -fPIC -cpp -O2 thiscode.f90 -o somelib.so

So, while trying to call the function "readin" from the following python code:

import os
_path = os.path.dirname(os.path.realpath(__file__)) + "/" + "somelib.so"

from ctypes import cdll, byref, c_int, c_double, c_char
lib_polint = cdll.LoadLibrary(_path)

def A():
    a = lib_polint.readin_

A()

I can not identify the name of the function into "somelib.so" and the following error appear:

"undefined symbol: readin_".

If I remove the module and keep just the subroutine "readin", it works.
How to handle this?

Body:
Use the Fortran interoperability with C to set the linker symbols to be anything you want

 SUBROUTINE readin bind(C, name="readin")
  INTEGER :: iargc, ndim, i

 END SUBROUTINE readin

Now the name of the subroutine as an externally visible C function will be just readin and you don't have to worry about the name mangling.

Without modules, you can sort of bet the name is _readin but it can also be readin_ or _readin_, but not that often.

With modules it is a lottery, the name mangling really differs between compilers. No point using thos _MOD_ symbols.


问:
Converting dataframe column data to matrix using R
I have data in dataframe in following format

And i want to convert this data into a matrix like this, so that i can generate a graph out of it using R

Please advice how can i do this. Also if there are any packages available to generate a graph

[![enter image description here][3]][3]

答:
We can do this using base R by first converting the columns to factor with levels specified as the unique elements in both columns, then just do a table

```<code>df1[] <- lapply(df1, factor, levels = un1)
m1 <- table(df1[2:1])
class(m1) <- "matrix"
names(dimnames(m1)) <- NULL
m1
#             angle traingle rightangle similarangle pythogoreous end
#angle            0        0          0            0            0   0
#traingle         1        0          0            0            0   0
#rightangle       0        1          0            0            0   0
#similarangle     0        1          1            0            0   0
#pythogoreous     0        0          0            1            0   0
#end              0        0          0            0            1   0
</code>```

data

```<code>df1 <- structure(list(children.startnode = c("angle", "traingle", "traingle",
"rightangle", "similarangle", "pythogoreous"), children.endnode = c("traingle",
"rightangle", "similarangle", "similarangle", "pythogoreous",
"end")), .Names = c("children.startnode", "children.endnode"), row.names = c(NA,
 -6L), class = "data.frame")
</code>```

Body:
We can do this using base R by first converting the columns to factor with levels specified as the unique elements in both columns, then just do a table

df1[] <- lapply(df1, factor, levels = un1)
m1 <- table(df1[2:1])
class(m1) <- "matrix"
names(dimnames(m1)) <- NULL
m1
#             angle traingle rightangle similarangle pythogoreous end
#angle            0        0          0            0            0   0
#traingle         1        0          0            0            0   0
#rightangle       0        1          0            0            0   0
#similarangle     0        1          1            0            0   0
#pythogoreous     0        0          0            1            0   0
#end              0        0          0            0            1   0

data

df1 <- structure(list(children.startnode = c("angle", "traingle", "traingle",
"rightangle", "similarangle", "pythogoreous"), children.endnode = c("traingle",
"rightangle", "similarangle", "similarangle", "pythogoreous",
"end")), .Names = c("children.startnode", "children.endnode"), row.names = c(NA,
 -6L), class = "data.frame")


问:
How to select random three rows in Sybase against value check for other column
I have a table like below with approx 1 million rows.
col2 has all the alphabets(consonant + vowels)
col1 has random words

```<code>COL1          COL2 ......
val1          A
val2          A
val3          A
val4          A
val5          B
val6          B
val7          B
val8          B
.             .
.             .
.             .
.             .
.val100000    Z
</code>```

Now i want to get the result as random three rows with col2 in (A,E,I,O,U)

As a hack I used min and max function to get the two numbers.But that doesn't behold the random property.

Any help would be greatly appreciated here.

答:
you can use NEWID(),

like this

```<code>select *
from (select row_number() over (partition by col2 order by NEWID()) rownum, m.*      from myTable m
where m.col2 in (A,E,I,O,U)) sel
where sel.rownum=1
</code>```

Body:
I have a table like below with approx 1 million rows.
col2 has all the alphabets(consonant + vowels)
col1 has random words

COL1          COL2 ......
val1          A
val2          A
val3          A
val4          A
val5          B
val6          B
val7          B
val8          B
.             .
.             .
.             .
.             .
.val100000    Z

Now i want to get the result as random three rows with col2 in (A,E,I,O,U)

As a hack I used min and max function to get the two numbers.But that doesn't behold the random property.

Any help would be greatly appreciated here.

Body:
you can use NEWID(),

like this

select *
from (select row_number() over (partition by col2 order by NEWID()) rownum, m.*      from myTable m
where m.col2 in (A,E,I,O,U)) sel
where sel.rownum=1


问:
How to avoid forgetting making attributes private in class
I ALWAYS want to avoid that new attributes in a class are visible.
For java I can put private in front of the attributes. However because it's standard for me, I want to automate this set up via Eclipse code completion or error alert warnings.

How can I set up Eclipse so I can't forget anymore to make all the attributes of the classes private?

How can Eclipse assure that I never type following

```<code>package Test;

public class Test {
    String test;
}
</code>```

How can Eclipse furthermore assure that I always type private as follows?

```<code>package Test;

public class Test {
    private String test;
}
</code>```

答:
I don't know of a way for Eclipse to enforce private fields. As package visible fields are perfectly valid, Eclipse should not prevent you from creating them.

I see two ways that can help you in this scenario, though.

You can check your code after you have created it. Use the Unnecessary Code Detector plugin to check your code for unnecessary code. This will add a warning to all fields that have a visibility that's greater than required by your code.

You can create a code snippet in Eclipse Code Recommenders Snipmatch (It comes bundled in some Eclipse packages. If  is not installed in your Eclipse already, get it from the marketplace). Open Window > Show View > Other... > Code Recommenders > Snippets. Then select Add Snippet.... Define yourself a snippet that creates a private field.

In the Metadata tab, input a name, e.g. "private field" and a description, e.g. "Creates a private field". As location, select "Java type members". This ensures that this snippet is only available at places where you can create fields (i.e. not in method bodies). Leave the other fields blank.

Switch to the Raw Source tab, and input private ${type} ${name};. Save the snippet.

Place the cursor at a place where you want to create the field, press CTRL+ALT+SPACE and type "private field". Press enter to select your snippet. This will now insert the private modifier and allows you to specify the type and name of the field by tabbing between those options.

Once you've gotten used to this way of creating fields, it will make sure you never forget the modifier. You may even create additional snippets for other visibilities, should you need them.

For more help, refer to Snipmatch's manual. Disclaimer: I am one of Snipmatch's developers.

Body:
I ALWAYS want to avoid that new attributes in a class are visible.
For java I can put private in front of the attributes. However because it's standard for me, I want to automate this set up via Eclipse code completion or error alert warnings.

How can I set up Eclipse so I can't forget anymore to make all the attributes of the classes private?

How can Eclipse assure that I never type following

package Test;

public class Test {
    String test;
}

How can Eclipse furthermore assure that I always type private as follows?

package Test;

public class Test {
    private String test;
}


问:
How to make normal function to be returning in node.js
```<code>    function puts(error, stdout, stderr) {
    if (error) {
        console.log("error", "Error connecting");
        result = "Failed";
        console.log(result)
    }
    else {
        sys.puts(stdout)
        result = "Success"
        console.log(result)
    }
    }

//The calling function is mentioned as below:
app.get('/api/platforms1', function(req, res){
    exec("ping localhost",puts);
});
</code>```

<p>//I am working under mean stack.I have created a method to ping ip address and display their result.But now I want to display the result as a return function.How can we do it??</p>

答:
First of all sys is deprecated you can use util instead of it.

And if you want to get your result wherever, that thing you can do with callback, since Node.js nature is asynchronous.

Body:
    function puts(error, stdout, stderr) {
    if (error) {
        console.log("error", "Error connecting");
        result = "Failed";
        console.log(result)
    }
    else {
        sys.puts(stdout)
        result = "Success"
        console.log(result)
    }
    }

//The calling function is mentioned as below:
app.get('/api/platforms1', function(req, res){
    exec("ping localhost",puts);
});

//I am working under mean stack.I have created a method to ping ip address and display their result.But now I want to display the result as a return function.How can we do it??


问:
Using event of control under datalist
I have a datalist control which some controls(ex: button) are in it. I want to write some code into click event of button which is in the datalist control. But in the code behind page I can't see the name of controls into datalist. How can I solve this problem?</p>

答:
If you don't want to add a handler to all the child events, you could instead add your code to the OnItemCommand. </p>

```<code><asp:DataList id="DataList1" runat="server">
<ItemTemplate>
<asp:Button ID="btnDoSomething" Runat=server CommandName="DoSomething"
CommandArgument="<%# DataBinder.Eval(Container.DataItem, "SomeID")
%>"></asp:LinkButton>
</ItemTemplate>
</asp:DataList>

protected void DataList1_ItemCommand(
object source, DataListCommandEventArgs e)

{

  if (e.CommandName == "DoSomething")

  {

    //Do stuff

  }

}
</code>```

OwnerDisplayName: mavera

Title: Using event of control under datalist

Body:
If you don't want to add a handler to all the child events, you could instead add your code to the OnItemCommand.

<asp:DataList id="DataList1" runat="server">
<ItemTemplate>
<asp:Button ID="btnDoSomething" Runat=server CommandName="DoSomething"
CommandArgument="<%# DataBinder.Eval(Container.DataItem, "SomeID")
%>"></asp:LinkButton>
</ItemTemplate>
</asp:DataList>

protected void DataList1_ItemCommand(
object source, DataListCommandEventArgs e)

{

  if (e.CommandName == "DoSomething")

  {

    //Do stuff

  }

}

OwnerDisplayName: cmsjr


问:
How to draw simple bitmap text in a CALayer?
I would like to draw lots of strings to a CALayer using sprite-sheet like images containing about eighteen fixed-width (9x15, in 1x and retina sizes) characters. I don't need any sort of color changing, converting from system fonts, or even size changing. Just simple bitmap font rendering.

Here's my sprite-sheet I'm trying to use (1x size):

Image link

I've tried using CoreText framesetters and NSAttributedString.draw, but they were too slow and too fancy for the amount of text I need to update each frame and the look and feel I am trying to achieve.

How would I go about doing this?

答: @ToxicCaves64, maybe you can make your own true type font(.ttf) file, and put your eighteen fixed-width characters into your font file, then you can render your characters as text rather than images</p>


问:
getting error using latest chromedriver 2.28 - disconnected: received Inspector.detached event
Seem to be getting this error waiting for popup window. As I am watching the script execute the js button executes and popup window does open but my test fails with the following error:</p>

```<code>org.openqa.selenium.WebDriverException: disconnected: received    Inspector.detached event
(Session info: chrome=56.0.2924.87)
(Driver info: chromedriver=2.28.455520 (cc17746adff54984afff480136733114c6b3704b),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 3.20 seconds
Build info: version: '2.53.1', revision: 'a36b8b1cd5757287168e54b817830adce9b0158d', time: '2016-06-30 19:26:09'
System info: host: '*******', ip: '*******', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_91'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.28.455520
</code>```

答: Try updating your Chrome, I can see that your chromedriver version is 2.28 which is the most recent release and it should support Chrome v55-77, but updating Chrome might be a solution.</p>

Body:
Seem to be getting this error waiting for popup window. As I am watching the script execute the js button executes and popup window does open but my test fails with the following error:

org.openqa.selenium.WebDriverException: disconnected: received    Inspector.detached event
(Session info: chrome=56.0.2924.87)
(Driver info: chromedriver=2.28.455520 (cc17746adff54984afff480136733114c6b3704b),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 3.20 seconds
Build info: version: '2.53.1', revision: 'a36b8b1cd5757287168e54b817830adce9b0158d', time: '2016-06-30 19:26:09'
System info: host: '*******', ip: '*******', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_91'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.28.455520


问:
Mysql select statement using php array
Suppose I have an array as following

```<code>$sql_column_headings = array("Week Period", "Comments Approved", "Comment Replies");
</code>```

Number of items in the array is not fixed as they are selected from a 'select multiple lists'.

The list may consist more than 3 items and any number of items may be selected. Then submit button is pressed.
How can I create a select statement where the column headings are taken from the array mentioned above. Thanks.

答:
```<code>$sql_column_headings = array("Week Period", "Comments Approved", "Comment Replies");

    $columns = implode(",",$sql_column_headings);

    $sql = "SELECT '$columns' FROM table_name";

    $result = mysql_query($sql);
</code>```

Title: Mysql select statement using php array

Body:
Suppose I have an array as following

$sql_column_headings = array("Week Period", "Comments Approved", "Comment Replies");

Number of items in the array is not fixed as they are selected from a 'select multiple lists'.

The list may consist more than 3 items and any number of items may be selected. Then submit button is pressed.
How can I create a select statement where the column headings are taken from the array mentioned above. Thanks.


问:
Is it possible to mark permanently certain past day in Calendar view with some color or somehow
I have a simple android application which reminds me every day via scheduled local notification to drink water. For this purpose, I am using AlarmManager and BroadcastRreceiver. However, by clicking on the notification, an activity of my application starts which displays a message like "Did you drink enough water today?" and two buttons YES/NO. I have also another activity wich displays Calendar View. Depending on what I have chosen I want to mark somehow the current day in my Calendar View, if "YES" in green and if "NO" in red. So later when I run my application to be able to see in which days I drank enough water and in which not. Please check the attached picture to see what I mean.

example

I am not sure if this is possible with Calendar View at all but if not please advise how can I achieve it.

Thank you in advance!

答:
After a quick search I found this link on StackOverflow: highlighting specific date in calendar view without onClickListener

While it is not 100% what you are looking for, I think you can turn this into code to highlight the dates that you want. Since this code is for Java you have to do some translation to C# (which basically) adding some capitals. Also, you will need to put it into a custom renderer.

Another route you could take is to look for some custom component which has this functionality out-of-the-box. For instance I see that Telerik has a Calendar control which has some highlighting functionality.


问:
Setting the IP address of github as the origin url
I have a server that has DNS problems and cannot find "Github.com". I have to use Github's IP address instead. But when I try to use the IP address like this:

```<code>git remote set-url origin http://192.30.253.113/foo/bar.git
</code>```

when I try to push to origin this happens:

```<code>git push origin master
</code>```

fatal: unable to access 'https://192.30.253.113/foo/bar.git/': SSL: certificate subject name (github.com) does not match target host name '192.30.253.113'

答:
Git pull does not work, because Git verifies the SSL certificate and checks whether the hostname matches the name in the certificate. In your case the IP is not included in the certificate and, thus, you are getting this error.

An option could be to disable SSL (as described in https://stackoverflow.com/a/16869961/3906760), however, that would allow attackers to MitM your connection.

Instead of disabling SSL verification, why don't you add github.com to /etc/hosts (cf. https://ubuntuforums.org/showthread.php?t=3407), then SSL certificate validation would still work.

Body:
I have a server that has DNS problems and cannot find "Github.com". I have to use Github's IP address instead. But when I try to use the IP address like this:

git remote set-url origin http://192.30.253.113/foo/bar.git

when I try to push to origin this happens:

git push origin master

fatal: unable to access 'https://192.30.253.113/foo/bar.git/': SSL: certificate subject name (github.com) does not match target host name '192.30.253.113'


问:
search on ng-repeat by grouping the items
I have created ng-repeat by group on which I am applying the filter, everything is working fine but the search functionality is not doing well, means when I am searching an item then its displaying the item but along with other group names are displaying which I want to hide.
when I search for an item then it should display the item along with the group and hide all the groups and other items.
Below is the

{{ key }}

{{pop.EmpName}}

Id: {{pop.EmpNo}}

Desig: {{pop.Designation | titlecase}}

```

code.

答:
Try using this and add your filter code in it

HTML

```<code><input type='text' placeholder='look for' ng-model='lookfor'>
</code>```

Jsfiddle demo

Body:
I have created ng-repeat by group on which I am applying the filter, everything is working fine but the search functionality is not doing well, means when I am searching an item then its displaying the item but along with other group names are displaying which I want to hide.
when I search for an item then it should display the item along with the group and hide all the groups and other items.
Below is the

{{ key }}

{{pop.EmpName}}

Id: {{pop.EmpNo}}

Desig: {{pop.Designation | titlecase}}

code.

Body:
Try using this and add your filter code in it

HTML

<input type='text' placeholder='look for' ng-model='lookfor'>

Jsfiddle demo


问:
Print the hash name of a hash of hashes of hashes etc
So I have a massive hash of hashes.

```<code>$VAR1 = {
          'Peti Bar' => {
                          'Mathematics' => 82,
                          'Art' => 99,
                          'Literature' => 88
                        },
          'Foo Bar' => {
                         'Mathematics' => 97,
                         'Literature' => 67
                       }
        };
</code>```

There's an example I found on the web.

What I want to print is 'Peti Bar' and 'Foo Bar', but it's not quite that simple. Imagine Mathematics being it's own hash within that hash, etc. So I'd wanta to print 'Peti Bar' -> 'Mathematics' -> 'AnotherHash'
'Foo Bar' -> 'Literature' -> 'Anotherhash'

I guess maybe what I'm asking is print the hash of hashes without key/value of each respective hash.

答:
The easiest way is probably to use a recursive function to go through the top-level hash and any subhashes, printing any keys that have subhashes before descending into the subhash:

```<code>#!/usr/bin/env perl

use strict;
use warnings;
use 5.010;

my %bighash = (
  'Peti Bar' => {
    'Mathematics' => {
      'Arithmetic' => 7,
      'Geometry'   => 8,
      'Calculus'   => 9,
    },
    'Art'        => 99,
    'Literature' => 88
  },
  'Foo Bar' => {
    'Mathematics' => 97,
    'Literature'  => 67
  }
);

dump_hash(\%bighash);

sub dump_hash {
  my $hashref = shift;
  my @parents = @_;

  return unless $hashref && ref $hashref eq 'HASH';

  for my $key (sort keys %$hashref) {
    my $val = $hashref->{$key};
    next unless ref $val eq 'HASH';
    say join ' -> ', @parents, $key;
    dump_hash($val, @parents, $key);
  }
}
</code>```

Output:

```<code>Foo Bar
Peti Bar
Peti Bar -> Mathematics
</code>```

Body:
So I have a massive hash of hashes.

$VAR1 = {
          'Peti Bar' => {
                          'Mathematics' => 82,
                          'Art' => 99,
                          'Literature' => 88
                        },
          'Foo Bar' => {
                         'Mathematics' => 97,
                         'Literature' => 67
                       }
        };

There's an example I found on the web.

What I want to print is 'Peti Bar' and 'Foo Bar', but it's not quite that simple. Imagine Mathematics being it's own hash within that hash, etc. So I'd wanta to print 'Peti Bar' -> 'Mathematics' -> 'AnotherHash'
'Foo Bar' -> 'Literature' -> 'Anotherhash'

I guess maybe what I'm asking is print the hash of hashes without key/value of each respective hash.

Body:
The easiest way is probably to use a recursive function to go through the top-level hash and any subhashes, printing any keys that have subhashes before descending into the subhash:

#!/usr/bin/env perl

use strict;
use warnings;
use 5.010;

my %bighash = (
  'Peti Bar' => {
    'Mathematics' => {
      'Arithmetic' => 7,
      'Geometry'   => 8,
      'Calculus'   => 9,
    },
    'Art'        => 99,
    'Literature' => 88
  },
  'Foo Bar' => {
    'Mathematics' => 97,
    'Literature'  => 67
  }
);

dump_hash(\%bighash);

sub dump_hash {
  my $hashref = shift;
  my @parents = @_;

  return unless $hashref && ref $hashref eq 'HASH';

  for my $key (sort keys %$hashref) {
    my $val = $hashref->{$key};
    next unless ref $val eq 'HASH';
    say join ' -> ', @parents, $key;
    dump_hash($val, @parents, $key);
  }
}

Output:

Foo Bar
Peti Bar
Peti Bar -> Mathematics


问:
How to handle error message in Selenium
I'm automating an application using Selenium so what is happening is when the script runs and it hits the login button an error comes up in the top right which stops further execution. What I want is need a way by which i can capture this "error message" so that I would know the cause of the halt of the application execution.I'm attaching the image of error and also the code that I have tried but it didnt work.

```<code>@FindBy(xpath="//*[@id='toast-container']/div/div]")
    static WebElement errorMessage;
    WebDriverWait wait = new WebDriverWait(CommonBrowserSetup.driver, 15);
            wait.until(ExpectedConditions.visibilityOf(errorMessage));
            String mess=errorMessage.getText();
            System.out.println(mess);
</code>```

答:
If you want to capture Unknown error occured
Just try the following code and let me know if it works for you.
After the login button is clicked add the following:

```<code>WebElement Error =  driver.findElement(By.xpath("//div[contains(text(),'Unknown error occured')]"));
            if(Error.isDisplayed()){
                String Errormessage = Error.getText();
                System.out.println(Errormessage);
            }
</code>```

Title: How to handle error message in Selenium

Body:
I'm automating an application using Selenium so what is happening is when the script runs and it hits the login button an error comes up in the top right which stops further execution. What I want is need a way by which i can capture this "error message" so that I would know the cause of the halt of the application execution.I'm attaching the image of error and also the code that I have tried but it didnt work.

@FindBy(xpath="//*[@id='toast-container']/div/div]")
    static WebElement errorMessage;
    WebDriverWait wait = new WebDriverWait(CommonBrowserSetup.driver, 15);
            wait.until(ExpectedConditions.visibilityOf(errorMessage));
            String mess=errorMessage.getText();
            System.out.println(mess);

Body:
If you want to capture Unknown error occured
Just try the following code and let me know if it works for you.
After the login button is clicked add the following:

WebElement Error =  driver.findElement(By.xpath("//div[contains(text(),'Unknown error occured')]"));
            if(Error.isDisplayed()){
                String Errormessage = Error.getText();
                System.out.println(Errormessage);
            }


问:
PHP merge and rearrange 2 or more arrays
It will be 2 or more arrays come out from foreach loop. Like following

```<code>array1
    [0] => Array
        (
            [0] => 1207
            [1] => 4
            [2] => haha.mp4
        )

    [1] => Array
        (
            [0] => 1208
            [1] => 4
            [2] => hehe.mp4
        )

array2
   [0] => Array
        (
            [0] => 1209
            [1] => 16
            [2] => SampleVideo.mp4
        )

    [1] => Array
        (
            [0] => 1210
            [1] => 16
            [2] => 295.mp4
        )
</code>```

I want to get same index value from these 2 arrays and merge these array like that.

```<code>**FinalArray = array1[0],array2[0],array1[1],array2[1]**
</code>```

E.g

```<code>FinalArray

    [0] => Array
        (
            [0] => 1207
            [1] => 4
            [2] => haha.mp4
        )
    [1] => Array
        (
            [0] => 1209
            [1] => 16
            [2] => SampleVideo.mp4
        )

    [2] => Array
        (
            [0] => 1208
            [1] => 4
            [2] => hehe.mp4
        )

    [3] => Array
        (
            [0] => 1210
            [1] => 16
            [2] => 295.mp4
        )
</code>```

please help how to get same index values and merge that 2 arrays. Thanks

答:
To get finalArray with elements order array0[0],array1[0],array0[1],array1[1] first calculate $max_elements and then perform nested loop with check if element with $i in that array exist:

```<code>$arrays = [$array0, $array1];
$max_elements = 0;
foreach($arrays as $array){
    $max_elements = max($max_elements, count($array));
}
$merged = []
for($i = 0; $i < $max_elements; $i++){
    foreach($arrays as $array){
        if($array[$i]){
            $merged[] = $array[$i];
        }
    }
}
</code>```

Body:
It will be 2 or more arrays come out from foreach loop. Like following

array1
    [0] => Array
        (
            [0] => 1207
            [1] => 4
            [2] => haha.mp4
        )

    [1] => Array
        (
            [0] => 1208
            [1] => 4
            [2] => hehe.mp4
        )

array2
   [0] => Array
        (
            [0] => 1209
            [1] => 16
            [2] => SampleVideo.mp4
        )

    [1] => Array
        (
            [0] => 1210
            [1] => 16
            [2] => 295.mp4
        )

I want to get same index value from these 2 arrays and merge these array like that.

**FinalArray = array1[0],array2[0],array1[1],array2[1]**

E.g

FinalArray

    [0] => Array
        (
            [0] => 1207
            [1] => 4
            [2] => haha.mp4
        )
    [1] => Array
        (
            [0] => 1209
            [1] => 16
            [2] => SampleVideo.mp4
        )

    [2] => Array
        (
            [0] => 1208
            [1] => 4
            [2] => hehe.mp4
        )

    [3] => Array
        (
            [0] => 1210
            [1] => 16
            [2] => 295.mp4
        )

please help how to get same index values and merge that 2 arrays. Thanks

Body:
To get finalArray with elements order array0[0],array1[0],array0[1],array1[1] first calculate $max_elements and then perform nested loop with check if element with $i in that array exist:

$arrays = [$array0, $array1];
$max_elements = 0;
foreach($arrays as $array){
    $max_elements = max($max_elements, count($array));
}
$merged = []
for($i = 0; $i < $max_elements; $i++){
    foreach($arrays as $array){
        if($array[$i]){
            $merged[] = $array[$i];
        }
    }
}


问:
How do I change the time zone of a Google Cloud Windows Server 2016 VM?
When I try to change the time zone of a Windows Server 2016 VM on Google Cloud Platform I get a permissions error. My user has full admin privileges. Is it possible?

答: You need to change the timezone through the Server Manager, not the control panel. Nothing to do with GCP.</p>


问:
How to make QWebEngineView go fullscreen?
I have the following code, and I want to make my QWebEngineView (Qt 5.8) to go full screen.

My WebView class is contained in a QTabWidget, so it just fills up the tab, not entire screen.

How can I make it go fullscreen?

```<code>class WebView:public QObject{
    void acceptFullScreen(QWebEngineFullScreenRequest request){
        request.accept();
    }

public:
    char* home_page;
    QWebEngineView* view=new QWebEngineView();
    WebView(char* page=(char*)"file:///home/tarptaeya/Desktop/Crusta_Prototype_python/about.html"){
        this->home_page=page;
        createWebView();
        this->view->settings()->setAttribute(QWebEngineSettings::FullScreenSupportEnabled,true);
        this->view->settings()->setAttribute(QWebEngineSettings::PluginsEnabled,true);
        this->view->settings()->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows,true);
        connect(this->view->page(),&QWebEnginePage::fullScreenRequested,this,&WebView::acceptFullScreen);
    }
    void createWebView(){
        this->view->load(QUrl(this->home_page));
    }
}
</code>```

答:
If your widget is inside a tab, then it can't be full screen directly. You have two options:

Remove it from the tab when you want to make it fullscreen (for example, if you have a fullscreen button) and make it a standalone widget. Insert it back into the QTabWidget when quitting the fullscreen mode.

Make the QTabWidget to fulfill the screen.

In both cases you can use something like this to make it occupy the whole screen:

```<code>// Replace the 0 with the screen index
const auto windowGeometry = qApp->desktop()->availableGeometry(0);
widget.move(windowGeometry.topLeft());
widget.resize(windowGeometry.size());
</code>```

It will fulfill the screen but will keep the taskbar visible (in my experience this is highly recommended, so the user can easily switch to other tasks). If you want to cover it, just use geometry() instead of the availableGeometry() method.

EDIT in both cases the widget will have the windows manager frame. If you want to remove it you may try setting the Qt::FramelessWindowHint flag. Take into consideration that removing frame may also make some actions unavailable (at least on Windows) such as moving, resizing, snapping...

Body:
I have the following code, and I want to make my QWebEngineView (Qt 5.8) to go full screen.

My WebView class is contained in a QTabWidget, so it just fills up the tab, not entire screen.

How can I make it go fullscreen?

class WebView:public QObject{
    void acceptFullScreen(QWebEngineFullScreenRequest request){
        request.accept();
    }

public:
    char* home_page;
    QWebEngineView* view=new QWebEngineView();
    WebView(char* page=(char*)"file:///home/tarptaeya/Desktop/Crusta_Prototype_python/about.html"){
        this->home_page=page;
        createWebView();
        this->view->settings()->setAttribute(QWebEngineSettings::FullScreenSupportEnabled,true);
        this->view->settings()->setAttribute(QWebEngineSettings::PluginsEnabled,true);
        this->view->settings()->setAttribute(QWebEngineSettings::JavascriptCanOpenWindows,true);
        connect(this->view->page(),&QWebEnginePage::fullScreenRequested,this,&WebView::acceptFullScreen);
    }
    void createWebView(){
        this->view->load(QUrl(this->home_page));
    }
}

Body:
If your widget is inside a tab, then it can't be full screen directly. You have two options:

Remove it from the tab when you want to make it fullscreen (for example, if you have a fullscreen button) and make it a standalone widget. Insert it back into the QTabWidget when quitting the fullscreen mode.

Make the QTabWidget to fulfill the screen.

In both cases you can use something like this to make it occupy the whole screen:

// Replace the 0 with the screen index
const auto windowGeometry = qApp->desktop()->availableGeometry(0);
widget.move(windowGeometry.topLeft());
widget.resize(windowGeometry.size());

It will fulfill the screen but will keep the taskbar visible (in my experience this is highly recommended, so the user can easily switch to other tasks). If you want to cover it, just use geometry() instead of the availableGeometry() method.

EDIT in both cases the widget will have the windows manager frame. If you want to remove it you may try setting the Qt::FramelessWindowHint flag. Take into consideration that removing frame may also make some actions unavailable (at least on Windows) such as moving, resizing, snapping...


问:
SOAP WS-Addressing property with Wss4jSecurityInterceptor with Java
Hi I create code for consume SOAP service,

For Authentication Header I used Wss4jSecurityInterceptor for set Header information.

I am getting fail response like below

```<code> Exception in thread "main" org.springframework.ws.soap.client.SoapFaultClientException: Required element {http://www.w3.org/2005/08/addressing}Action is missing
</code>```

My Configuration code as below

```<code>@Configuration
public class SoapClientConfig {

    @Bean
    public Jaxb2Marshaller marshaller() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setContextPath("com.xyz.client");
        marshaller.setCheckForXmlRootElement(false);
        return marshaller;
    }

    @Bean
    public MyClient myClient(Jaxb2Marshaller marshaller) throws Exception {
        MyClient client = new MyClient();
        client.setDefaultUri("https://localhost:8080/ws/service");
        client.setMarshaller(marshaller);
        client.setUnmarshaller(marshaller);

        ClientInterceptor[] interceptors = new ClientInterceptor[] {securityInterceptor()};

        client.setInterceptors(interceptors);
        return client;
    }

    @Bean
    public Wss4jSecurityInterceptor securityInterceptor() {
        Wss4jSecurityInterceptor wss4jSecurityInterceptor = new Wss4jSecurityInterceptor();
        wss4jSecurityInterceptor.setSecurementActions("UsernameToken");
        wss4jSecurityInterceptor.setSecurementMustUnderstand(true);
        wss4jSecurityInterceptor.setSecurementPasswordType("PasswordText");
        wss4jSecurityInterceptor.setSecurementUsername("XXXXXXXXXXX");
        wss4jSecurityInterceptor.setSecurementPassword("XXXXXXXX");
        return wss4jSecurityInterceptor;
    }
}
</code>```

Can anyone suggest me what I am missing?

If I try from SOAPUI its working fine. If I set WS-Addressing=false from SOAPUI also giving me same error, So Issue with set WS-Addressing property with above code. How can I?

答:
Long time before worked on populating SOAP Header with dynamic value, for that you need to work on constructing the xml nodes using callback object...WebServiceMessageCallback

http://docs.spring.io/spring-ws/site/reference/html/client.html#d5e1848

In my scenario I need to construct the node using QName (Java) Node by Node.

Body:
Hi I create code for consume SOAP service,

For Authentication Header I used Wss4jSecurityInterceptor for set Header information.

I am getting fail response like below

 Exception in thread "main" org.springframework.ws.soap.client.SoapFaultClientException: Required element {http://www.w3.org/2005/08/addressing}Action is missing

My Configuration code as below

@Configuration
public class SoapClientConfig {

    @Bean
    public Jaxb2Marshaller marshaller() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setContextPath("com.xyz.client");
        marshaller.setCheckForXmlRootElement(false);
        return marshaller;
    }

    @Bean
    public MyClient myClient(Jaxb2Marshaller marshaller) throws Exception {
        MyClient client = new MyClient();
        client.setDefaultUri("https://localhost:8080/ws/service");
        client.setMarshaller(marshaller);
        client.setUnmarshaller(marshaller);

        ClientInterceptor[] interceptors = new ClientInterceptor[] {securityInterceptor()};

        client.setInterceptors(interceptors);
        return client;
    }

    @Bean
    public Wss4jSecurityInterceptor securityInterceptor() {
        Wss4jSecurityInterceptor wss4jSecurityInterceptor = new Wss4jSecurityInterceptor();
        wss4jSecurityInterceptor.setSecurementActions("UsernameToken");
        wss4jSecurityInterceptor.setSecurementMustUnderstand(true);
        wss4jSecurityInterceptor.setSecurementPasswordType("PasswordText");
        wss4jSecurityInterceptor.setSecurementUsername("XXXXXXXXXXX");
        wss4jSecurityInterceptor.setSecurementPassword("XXXXXXXX");
        return wss4jSecurityInterceptor;
    }
}

Can anyone suggest me what I am missing?

If I try from SOAPUI its working fine. If I set WS-Addressing=false from SOAPUI also giving me same error, So Issue with set WS-Addressing property with above code. How can I?


问:
Avoiding complex if statements
I have the following function

```<code>const getVal = (type, a, b, val) => {
    if(type) {
        if(a && b) {
            return val;
        }else if(a) {
            return toPercent(val);
        }else{
            return undefined;
        }
    }
    return toPx(val);
}
</code>```

is there a better way to express this? How would such a code be written in functional programming style

答:
With functional programming there is a technique called currying which you can use. So you basically have a function that takes 'type' and returns a new function that takes 'val'...etc.

```<code>const toPercent = (val) => {
  return 'toPercent: ' + val;
};
const toPX = (val) => {
  return 'toPx: ' + val;
};

const getValByFlags = (a, b, val) => {
  if (a) {
    return b
      ? val
      : toPercent(val);
  }
  return undefined;
};

const getValByType = (type) => {
  if (!type) return toPX;
  return (val) => {
    return (a, b) => {
      return getValByFlags(a, b, val);
    };
  };
};

let a = getValByType('a')(3)(true, true);
let b = getValByType()(3);
let c = getValByType('a')(3)(true, false);
let d = getValByType('a')(3)(false, false);
</code>```

or generically

```<code>let getVal = getValByType(type);
let getValByConditions = getVal(val);
let resVal = type
  ? getValByConditions(cond1, cond2)
  : getValByConditions;
</code>```

Title: Avoiding complex if statements

Body:
I have the following function

const getVal = (type, a, b, val) => {
    if(type) {
        if(a && b) {
            return val;
        }else if(a) {
            return toPercent(val);
        }else{
            return undefined;
        }
    }
    return toPx(val);
}

is there a better way to express this? How would such a code be written in functional programming style

Body:
With functional programming there is a technique called currying which you can use. So you basically have a function that takes 'type' and returns a new function that takes 'val'...etc.

const toPercent = (val) => {
  return 'toPercent: ' + val;
};
const toPX = (val) => {
  return 'toPx: ' + val;
};

const getValByFlags = (a, b, val) => {
  if (a) {
    return b
      ? val
      : toPercent(val);
  }
  return undefined;
};

const getValByType = (type) => {
  if (!type) return toPX;
  return (val) => {
    return (a, b) => {
      return getValByFlags(a, b, val);
    };
  };
};

let a = getValByType('a')(3)(true, true);
let b = getValByType()(3);
let c = getValByType('a')(3)(true, false);
let d = getValByType('a')(3)(false, false);

or generically

let getVal = getValByType(type);
let getValByConditions = getVal(val);
let resVal = type
  ? getValByConditions(cond1, cond2)
  : getValByConditions;


问:
Update a column with the result-dataset-count of a stored procedure
I have a table #data which has the columns Id and Count. In addition I have a stored procedure MyProc which accepts a parameter @id (equals the Id column) and returns a dataset (the count equals the Count column).

My goal is to assign the Count column from Id with MyProc without a cursor.

I know, something like this does not work:

```<code>UPDATE d
SET Count = (SELECT COUNT(*) FROM (EXEC MyProc d.Id))
FROM #data AS d
</code>```

Is there a syntax I do not know or is a cursor the only option to achieve this?

PS: It is a code quality and performance problem for me. Calling the stored procedure would be the easiest way without repeating 50 lines of SQL but a cursor slows it down.

答:
I believe you can make use of the below query :

```<code>    IF OBJECT_ID('dbo.data') IS NOT NULL DROP TABLE data;
    IF OBJECT_ID('dbo.MyFunct') IS NOT NULL DROP FUNCTION dbo.MyFunct;
    GO

    CREATE TABLE data
    (
      ID      int,
      [Count] int
    );

    INSERT data VALUES (1,5), (1,10), (2,3), (4,6);
    GO

    UPDATE d
    SET d.[Count] = f.CNT
    FROM
        (SELECT ID,COUNT(id) AS CNT FROM data GROUP BY ID) f
    INNER JOIN data d ON f.ID = d.ID
</code>```

I couldn't find a way to use Stored procedure. Needed you can use Table valued function:

```<code>    CREATE FUNCTION dbo.MyFunct(@id INT)
    RETURNS @i TABLE
    (ID INT , CNT INT)
    AS
    BEGIN
        INSERT INTO @i
        SELECT ID,COUNT(id) AS CNT FROM data GROUP BY ID
    RETURN
    END;
    GO

    UPDATE d
    SET d.[Count] = f.CNT
    FROM dbo.MyFunct(1) f INNER JOIN data d ON f.ID = d.ID
</code>```

Body:
I have a table #data which has the columns Id and Count. In addition I have a stored procedure MyProc which accepts a parameter @id (equals the Id column) and returns a dataset (the count equals the Count column).

My goal is to assign the Count column from Id with MyProc without a cursor.

I know, something like this does not work:

UPDATE d
SET Count = (SELECT COUNT(*) FROM (EXEC MyProc d.Id))
FROM #data AS d

Is there a syntax I do not know or is a cursor the only option to achieve this?

PS: It is a code quality and performance problem for me. Calling the stored procedure would be the easiest way without repeating 50 lines of SQL but a cursor slows it down.

Body:
I believe you can make use of the below query :

    IF OBJECT_ID('dbo.data') IS NOT NULL DROP TABLE data;
    IF OBJECT_ID('dbo.MyFunct') IS NOT NULL DROP FUNCTION dbo.MyFunct;
    GO

    CREATE TABLE data
    (
      ID      int,
      [Count] int
    );

    INSERT data VALUES (1,5), (1,10), (2,3), (4,6);
    GO

    UPDATE d
    SET d.[Count] = f.CNT
    FROM
        (SELECT ID,COUNT(id) AS CNT FROM data GROUP BY ID) f
    INNER JOIN data d ON f.ID = d.ID

I couldn't find a way to use Stored procedure. Needed you can use Table valued function:

    CREATE FUNCTION dbo.MyFunct(@id INT)
    RETURNS @i TABLE
    (ID INT , CNT INT)
    AS
    BEGIN
        INSERT INTO @i
        SELECT ID,COUNT(id) AS CNT FROM data GROUP BY ID
    RETURN
    END;
    GO

    UPDATE d
    SET d.[Count] = f.CNT
    FROM dbo.MyFunct(1) f INNER JOIN data d ON f.ID = d.ID