text:
Q: Creating an IIS site through setup I want to create an IIS site with setup and deployment. How can I create an installer that creates an IIS site?

A: Unfortunately even in Visual Studio 2010 there still isn't a way to do this without resorting to custom install actions.


text:
Q: similar to last() in sql, what can i use in derby database? Select Last(column_name) from table_name will return the last value in the column in standard SQL. What is a similar query that will work in derby to fetch the last value in the column?
Please find the sample table below: 'secondcol' is the column name in the table.
          secondcol
          33
          45
          78

Select Last(secondcol) from table_name in sql will return 78 as output. If i want to get similar output in javadb/derby database, how can i query it? I don't want to change any order in the column values.

A: To select last row in table is little bit different then it is in pure SQL:
SQL:
SELECT * FROM tableName ORDER BY id DESC LIMIT 1;

DERBY:
SELECT * FROM tablename ORDER BY id DESC FETCH FIRST ROW ONLY;

Have a nice day ;)

A: Is there some unique key on the table where you could form the question as "give me the secondcol value on the row with the max key value"?  If so, there is a technique that will work in any database engine - the idea is to concatenate the key plus any desired result data, perform a min/max, then extract the result data.
See here and here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: WPF ComboBox Bound to Collection of UserControls Not Showing Selected Item's Text I have a ComboBox that is bound to an ObservableCollection of custom UserControls. Each user control has a Tag value set and the ComboBox' DisplayMemberPath is set to "Tag". This correctly displays the Tag of each UserControl in the drop down list when the ComboBox is clicked, however when an item in the list is selected and the drop down list is closed, the ComboBox displays nothing in the button.
If I swap out a UserControl for a standard WPF control such as a TextBox, then it correctly displays the Tag value of the selected item, so it is something related to binding to a UserControl vs a standard WPF control. Also, if I set the IsEditable to True, then the editable TextBox displays the Tag correctly, but I don't want the text to be editable.
How do I get the Selected item to display when the ComboBox is not expanded?
Here is some sample code that replicates the issue:
(Note: The sample code is taken out of the context of the application it is running in so it looks a bit weird in what it is trying to do, but it still results in the same symptoms).
MyUC.xaml
<UserControl x:Class="ComboboxTest.MyUC"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <TextBox />
    </Grid>
</UserControl>

Window1.xaml
<Window x:Class="ComboboxTest.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:ComboboxTest"
        Title="Window1" Height="300" Width="300"
        DataContext="{Binding RelativeSource={RelativeSource Self}}">
<StackPanel>
    <StackPanel Name="ControlsHolder">
        <TextBox Tag="Box 1" Text="This is in Box 1" />
        <TextBox Tag="Box 2" Text="This is in Box 2" />
        <local:MyUC Tag="UC 1" />
        <local:MyUC Tag="UC 2" />
    </StackPanel>
    <Grid>
        <ComboBox Grid.Column="1"
              Margin="5,0"
              Name="MyComboBox"
              ItemsSource="{Binding MyControls}"
              DisplayMemberPath="Tag"
              MinWidth="120"/>
    </Grid>
</StackPanel>

Window1.cs
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace ComboboxTest
{
    public partial class Window1 : Window, INotifyPropertyChanged
    {
        ObservableCollection<MyUC> myControls = new ObservableCollection<MyUC>();

        public Window1()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(Window1_Loaded);
        }

        void Window1_Loaded(object sender, RoutedEventArgs e)
        {
            myControls.Clear();

            foreach (UIElement uiElement in this.ControlsHolder.Children)
            {
                MyUC tb = uiElement as MyUC;

                if (tb != null)
                {
                    myControls.Add(tb);
                }
            }

            RaisePropertyChanged("MyControls");
        }

        public ObservableCollection<MyUC> MyControls
        {
            get
            {
                return this.myControls;
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void RaisePropertyChanged(string p)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(p));
            }
        }
    }
}

This app appears as:
ComboBox with Drop Down Visible http://img229.imageshack.us/img229/5597/comboboxtestexpanded.png
And when "UC 2" is selected it appears as:
ComboBox with selected item not visible http://img692.imageshack.us/img692/4362/comboboxtestuc2selected.png

A: Binding a list of UIElements is not a good idea. Try using a wrapper class :
public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
        this.Loaded += new RoutedEventHandler(Window1_Loaded);
        MyComboBox.ItemsSource = MyControls;
    }

    ObservableCollection<Wrapper> myControls = new ObservableCollection<Wrapper>();

    void Window1_Loaded(object sender, RoutedEventArgs e)
    {
        myControls.Clear();

        foreach (UIElement uiElement in this.ControlsHolder.Children)
        {
            MyUC tb = uiElement as MyUC;

            if (tb != null)
            {
                myControls.Add(new Wrapper(tb));
            }
        }

        RaisePropertyChanged("MyControls");
    }

    public ObservableCollection<Wrapper> MyControls
    {
        get
        {
            return this.myControls;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void RaisePropertyChanged(string p)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(p));
        }
    }
}

public class Wrapper
{
    public UserControl Control { get; protected set; }

    public Wrapper(UserControl control)
    {
        Control = control;
    }

    public Object Tag
    {
        get { return Control.Tag; }
    }
}


text:
Q: number of primes of the form |$n^2 - 6n + 5$|? How can I find the number of primes of the form $|n^2 - 6n + 5|$ where $n$ is an integer? Through trial and error, I have found $n = 6$ (this one is obvious), and $2$. Are there any more, and what is a smarter way to solve this question?

A: The first thing I did when I saw your question was compute about a dozen values for small $n$ and look them up in the OEIS, which gave me A028347 and the formula $n^2 - 4$. Clearly for $n^2 - 4$ to be prime you need $n$ to be odd. Slightly less obvious, you need for $n$ to be a multiple of 3, because otherwise $n^2 \equiv 1 \pmod 3$. These conditions are necessary but not sufficient.
Digging a little further, we find that $n^2 - 4 = (n - 2)(n + 2)$: this is clearest when the formula gives you semiprimes with prime factors 4 apart, e.g., $19 \times 23$, $37 \times 41$, $43 \times 47$.
So you have found all the prime values already.


text:
Q: Its possible use outputDirectory two times in my pom.xml? I have one problem in my java project. Basicaly, I want build and compile my project to export jar file in two distinct directories. It's possible? Because method I am using is not working in my pom.xml
I was trying to use this code below, but always in the second outputDirectory, it didn't work.

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>3.3.0</version>
                <executions>
                    <execution>
                        <id>copy-resources</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>C:\My\First\Directory\Folder</outputDirectory>
                            <outputDirectory>C:\My\Second\Directory\Folder</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>C:\Local\Of\My\Jar\</directory>
                                    <filtering>false</filtering>
                                    <includes>
                                        <include>myJar.jar</include>
                                    </includes>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
     </build>

A: You can only copy to one directory.
But I never heard that somebody needed to copy to a second directory.
So you probably won't need it.


text:
Q: Can ASP.NET automatically generate code from an API definition file? On the Swagger page of many APIs (web services) there is a documentation file that includes information about API object properties (their type, whether they are required or not, etc.)  It seems this data could be used to automatically generate create/read/update/delete code or possibly code for an API service, for interactions with the API endpoints.
I was wondering if this is possible in .NET 6.0 (or other versions), Visual Studio Professional, etc.   Thank you in advance.

A: First of all, it is certain that ASP.net can fully realize the automatic generation of API documents. It can satisfy your test of the backend interface.
Proceed as follows:
1.    Create a Web API project.
2.    Modify the default API routing configuration
Why modify it? Because the default route of each Controller is assigned to "api/{controller}/{id}", the default generated controller is similar to the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace WebAPI.Controllers
{
    public class ValuesController : ApiController
    {
        // GET api/<controller>
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/<controller>/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/<controller>
        public void Post([FromBody]string value)
        {
        }

        // PUT api/<controller>/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/<controller>/5
        public void Delete(int id)
        {
        }
    }
}

3.    We need a method to provide multiple HTTP access methods, so the action configuration should be added, such as: "api/{controller}/{action}/{id}".
Modify the WebApiConfig.cs file.
Code show as below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace WebAPI
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API Routing
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

4.    Modify the HelpPageConfig.cs file, the code is as follows:
// Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData
// package to your project.
#define Handle_PageResultOfT

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Web;
using System.Web.Http;
using WebAPI.Utils;

namespace WebAPI.Areas.HelpPage
{
    ///
    /// Use this class to customize the Help Page.
    /// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation
    /// or you can provide the samples for the requests/responses.
    ///
    public static class HelpPageConfig
    {
        [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters",
            MessageId = "WebAPI.Areas.HelpPage.TextSample.#ctor(System.String)",
            Justification = "End users may choose to merge this string with existing localized resources.")]
        [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly",
            MessageId = "bsonspec",
            Justification = "Part of a URI.")]
        public static void Register(HttpConfiguration config)
        {
             Uncomment the following to use the documentation from XML documentation file.
            //config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
            #region *************************XML display interface parameters and comments****************** ***********************
            // Add the XML configuration of this project or other reference projects: multiple can be added
            config.SetDocumentationProvider(new MultiXmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/bin/WebAPI.XML")));
            #endregion
             Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.
             Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type
             formats by the available formatters.
            //config.SetSampleObjects(new Dictionary<Type, object>
            //{
            //    {typeof(string), "sample string"},
            //    {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}
            //});

            // Extend the following to provide factories for types not handled automatically (those lacking parameterless
            // constructors) or for which you prefer to use non-default property values. Line below provides a fallback
            // since automatic handling will fail and GeneratePageResult handles only a single type.
#if Handle_PageResultOfT
            config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult);
#endif

            // Extend the following to use a preset object directly as the sample for all actions that support a media
            // type, regardless of the body parameter or return type. The lines below avoid display of binary content.
            // The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.

            #region *************************Default JSON display interface******************** *********************
            //config.SetSampleForMediaType(
            //    new TextSample("Binary JSON content. See http://bsonspec.org for details."),
            //    new MediaTypeHeaderValue("application/bson"));
            #endregion

             Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format
             and have IEnumerable<string> as the body parameter or return type.
            //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));

             Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values"
             and action named "Put".
            //config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put");

             Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png"
             on the controller named "Values" and action named "Get" with parameter "id".
            //config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id");

             Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.
             The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter.
            //config.SetActualRequestType(typeof(string), "Values", "Get");

             Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.
             The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.
            //config.SetActualResponseType(typeof(string), "Values", "Post");
        }

#if Handle_PageResultOfT
        private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type)
        {
            if (type.IsGenericType)
            {
                Type openGenericType = type.GetGenericTypeDefinition();
                if (openGenericType == typeof(PageResult<>))
                {
                    // Get the T in PageResult<T>
                    Type[] typeParameters = type.GetGenericArguments();
                    Debug.Assert(typeParameters.Length == 1);

                    // Create an enumeration to pass as the first parameter to the PageResult<T> constuctor
                    Type itemsType = typeof(List<>).MakeGenericType(typeParameters);
                    object items = sampleGenerator.GetSampleObject(itemsType);

                    // Fill in the other information needed to invoke the PageResult<T> constuctor
                    Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), };
                    object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, };

                    // Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor
                    ConstructorInfo constructor = type.GetConstructor(parameterTypes);
                    return constructor.Invoke(parameters);
                }
            }

            return null;
        }
#endif
    }
}

This modification supports multiple XML document methods, and the extension class is as follows:
using System;
using System.Linq;
using System.Reflection;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using WebAPI.Areas.HelpPage;
using WebAPI.Areas.HelpPage.ModelDescriptions;

namespace WebAPI.Utils
{
    /// A custom <see cref='IDocumentationProvider'/> that reads the API documentation from a collection of XML documentation files.
    public class MultiXmlDocumentationProvider : IDocumentationProvider, IModelDocumentationProvider
    {
        /*********
        ** Properties
        *********/
        /// The internal documentation providers for specific files.
        private readonly XmlDocumentationProvider[] Providers;

        /*********
        ** Public methods
        *********/
        /// Construct an instance.
        /// <param name='paths'>The physical paths to the XML documents.</param>
        public MultiXmlDocumentationProvider(params string[] paths)
        {
            this.Providers = paths.Select(p => new XmlDocumentationProvider(p)).ToArray();
        }

        /// Gets the documentation for a subject.
        /// <param name='subject'>The subject to document.</param>
        public string GetDocumentation(MemberInfo subject)
        {
            return this.GetFirstMatch(p => p.GetDocumentation(subject));
        }

        /// Gets the documentation for a subject.
        /// <param name='subject'>The subject to document.</param>
        public string GetDocumentation(Type subject)
        {
            return this.GetFirstMatch(p => p.GetDocumentation(subject));
        }

        /// Gets the documentation for a subject.
        /// <param name='subject'>The subject to document.</param>
        public string GetDocumentation(HttpControllerDescriptor subject)
        {
            return this.GetFirstMatch(p => p.GetDocumentation(subject));
        }

        /// Gets the documentation for a subject.
        /// <param name='subject'>The subject to document.</param>
        public string GetDocumentation(HttpActionDescriptor subject)
        {
            return this.GetFirstMatch(p => p.GetDocumentation(subject));
        }

        /// Gets the documentation for a subject.
        /// <param name='subject'>The subject to document.</param>
        public string GetDocumentation(HttpParameterDescriptor subject)
        {
            return this.GetFirstMatch(p => p.GetDocumentation(subject));
        }

        /// Gets the documentation for a subject.
        /// <param name='subject'>The subject to document.</param>
        public string GetResponseDocumentation(HttpActionDescriptor subject)
        {
            return this.GetFirstMatch(p => p.GetDocumentation(subject));
        }

        /*********
        ** Private methods
        *********/
        /// Get the first valid result from the collection of XML documentation providers.
        /// <param name='expr'>The method to invoke.</param>
        private string GetFirstMatch(Func<XmlDocumentationProvider, string> expr)
        {
            return this.Providers
                .Select(expr)
                .FirstOrDefault(p => !String.IsNullOrWhiteSpace(p));
        }
    }
}

Note: HelpPageConfig.cs needs to comment out the following code when XML document comments are enabled
 #region *************************Default JSON display interface******************** *********************
             //config.SetSampleForMediaType(
            //    new TextSample("Binary JSON content. See http://bsonspec.org for details."),
            //    new MediaTypeHeaderValue("application/bson"));
            #endregion

5.    Next you can write some Controller.cs. Then start the project to view the Api link.
6.    Configure automatic generation of interface test pages
Add a reference to the NuGet installation package:
WebApiTestOnHelpPage
7.    Click the "Test API" button to test.


text:
Q: How to Prioritize Boost Include for a Specific Version on macOS The GitHub project, https://github.com/bluzelle/swarmDB , that I am working on provides an option that installs Boost 1.70.0 in the build folder and links from there.
Unfortunately, on macOS only, if the developer has installed a previous version of boost, 1.68.0 say, manually or via brew, the include and lib files are placed in
/usr/local
which causes the compiler to ignore the boost in the build folder, as it sees the older version of boost first. Since we are using new functionality in boost 1.70.0 this results in difficult to diagnose linker errors (well, not now, we know what the problem is).
The fix is to request developers remove the older version of boost, a better fix would be to ignore the older boost include folders and libraries.
How do we get the macOS c++ compilers to ignore the older boost versions include folder and libraries in favour of those installed in the build folder?


text:
Q: How change actionbar title on appcompat v7 library I Want to Change Actionbar title to any text programically.
I use appcompat v7
Here is my code:
  LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View actionBarview = inflater.inflate(R.layout.action_bar, null);

    ActionBar actioBar = getSupportActionBar();
    actioBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actioBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    actioBar.setCustomView(actionBarview, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    final DrawerLayout drowerlayout = (DrawerLayout) findViewById(R.id.drawerlayout);

I tried: actioBar.setTitle("MyText");
But nothing happened.
Here is my custom actionbar xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:layout_gravity="right"
    android:background="#bfbfbf"
    android:gravity="right"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="0dp"
        android:layout_height="wrap_content" android:layout_gravity="center" android:layout_weight="0.1"/>

    <TextView
        android:id="@+id/txtBName"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:gravity="center"
        android:text="......"
        android:textColor="#000" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="wrap_content" android:layout_gravity="center" android:layout_weight="0.1"/>

    <Button
        android:id="@+id/btnMenu"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="menu" />

.

A: Since you are setting a custom view on you action bar setting title setTitle() wont work, instead you will either have to drop custom and stick with the default actionbar view or there have to be a TextView in your custom that you can get a reference and set its text to whatever your title is.
If setting customView is required for your case here is how you will have to go about it...
View actionBarview = inflater.inflate(R.layout.action_bar, null);
TextView tvTitle = (TextView) actionBarview.findViewById(R.id.tv_title)
tvTitle.setText(<your title here>)

remember tv_title should be in your custom view xml as a TextView widget. later in code you can reference to tvTitle for changing you actionbar Title


text:
Q: Multiple jQuery sliders: How to disable keyboard navigation for all but one slider? I have six sliders on a single page, each in its own section. As you scroll, the section in view gets a CSS class of 'active.' I'm trying to disable keyboard navigation for every slider except the slider in the active section.
My current code looks like this:

$('section').not('.active').on('keydown', function(e){
    if(e.keyCode === 37 || e.keyCode === 39) {
        e.preventDefault();
        return false;
    }
});

No avail. They all move. Is my selector wrong? Is there a better way to disable left and right keyboard navigation for a group of elements?
I'm using Unslider.

A: It looks like the keydown event is assigned to document so first you have to unbind the existing event assigned by the plugin and bind a new keydown event which changes the slide on next and prev.
If you have used $('.banner').unslider(); (ie. a css selector to select all sliders) to initialize the sliders then the following code will do the job
$(function() {
    var banners = $('.banner');
    banners.unslider();
    $(document).unbind('keydown').keydown(function(e){
        var index = banners.index($('.active')[0]) + 1;
        var data = $('.active').data('unslider'+index);

        if(e.keyCode === 37 ) {
            e.preventDefault();
            data.prev();
            return false;
        }
        if(e.keyCode === 39 ) {
            e.preventDefault();
            data.next();
            return false;
        }
    });
});

Sample FIDDLE
UPDATE
I have made a small correction in the selector for active banner
FIDDLE
As you can see I have changed $('.active') to $('div.active')
I would recommend you to put a very specific class name than active
you can even replace $('div.active') with $('div.portfolio-slider.active')

A: Thanks to Cerlin Boss for the help! Here's the solution I ended up using, including arrow navigation that works for individual sliders on a multi-slider page:
$(document).ready(function (){
    $('.portfolio-slider').each(function(){
        var $this = $(this);
        $this.unslider({
          delay: false,
          dots: false,
          fluid: true,
          keys: true,
          loop: true
        }).find('.unslider-arrow').click(function(event){
            event.preventDefault();
            if ($(this).hasClass('next')) {
                $this.data('unslider').next();
            } else {
                $this.data('unslider').prev();
            }
        });
        $(document).unbind('keydown').keydown(function(e){
            var active = $('div.portfolio-slider.active');
            if(e.keyCode === 37 ) {
                e.preventDefault();
                active.data('unslider').prev();
                return false;
            }
            if(e.keyCode === 39 ) {
                e.preventDefault();
                active.data('unslider').next();
                return false;
            }
        });

    });
});

The key, as Cerlin Boss pointed out, is to unbind keydown events, and then rebind them to target only the slider with a specific class, in my case 'active'. Hope this helps someone!


text:
Q: Google Maps overview_polyline give wrong value My application is java google map web application. Get 2 points and send to Google
http://maps.googleapis.com/maps/api/directions/json?origin="+saddr+"&destination="+daddr+"&sensor=false , it give json. Then I have decodeoverview_polyline . My Problem is sometime it give extended value.
This is my decode part.
  public static ArrayList<Location> decodePoly(String encoded) {
      ArrayList<Location> poly = new ArrayList<Location>();
      int index = 0, len = encoded.length();
      int lat = 0, lng = 0;
      while (index < len) {
       int b, shift = 0, result = 0;
       do {
        b = encoded.charAt(index++) - 63;
        result |= (b & 0x1f) << shift;
        shift += 5;
       } while (b >= 0x20);
       int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
       lat += dlat;
       shift = 0;
       result = 0;
       do {
        b = encoded.charAt(index++) - 63;
        result |= (b & 0x1f) << shift;
        shift += 5;
       } while (b >= 0x20);
       int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
       lng += dlng;
       Location p = new Location((((double) lat / 1E5)),
         (((double) lng / 1E5)));

     //  System.out.println("==p==" +p.getLatitude());
      // System.out.println("==p==" +p.getLongitude());
       poly.add(p);
      }
      return poly;
     }

The black color mark , the rep didn't travel to that path. But it drawn like that.
http://maps.googleapis.com/maps/api/directions/json?origin=6.95522,79.8864&destination=6.96165,79.8958&sensor=false  This overview_polyline is _pmi@}xqfNEkEM{@DREUOc@Wi@MOkBmCi@k@o@o@gA}@qD_DiDgD{MoN_DeDJEVGvBS
this 2nd wrong path drawn
This is my db sample data...

Please give some idea? What is an issue?
Thanks in advance.

A: Probably this is just an error for the smooth applied to the points, as described in the documentation:

overview_polyline contains an object holding an array of encoded points that represent an approximate (smoothed) path of the resulting directions.

I actually saw how my path is drawed twice, so the last point connects with the first one, making a close path.
I guess that this element in the call output is just for a far-zoom use or something similar.
However, you can still parse the rest of the content as described in this post.


text:
Q: Какое событие постоянно мониторит input, независимо от фокуса в нем? сhange только по смене фокуса. keyup только когда набираешь. А какое событие отслеживает любое изменение начение value даже если я к примеру при нажатии на любой селектор передал значение в инпут?
Приведу конкретный пример. При нажатии на p происходит изменение значения value у input, но при этом мой div не меняет bacground, как при событии input

const $inp = document.querySelector('input');
const $p = document.querySelector('p');
const $div = document.querySelector('div');

$p.addEventListener('click', () => {
 $inp.value = $p.textContent;
});

$inp.addEventListener('input', () => {
 $div.style.background = "#fc0";
});
<input type="text" >

Text

Не меняется backgroud, когда меняется value input

Мне нужно, чтобы при нажатии на p происходило именно отслеживание input. Я понимаю, что могу просто написать функционал при нажатии на p, но такое не подходит. Потому что input может менять значение при куче событий в моей задаче.

A: данный пример показывает работу

*

*oninput - сразу

*onchange - при потере фокуса

а ещё, как вызвать эти два события с помощью JS

var myInput, demo;
myInput = myInput || document.getElementById("myInput");
demo = demo || document.getElementById("demo")

function doOnInput() {
  demo.innerHTML = "on Input: " + myInput.value;
}

function doOnChange() {
  demo.innerHTML = "on Change: " + myInput.value;
}
setTimeout(() => {
  myInput.value = 'Напиши change'
  let e = new Event('change')
  myInput.dispatchEvent(e)
}, 3e3);
setTimeout(() => {
  myInput.value = 'Напиши input'
  let e = new Event('input')
  myInput.dispatchEvent(e)
}, 5e3);

Напиши, вставь или удали какой-нибудь текст в поле ниже:

<input type="text" id="myInput" oninput="doOnInput()" onchange="doOnChange()" value="здесь" />

как подписаться на эти события с помощью JS:
myInput.addEventListener('input' , (_e) => {} )
myInput.addEventListener('change', (_e) => {} )

A: Событие input
Событие input срабатывает тут же при изменении значения текстового элемента и поддерживается всеми браузерами, кроме IE8-.
вот тут читайте подробнее https://learn.javascript.ru/events-change


text:
Q: error_handlers page not show when deployed I am new to google app engine, and want to host my php website on it. I found that there is a error_handlers option to redirect error(missing page) to custom error page, but when deployed, the error page never show.
I have try it with local server using dev_appserver.py app.yaml and it works. If I enter a file that is not exist, it will redirect to the error page. But when deployed to the web, it doesn't work.
This is my app.yaml. If the URL is not a php or html file, just simply redirect to index.php. But if it is a php or html file but not found, it will go to error.html.
runtime: php55
api_version: 1

handlers:
# Serve images as static resources.
- url: /(.+\.(gif|png|jpg))$
  static_files: \1
  upload: .+\.(gif|png|jpg)$
  application_readable: true

# Serve php scripts.
- url: /(.+\.(php\html))$
  script: \1

- url: /.*
  script: index.php

error_handlers:
  - file: error.html

In local server, it works fine and show the error page. When deployed, 404 error will appear for missing php or html. The error.html will never show, even if the URL is (domain).com/error.html. 404 error will show for error.html
I wonder if it is possible to redirect missing page to custom error page.

A: In your app.yaml I think you are missing a \ in - url: /(.+\.(php\html))$ like this: /(.+\.(php\\html))$
error_handlers only works for timeouts, over quota, and dos api denial errors.
It seems to me that you are redirecting all your urls to index.php and creating the appropriated handler there for each url. In that case, you should catch the errors there with set_error_handler.
For the 404, I will recommend the following:
handlers:
 -url:/
  script: index.php

 -url:/*.
  script: 404_custom_error.php

In this case, any url that can not be handled inside the index.php will then be handled by the 404 custom error php script, as shown in the app.yaml example.
I found two public issue trackers discussing this topic. The first has info on a feature request and the second explains that the infrastructure will not intercept valid 404 responses.


text:
Q: Use urllib.request with a proxy I need to download a file using a python script when i am in the office ... Long term goal is to give this out to my team mates but need to fix the proxy issue
Here is the code I am using right now
import urllib.request
import shutil

url = "https://download/app/client/app.exe"
output_file = "C:\\Desktop\\testing\\App.exe"
with urllib.request.urlopen(url) as response, open(output_file, 'wb') as out_file:
    shutil.copyfileobj(response, out_file)

When i launch this script it just hangs and I know it is because of the proxy issue .... How can i set this to use my corporate proxy? Ideally it would be great to get this to use proxy settings based on location (home vs office) but i will take what i can get


text:
Q: Do Inferi need to be victims of the commanding wizard? Albus Dumbledore stated in HP6 about Inferi and Voldemort:

They are corpses, dead bodies that have been bewitched to do a Dark wizard's bidding. Inferi have not been seen for a long time, however, not since Voldemort was last powerful ... He killed enough people to make an army of them, of course."

Why did he add that last sentence? Is that because it's only possible to create an Inferi out of the victim you yourself killed? Or simply easier than from a person dead from other causes? Or merely an off-the-cuff observation about Voldemort having no implication on Inferi?

A: I think it might be a throwaway.
Grindelwald also seriously considered raising an army of Inferi, and while it's not explicitly stated how many people Grindelwald killed (the only known victim is possibly Arianna Dumbledore), there's nothing in canon to imply that Grindelwald was a darker wizard than Voldemort. As well, their agendas were different -- immortality for Voldemort, taking over of the Muggle world by the Wizarding world for Grindelwald.
Tales of Beedle the Bard says [We] remain incapable of raising the dead, and there is every reason to suppose this will never happen. Vile substitutions have, of course, been attempted by Dark Wizards, who have created Inferi, but these are ghastly puppets, not truly reawoken humans. - TOBTB - Page 164. It indicates that Necromancy is the Dark Art used to conjure the dead, but it is a branch of magic that has never worked. (Page 160)
I can't recall or locate anything in canon that indicates Inferi can only be conjured by the Dark Wizard who initially killed them. And if Necromancy doesn't work, then is there a spell? I suppose that's a separate question.
ETA: I forgot I was going to mention this bit of text:

'The Lestranges should stand here,' said Voldemort quietly. 'But they are entombed in Azkaban. They were faithful. They went to Azkaban rather than renounce me ... when Azkaban is broken open, the Lestranges will be honoured beyond their dreams. The Dementors will join us ... they are our natural allies ... we will recall the banished giants ... I shall have all my devoted servants returned to me, and an army of creatures whom all fear ...'
Goblet of Fire - Page 564 - British Hardcover

The last sentence might imply the Inferi, but I take it neutrally as to your question. It neither confirms nor denies whether or not the wizard must use his/her own murder victims for Inferi. I still err on the side of it being a toss-away comment, given the lack of canon indicating otherwise. :)

A: No, it doesn't seem like it.
When Professor Snape explains Inferi to the class, he never mentions anything about Inferi needing to be bodies that were killed by the wizard who turned them into Inferi.

"The Inferius is a corpse that has been reanimated by a Dark wizard's spells. It is not alive, it is merely used like a puppet to do the wizard's bidding. A ghost, as I trust that you are all aware by now, is the imprint of a departed soul left upon the earth … and of course, as Potter so wisely tells us, transparent." - Harry Potter and the Half-Blood Prince, Chapter 21 (The Unknowable Room)

The J.K. Rowling writing on Pottermore goes into a bit more detail about how Inferi are created, and again doesn't mention it being necessary for the Inferi to be people killed by the Dark wizard who wishes to control them.

An Inferius (plural: Inferi) is a corpse that has been reanimated by a Dark wizard's curse. It becomes a grisly puppet, and may be used as an expendable servant by the Dark wizard in question. The most obvious sign that one is facing an Inferius rather than a living human are the white and cloudy eyes.
The spells used to reanimate a human body are much more complex than those used, for instance, to make inanimate objects fly. The Inferius may be cursed to respond lethally if disturbed, to kill indiscriminately, and to undertake perilous jobs for its master. Inferi (Pottermore)

It seems likely that Dumbledore's comment was either about how many people the Dark Lord had killed, or how many Inferi the Dark Lord himself might have (knowing his temperament, Dumbledore may have suspected he'd use the corpses of the people he killed). It doesn't seem to be in any way implying that's the only way to create Inferi.
However, the Dark Lord did kill the people for his Inferi himself.
While it doesn't seem necessary to kill corpses used to make Inferi, the Dark Lord did kill the people he used to make the ones guarding his Horcrux.

The Inferi whom Harry and Dumbledore encounter in the depths of the lake in Harry Potter and the Half-Blood Prince were, when alive, mostly vagrant, homeless Muggles whom Voldemort had murdered for the purpose during his first rise to power, although some were the earthly remains of wizards or witches who 'disappeared' without explanation. Inferi (Pottermore)

The Dark Lord did kill Muggles specifically for the purpose of creating Inferi.

A: I think Dumbledore was noting Voldemort's pragmatism and cruelty. He could, presumably, have had graves dug up or bodies stolen to get his army, but large numbers of desecrated graves and mass body snatchings would have drawn attention before he was ready for direct conflict.
Killing people who wouldn't be missed let him amass numbers without attracting attention.
He caused terror by making people disappear and probably killed others who saw through him or were otherwise a potential problem. He was already creating an inferi army, so he put the corpses to use rather than bother trying to hide them.


text:
Q: On selecting a textfield, adjust view height for keyboard I have a ViewController (login view) in xib which has 2 UITextField and 1 UIButton component. The view hierarchy is
 UIView
     -> UIScrollView
         -> UIView (contentView)
             -> UITextField
             -> UITextField
             -> UIButton

I am using autolayout for the view. The UIScrollView has 4 constraints i.e., leading, trailing, top & bottom aligned to its superview (UIViewController view). ContentView has 4 constraints i.e., leading, trailing, top & bottom to its superview (UIScrollView) and width matching UIViewController view.
I have followed the steps as in Apple documentation to scroll up or down when user selects UITextField so that keyboard is not on top of UITextField.
When keyboard is shown scrollview is scrolled up but when keyboard is hidden scrollview does not scroll back. Any help is appreciated.
override func viewDidLoad() {
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func keyboardWillHide(notification: NSNotification) {

        let contentInsets: UIEdgeInsets = UIEdgeInsets.zero
        self.scrollView.contentInset = contentInsets
        self.scrollView.scrollIndicatorInsets = contentInsets
    }

func keyboardWillShow(notification: NSNotification) {

        if let activeField = self.activeField, let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {

            let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize.height, right: 0.0)

            self.scrollView.contentInset = contentInsets
            self.scrollView.scrollIndicatorInsets = contentInsets

            var aRect = self.view.frame

            aRect.size.height -= keyboardSize.size.height
            if (!aRect.contains(activeField.frame.origin)) {
                self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
            }
        }
    }

A: This problem with the keyboard is explained in detail in the apple documentation:
https://developer.apple.com/library/content/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html
Alternatively, try the following code:
func registerForKeyboardNotifications(){
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name:       NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name:    NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func deregisterFromKeyboardNotifications(){
   NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
   NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func keyboardWasShown(notification: NSNotification){
   self.scrollView.isScrollEnabled = true
   var info = notification.userInfo!
   let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
   let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)

   self.scrollView.contentInset = contentInsets
   self.scrollView.scrollIndicatorInsets = contentInsets

   var aRect : CGRect = self.view.frame
   aRect.size.height -= keyboardSize!.height
   if let activeField = self.activeField {
       if (!aRect.contains(activeField.frame.origin)){
           self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
       }
   }
}

func keyboardWillBeHidden(notification: NSNotification){
   var info = notification.userInfo!
   let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
   let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)
   self.scrollView.contentInset = contentInsets
   self.scrollView.scrollIndicatorInsets = contentInsets
   self.view.endEditing(true)
   self.scrollView.isScrollEnabled = false
}

func textFieldDidBeginEditing(_ textField: UITextField){
   activeField = textField
}

func textFieldDidEndEditing(_ textField: UITextField){
   activeField = nil
}

A: The scrollView contentInset.top was not 0.0 hence i was facing the problem. After changing contentInset.top properly scrollView set to original position after keyboard was hidden.
func keyboardWillShow(notification: NSNotification) {

        self.scrollView.isScrollEnabled = true

        var info = notification.userInfo!
        let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
        let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(self.scrollView.contentInset.top, 0.0, keyboardSize!.height, 0.0)

        self.scrollView.contentInset = contentInsets
        self.scrollView.scrollIndicatorInsets = contentInsets

        var aRect : CGRect = self.view.frame
        aRect.size.height -= keyboardSize!.height
        if let activeField = self.activeField {
            if (!aRect.contains(activeField.frame.origin)){
                self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
            }
        }
    }


text:
Q: How to create legend d3? I took this example from internet:It works fine except that it creates only two rects. I also fail to see why those rectangles are created since I would expect only one. I created this fiddle which seem not to work. https://jsfiddle.net/q4py7wxg/. Please help.
var color = d3.scale.linear()
          .range(["rgb(213,222,217)", "rgb(69,173,168)", "rgb(84,36,55)", "rgb(217,91,67)"]);

        var legendText = ["0 - 1000", "1000 - 2000", "2000 - 3000", "3000 - 5000"];
        var legend = d3.select("body").append("svg")
            .attr("class", "legend")
            .attr("width", 140)
            .attr("height", 200)
            .selectAll("g")
            .data(color.domain().slice().reverse())
            .enter()
            .append("g")
            .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

        legend.append("rect")
              .attr("width", 18)
              .attr("height", 18)
              .style("fill", color);

        legend.append("text")
              .data(legendText)
              .attr("x", 24)
              .attr("y", 9)
              .attr("dy", ".35em")
              .text(function(d) { return d; });

A: You wonder why your code...

Creates only two rects.

This is the reason: in D3, if you don't set the domain, the default domain is:
[0, 1]

And that's why you're seeing only two rectangles. Let's see it in this snippet, where color.domain().slice().reverse() is the data you're passing in your code:

//look Ma, no domain!
var color = d3.scaleLinear();

console.log(color.domain().slice().reverse());
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.5.0/d3.min.js"></script>

As you can see, your data is an array with only two elements.
Solution: first, change your domain:
.domain(d3.range(4))

Which is the same of:
.domain([0,1,2,3])

And change your data accordingly:
.data(d3.range(4))

PS: do not change your data without changing your domain, this will extrapolate the colours, that is, the scale will return colours that are not in the range.
PS2: you're using the wrong scale for the task. It's working (kind of), but it's a strange code to any seasoned d3 coder. Consider using scales with discrete ranges, like scaleQuantize, scaleQuantile or scaleThreshold.
Here is the fiddle: https://jsfiddle.net/9oxu4xyh/

A: Your are using the wrong version of D3, try d3.scaleLinear(). instead of d3.scale.linear()


text:
Q: Compare values in C# list I'm using fuzzyString to buy names from my list. I have a class Customer in which I want to compare a name with all other existing names.
My Customer class:
public class Customer
{
    public string Name { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
    public string Contact { get; set; }
    public int ID { get; set; }
    public int NIF { get; set; }
    public string NewName { get; set; }
    public string PostalCode { get; set; }
    public string City { get; set; }
}

In this code, I get the data from an Excel sheet and put it in the list. Now I want to compare the names:
static void Main(string[] args)
{
    var customer = ReadXls();

    foreach (var item in customer)
    {
        // Console.WriteLine($"Name:{item.Name}\n Phone:{item.Phone}\nContact:{item.Contact}\nEmail:{item.Email}\n");

        List<FuzzyStringComparisonOptions> options = new List<FuzzyStringComparisonOptions>();

        // Choose which algorithms should weigh in for the comparison
        options.Add(FuzzyStringComparisonOptions.UseOverlapCoefficient);
        options.Add(FuzzyStringComparisonOptions.UseLongestCommonSubsequence);
        options.Add(FuzzyStringComparisonOptions.UseLongestCommonSubstring);

        // Choose the relative strength of the comparison - is it almost exactly equal? or is it just close?
        FuzzyStringComparisonTolerance tolerance = FuzzyStringComparisonTolerance.Normal;

        bool result = item.Name.ApproximatelyEquals(item.Name, options, tolerance);

        // Get a boolean determination of approximate equality
        // double simLevenshtein = 1 - source.sor(target);
        double hamming = item.Name.HammingDistance(item.Name);
        double jaccard = item.Name.JaccardDistance(item.Name);
        double jaro = item.Name.JaroDistance(item.Name);

        double lev = item.Name.LevenshteinDistance(item.Name);

        Console.WriteLine(result + " " + hamming + " " + jaccard + " " + jaro+" " + lev);

        if (result == true)
        {
            Console.WriteLine(item.Name);
        }

        Console.WriteLine($"Name:{item.Name}\n Phone:{item.Phone}\nContact:{item.Contact}\nEmail:{item.Email}\n");
    }
}

private static List<Customer> ReadXls()
{
    var response = new List<Customer>();

    string FileName;
    Console.WriteLine("Diretório do ficheiro:");
    FileName = Console.ReadLine();

    FileInfo existingFile = new FileInfo(FileName);

    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

    using (ExcelPackage package = new ExcelPackage(existingFile))
    {
        ExcelWorksheet worksheet = package.Workbook.Worksheets[0];

        int colCount = worksheet.Dimension.End.Column;
        int rowCount = worksheet.Dimension.End.Row;

        int row = 2;
        int col = 1;

        while (string.IsNullOrWhiteSpace(worksheet.Cells[row, col].Value?.ToString()) == false)
        {
            Customer customer = new Customer();

            customer.Name = worksheet.Cells[row, 4].Text.Trim().ToUpper();
            customer.Phone = worksheet.Cells[row, 5].Text.Trim();

            // customer.Phone = Regex.Replace(customer.Phone, "\\+[0-9] {1,}", "");
            customer.Phone = Regex.Replace(customer.Phone, @"\s", "");
            customer.Phone = customer.Phone.Replace("+351", "");
            customer.Phone = customer.Phone.Replace("+44", "");
            customer.Phone = customer.Phone.Replace("+34", "");
            customer.Phone = customer.Phone.Replace("+244", "");
            customer.Phone = customer.Phone.Replace("+33", "");
            customer.Phone = customer.Phone.Replace("+49", "");

            customer.Contact = worksheet.Cells[row, 7].Text.Trim().ToLower();
            customer.Contact = UppercaseWords(customer.Contact);

            customer.Email = worksheet.Cells[row, 8].Text.Trim().ToLower();

            response.Add(customer);

            row += 1;
        }
    }

    return response;
}

With this code it only compares the Customer.Name with the same Customer.Name.. ex:
1 compares with 1 |
2 compares with 2 |
3 compares with 3 |

But I need that:
1 compares with 2 and 3 |

2 compares with 1 and 3 |

3 compares with 1 and 2 |


text:
Q: How to set required false for property in Stored Search in DocClass We have some properties defined in Stored Search Class which are required in Stored Search Class level
In ICN, it is not allowing us to save the search template, as few properties are required.
How can we make these properties required = false and it should allow to save the search template.
How can we achieve this using ICN plugin?


text:
Q: QueryServiceObjectSecurity fails with access denied error QueryServiceObjectSecurity call is failing with access denied error, i am not quite able to figure out why. I create service and then try to update the permissions for it. Interestingly once the call fails service is created and if i reexecute code, it detects existing service and attaches handle and then this call works fine, then why it fails for the first time? I am new to windows services, is there like during first time execution, service is created but SCM db  is not updated before i query object security?
Code snippet is below
Service creation:
managerHandle.Attach(::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS));
serviceHandle.Attach(::CreateService(managerHandle, serviceName, serviceDisplayName,
                SERVICE_CHANGE_CONFIG | SERVICE_START | SERVICE_QUERY_STATUS | SERVICE_INTERROGATE,
                serviceType, startCode, errorControl, path,
                groupName, NULL, NULL, NULL, NULL));

::ChangeServiceConfig2(m_serviceHandle, SERVICE_CONFIG_DESCRIPTION,  &serviceDesc);
service.Detach();

now after this i call function which updates the dacl for the service
ENSURE_STATE(!!m_serviceHandle)
CAutoPtr<PSECURITY_DESCRIPTOR *> pSecurityDescriptor;
DWORD bytesNeeded = 0;
if(::QueryServiceObjectSecurity(serviceHandle, DACL_SECURITY_INFORMATION, &pSecurityDescriptor, 0, &bytesNeeded) == FALSE)
{

Any help greatly appreciated

A: The documentation for Service Security and Access Rights explains that the access right READ_CONTROL is required to call QueryServiceObjectSecurity.
In the call to CreateService add READ_CONTROL to the list of access rights you request for the handle.

A: The access rights for system services are described in the MSDN article Service Security and Access Rights.
The relevant right is

READ_CONTROL  Required to call the QueryServiceObjectSecurity function to query the security descriptor of the service object.

The call to CreateService returns a handle with the access rights indicated by the dwDesiredAccess parameter, which you've set to
SERVICE_CHANGE_CONFIG |
  SERVICE_START |
  SERVICE_QUERY_STATUS |
  SERVICE_INTERROGATE

That gives the handle the right to change the service configuration, to start the service, query the service's status and interrogate the service - but not the right to query the security descriptor.
Add READ_CONTROL to dwDesiredAccess and the problem will go away.  Better still, set dwDesiredAccess to SERVICE_ALL_ACCESS.


text:
Q: SQL Query for listing all records where all values for one column are not in another column Sorry the question is too vague. I'll Explain it here.
So I have Two tables say R and S.
There are 10 Products P1,P2...............P10 and each product can have 5 types T1,T2,T3,T4,T5.
Table R is a 2-column table which is sorted according to the products.
Products   Type

P1         T1
P1         T3
P1         T4
P2         T2
P2         T3
P3         T1
.          .
.          .
.          .

So R is a table which is sorted by products and describes what type of every product out of the five is available.
S is another table of all 5 types listed.
Type

T1
T2
T3
T4
T5

I need to find out List off all types that are not available for a particular product.
So the result should be:
Products   Type

    P1         T2
    P1         T5
    P2         T1
    P2         T4
    P2         T5
    .          .
    .          .
    .          .
    .          .

SInce P1 does not have T2 and T5 in table R, it should be included in the result.
How can I achieve this? I tried using Left Join but I am unable to figure out the correct answer.
Help will be appreciated.!!!

A: You use cross join to generate all the rows and then filter out the ones that exist:
select p.product, t.type
from (select distinct product from producttypes) p cross join
     types t left join
     producttypes pt
     on pt.product = p.product and pt.type = t.type
where pt.type is null;

Of course, if you have a table with all products, you can use that for p instead of the subquery.

A: I would use CROSS JOIN and NOT EXISTS
select DR.product,
       S.type
from (select distinct product from R) DR
cross join types S
where not exists (
   select 1
   from R
   where R.product = DR.product and
         R.type = S.type
)

A: create table product(
    product_id varchar(10) not null,
    product_type varchar(10) not null
);
go

insert into product values
('P1','T1'),
('P1','T3'),
('P1','T4'),
('P2','T2'),
('P2','T3'),
('P3','T1');
go

create table productType(
    type_id varchar(10) not null,
);
go

insert into productType values
('T1'),('T2'),('T3'),('T4'),('T5'),('T6'),('T7')

select * from product
select *
    from
        (select distinct(product_id) from product) as a
        cross join
        (select distinct(type_id) from productType) as b
 except (select * from product)


text:
Q: Open a Popup using Image? I'm using WordPress on localhost and trying to add a popup or modal open using an image.
Tried using Popup Maker plugin-free version but it didn't work.
Can somebody help?

A: How about trying another Plugin, "Popup anything on click" this is a one that I find in a single search!!


text:
Q: Karma output unreadable due to huge traceback I've been experimenting with using Karma with Jasmine to run unit tests for my project.  But the output reported by Karma includes these giant stack traces that make it very hard to read the output.  Here is a sample of the output I'm seeing, copy-pasted from my terminal:  https://gist.github.com/JesseAldridge/5946d4ec299ed1f85cfb
Does anyone know of a way to make this output more readable?
Note that a lot of those lines are coming from Firebase.  Maybe there's some way to make Firebase produce less verbose tracebacks?  (Er, something along those lines anyway.)
I tried tee'ing the output to a file, but then I end up getting the progress line repeated every other line in the file.  Turning off the progress line is an option, but I'd really like to be able to monitor my test progress.  I also have to turn off syntax coloring to avoid junk characters being output to the text file, which is not ideal.

A: Using the mocha reporter helped mitigate the issue significantly:  https://www.npmjs.com/package/karma-mocha-reporter


text:
Q: Can TrueCrypt automatically dismount a volume when laptop shuts down? I created an encrypted volume in a partition in my laptop. But I'm worried to forget to unmount it when I close the laptop (which may put it in standby or hibernate) and somebody be able to hack Windows to login in and find the partition mounted.
TrueCrypt automatically dismounts its volumes when Windows is shutting down, and when a PC is in standby/hybernate we can remove a pendrive without corrupting it. But I tested closing the laptop and opening it and the encrypted partition was still available.
Is it possible to configure TrueCrypt to unmount volumes when I close the laptop?

A: Go into your options and set the auto dismount settings.   I believe 'Enter Power Saving' mode will do the trick.
http://www.truecrypt.org/screenshots6


text:
Q: char* truncated when assigned as struct member I have a structure with the following typedef.
typedef struct {
    short cmdLength;
    char cmdRequest[126];
} cmdRequest_t;

Then I have the following code in a main program.
char *command = "d tcpip\0";
printf("command: %s\n", command);
size_t cmdLen = strlen(command);
printf("size: %zu\n", cmdLen);
cmdRequest_t cmdRequest = {(short) cmdLen, *command};
printf("size: %hi\n", cmdRequest.cmdLength);
printf("command: %s\n", cmdRequest.cmdRequest);

However, my output is as follows.
command: d tcpip
size: 7
size: 7
command: d

The size is still correct, but for some reason the command is truncated to one letter. Any idea why this is the case?

A: What happens is that...
cmdRequest_t cmdRequest = {(short)cmdLen, *command};

This will initialize the member cmdRequest of cmdRequest as the dereferencing of command, or in other words, you'll end up with the first character in the string. It'ld be too easy that you actually don't have zeroes after that, so that printf() doesn't work. You may perfectly have had output like this if you changed a few unrelated things...
command: d%$232!>~11cCV224
mysh: program received SIGSEGV, Segmentation fault

Do this instead...
#include <string.h>

cmdRequest_t cmdRequest;
cmdRequest.cmdLength = (short)cmdLen;
strncpy(cmdRequest.cmdRequest, command, sizeof(cmdRequest.cmdRequest) - 1);

A: Use strcpy instead of plain assignment
When assigning dereferenced char pointer to array, only first char is read

A: command is a pointer to char.
It is initialized with a string constant, which means that it is a pointer to the first character of that string, i.e. 'd'.
If you dereference a pointer to char, you get, as a result, the single char to which it points, so *command evaluates to 'd'.
You're initializing a structure, which is an "aggregate type" in C, and the second member of that structure is an array, which is also an "aggregate type".
C90 says, in section 6.5.7 "Initialization"

Otherwise, the initializer for an object that has aggregate type shall be a brace-enclosed list of initializers for the members of the aggregate, written in increasing subscript or member order; and the initializer for an object that has union type shall be a brace-enclosed initializer for the first member of the union.
If the aggregate contains members that are aggregates or unions, or if the first member of a union is an aggregate or union, the rules apply recursively to the subaggregates or contained unions. If the initializer of a subaggregate or contained union begins with a left brace, the initializers enclosed by that brace and its matching right brace initialize the members of the subaggregate or the first member of the contained union. Otherwise, only enough initializers from the list are taken to account for the members of the subaggregate or the first member of the contained union; any remaining initializers are left to initialize the next member of the aggregate of which the current subaggregate or contained union is a part.

Your initializer for the structure is enclosed in braces, so the initializers in that initializer initialize the structure members cmdLength and cmdRequest, in order, so it initializes cmdLength to cmdlen and initializes cmdRequest to 'd'.
cmdRequest is an aggregate, but its initializer is not in braces, so "only enough initializers from the list are taken to account for the members of the subaggregate", so cmdRequest[0] is initialized to 'd'.
If you want to initialize cmdRequest to the array whose first member is pointed to by command, you'll have to do it with strcpy:
cmdRequest_t cmdRequest;
cmdRequest.cmdLen = (short) cmdLen;
strcpy(cmdRequest.cmdRequest, command);

Sorry about that, but that's what you get when using a language in which strings aren't real data types....


text:
Q: .htaccess encoding already encoded URL I have the following .htaccess entry:
RewriteCond %{SERVER_PORT}   !^443$
RewriteRule  (.*)  https://%{HTTP_HOST}/$1   [L]

When linking to http://...../?f=83|71|42 (which is URL-encoded by the browser to http://...../?f=83%7C71%7C42), it redirects to https://...../?f=83%257C71%257C42, encoding the % of %7C to %25, thus leading to the sequence %257C.
Is there any .htaccess syntax to prevent this?

A: Try adding the NE flag:
RewriteCond %{SERVER_PORT}   !^443$
RewriteRule  (.*)  https://%{HTTP_HOST}/$1   [L,NE]


text:
Q: cucumber.runtime.CucumberException: Not a Map or List type If I am using a data inside the Data Table which is not type of List or Map then it is giving me error
cucumber.runtime.CucumberException: Not a Map or List type
This is how I am testing this. I am testing it bottom to top i.e. write function > then write step def > write feature file (just for testing purpose).
java function:
public String getScenarioName(Scenario scenario) {
        System.out.println("scenario.getName().toString());
    }

step def:
@And("^Get current scenario name$")
    public void get_current_scenario_name(Scenario scenario) {
        System.out.println(getScenarioName(scenario));
    }

Feature file:
  Scenario: Title of your scenario
    Given I have a scenario
    Then Get current scenario name
      |scenario|

Since I'm using Scenario interface as a parameter I have to use it across, in function, in steps and in feature file.
Note: Please don't judge by the weird scenario, I am only testing it.
I have gone through below links, but it doesn't help me. It keep giving me same error.
https://github.com/cucumber/cucumber-jvm/issues/741
http://grasshopper.tech/340/ >> this one I couldn't implement, didn't quiet understand it.

A: You're looking somewhat in the wrong direction. To print out the scenario name in a given step you have to capture it in a before hook before printing it in a step:
import cucumber.api.Scenario;
import cucumber.api.java.Before;
import cucumber.api.java.en.And;

public class ExampleSteps {

    private Scenario scenario;

    @Before
    public void capture_scenario(Scenario scenario){
        this.scenario = scenario;
    }

    @And("^get current scenario name$")
    public void get_current_scenario_name() {
        System.out.println(this.scenario.getName());
    }
}

Then this scenario will print My Scenario.
Scenario: My Scenario
  And I get the current scenario name


text:
Q: Is it okay to have static methods returning CollectionReference or DocumentReference in Flutter with FlutterFire? I am building an app with Flutter and Firebase (using FlutterFire).
I find myself repeatedly adding code to access the same collection everywhere (in my case, outside the build method to be able to access the variable everywhere in during build).
The code looks like this:
CollectionReference usersCollection =
FirebaseFirestore.instance.collection('users').withConverter<UserFS>(
  fromFirestore: (snapshot, _) => UserFS.fromJson(snapshot.data()!),
  toFirestore: (dataObj, _) => dataObj.toJson(),
);

Would it be okay to move it to an utility class as an static method? Something like this:
static CollectionReference<UserFS> getUsersCollection() {
  return FirebaseFirestore.instance.collection('users').withConverter<UserFS>(
    fromFirestore: (snapshot, _) => UserFS.fromJson(snapshot.data()!),
    toFirestore: (dataObj, _) => dataObj.toJson(),
  );
}

Something similar happens with the DocumentSnapshot and QuerySnapshot streams. I do have them in multiple widgets and I do have to create a new one every time. (I could propagate them, but then it becomes a parameter nightmare creating widgets).
Would it be correct to have a static method that returns a new stream every time it is called? Or should it cache that stream and return always the same? (same question applies for the proposed method for CollectionReference and DocumentReference).
I am worried about messing with the quantity of connections, losing data, ... I do not understand the internals of the FlutterFire package.
The objective would be to have a single source of streams and references and not having to re-write the same code over and over again to access the same collections or documents in different widgets.
I hope I have explained myself clearly.
Thank you very much in advance!!!


text:
Q: What is wrong with this Java random software code? I have made software in Java that generates random number in range. But it don't work. Sorry for strange language and comments. I have three classes: main, for generating and GUI. When I click button to generate it shows 0 on screen. Please help me.
public class glavnaKlasa {
static public int broj;

public static void main(String[] args) {
    GUI guiObject = new GUI();
    guiObject.mainGUI();

    generisanje generisanjeObject = new generisanje();
    broj = generisanjeObject.glavno(guiObject.min, guiObject.max);
}
}

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class GUI {

private JFrame frmNasumicniBroj;
private JTextField textField;
private JTextField textField_1;
private JLabel lblNasumicniBroj;
private JTextField textField_2;

/**
 * Launch the application.
 */
public static void mainGUI() {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                GUI window = new GUI();
                window.frmNasumicniBroj.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public GUI() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
public int min, max;

private void initialize() {
    frmNasumicniBroj = new JFrame();
    frmNasumicniBroj.setTitle("Nasumicni broj");
    frmNasumicniBroj.getContentPane().setBackground(Color.CYAN);
    frmNasumicniBroj.setBounds(100, 100, 400, 300);
    frmNasumicniBroj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frmNasumicniBroj.getContentPane().setLayout(null);

    JLabel lblNewLabel = new JLabel("Donja granica: ");
    lblNewLabel.setForeground(Color.YELLOW);
    lblNewLabel.setFont(new Font("Wide Latin", Font.PLAIN, 12));
    lblNewLabel.setBounds(10, 11, 154, 14);
    frmNasumicniBroj.getContentPane().add(lblNewLabel);

    textField = new JTextField();
    textField.setBounds(200, 8, 154, 20);
    frmNasumicniBroj.getContentPane().add(textField);
    textField.setColumns(10);

    JLabel lblGornjaGranica = new JLabel("Gornja granica: ");
    lblGornjaGranica.setForeground(Color.YELLOW);
    lblGornjaGranica.setFont(new Font("Wide Latin", Font.PLAIN, 12));
    lblGornjaGranica.setBounds(10, 36, 165, 14);
    frmNasumicniBroj.getContentPane().add(lblGornjaGranica);

    textField_1 = new JTextField();
    textField_1.setColumns(10);
    textField_1.setBounds(200, 33, 154, 20);
    frmNasumicniBroj.getContentPane().add(textField_1);

    lblNasumicniBroj = new JLabel("Nasumicni broj: ");
    lblNasumicniBroj.setForeground(Color.YELLOW);
    lblNasumicniBroj.setFont(new Font("Wide Latin", Font.PLAIN, 12));
    lblNasumicniBroj.setBounds(10, 144, 180, 14);
    frmNasumicniBroj.getContentPane().add(lblNasumicniBroj);

    textField_2 = new JTextField();
    textField_2.setEditable(false);
    textField_2.setBounds(200, 141, 154, 20);
    frmNasumicniBroj.getContentPane().add(textField_2);
    textField_2.setColumns(10);

    JButton btnNewButton = new JButton("GENERISI");
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try{
                min = Integer.parseInt(textField.getText());
                max = Integer.parseInt(textField_1.getText());
                glavnaKlasa glKlasa = new glavnaKlasa();
                String brString = Integer.toString(glKlasa.broj);
                textField_2.setText(brString);
            }catch (Exception e){
                JOptionPane.showMessageDialog(null, e);
            }
        }
    });
    btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 14));
    btnNewButton.setBounds(10, 61, 345, 72);
    frmNasumicniBroj.getContentPane().add(btnNewButton);

    JLabel lblVerzija = new JLabel("Verzija: 1.0");
    lblVerzija.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
    lblVerzija.setBounds(10, 180, 71, 14);
    frmNasumicniBroj.getContentPane().add(lblVerzija);

    JLabel label_1 = new JLabel("Autor: Djordje Milanovic");
    label_1.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
    label_1.setBounds(10, 205, 141, 14);
    frmNasumicniBroj.getContentPane().add(label_1);

    JLabel label_2 = new JLabel("Copyright: Alfin Informatics");
    label_2.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
    label_2.setBounds(9, 236, 166, 14);
    frmNasumicniBroj.getContentPane().add(label_2);
}}

import java.util.Random;
import javax.swing.JOptionPane;

public class generisanje {
public static int glavno(int min, int max){
    if (min >= max) {
        JOptionPane.showMessageDialog(null, "Maksimalni broj mora biti veci od minimalnog");
    }
    Random rnd = new Random();
    return rnd.nextInt((max - min) + 1) + min;
}
}

A: This:
  glavnaKlasa glKlasa = new glavnaKlasa();

creates the object with empty constructor, your main will not run there, so broj remains uninitialized.
Actually, you don't need to instantiate this class there, just this:
public void actionPerformed(ActionEvent arg0) {
            try{
                min = Integer.parseInt(textField.getText());
                max = Integer.parseInt(textField_1.getText());
                int broj = generisanje.glavno(guiObject.min, guiObject.max);
                String brString = Integer.toString(broj);
                textField_2.setText(brString);
            }catch (Exception e){
                JOptionPane.showMessageDialog(null, e);
            }
        }

Also consider working according to Java coding standards ( class name first uppercase and so on, it will be much easier to maintain the code).


text:
Q: How do you get the current sessid from web address and use it in javascript? Sorry if this is a noob question, network admin unknowingly turned into web developer :) I am trying to understand how to get the current sessid and put it into the javascript where sessid= (current sessid), its on the web address and is generated when you visit the search page. ex: http://www.southerntiredirect.com/shop/catalog/search?sessid=uUQgRHQyekRGJcyWwTFwf5hxep7cdYlV4CdKfunmjxNOQPEgDZdJD2tNgRsD7Prm&shop_param=
<script language="JavaScript">
    var url= "http://www.southerntiredirect.com/online/system/ajax_search_manufacturer?sessid=????????";
  </script><script type="text/javascript" src="http://www.southerntiredirect.com/online/templatemedia/all_lang/manufacturer.js"></script><input type="hidden" name="sessid" value="sessid??????">

A: You could use a simple regexp:
var url = "http://www.southerntiredirect.com/shop/catalog/search?sessid=uUQgRHQyekRGJcyWwTFwf5hxep7cdYlV4CdKfunmjxNOQPEgDZdJD2tNgRsD7Prm&shop_param=";
var match = url.match(/sessid=([^&]+)/);
if (match === null) {
    throw new Error("now what? D:");
}
var sessid = match[1];

The regexp in English: look for "sessid=" then capture anything that isn't an &

A: Use my handy-dandy library URLTools!
Library
//URLTools- a tiny js library for accessing parts of the url
function urlAnalyze(url) {
    if (url == undefined) {var url = document.location.toString();}
    url = url.replace(/\%20/g," ");
    //seperates the parts of the url
    var parts = url.split("?");
    //splits into sperate key=values
    if (parts[1] == undefined) {return 1;}
    var keyValues = parts[1].split("&");
    var key = function () {}
    keyValues.forEach(function (keyValue) {
        var keyAndValue = keyValue.split("=");
        key[keyAndValue[0]] = keyAndValue[1];
    });
    return key;
}

Then, just call URLAnalyze and get the sessid key.
Usage
var urlKeys = urlAnalyze(),
    sessid = urlKeys["sessid"];

A: here is a great function that grabs whatever you want and returns the key, value for it.
The main portion of this function gets the url using window.location.href and then performs a regular expression on it to find botht he key and the value.
I DO NOT TAKE CREDIT FOR THIS CODE.
Please go the link to see the full example
function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(
        /[?&]+([^=&]+)=([^&]*)/gi,
        function(m,key,value) {
            vars[key] = value;
        });
    return vars;
}


text:
Q: possible to hide specific character within media queries? I'm wondering if I can simply hide 'pipe' (eg: | ) characters within my media queries at a specific viewport?
I'm wondering because I have a menu that uses them as dividers but renders really poorly at mobile viewports, so would LOVE if I could somehow just hide them.
I'm thinking I may have to use some jQuery with my defined CSS within mobile viewport?
Any suggestions?
Update 10:38AM: Thanks for the awesome responses guys; I've tried suggested with adding class to span tag and now my pipes are not displaying accross, below is the mark-up within the footer.php I have and corresponding hide within media Q's.

EXPLORE  |

 FOR |

ENHANCED |

Iframe

CSS3:
/* Smartphones (Landscape) ----------- */
@media only screen and (min-width: 320px) and (max-width: 480px) {

#topvidarea {
    margin-left: 24%;
    margin-right: 20%;
    margin-top: -265px;
    max-width: 400px;
}

#topbgimg { display: none; }

#topbtn, #topbtn2, #topbtn3 {
    border: 0 solid #C6C699;
    display: inline;
    float: left;
    font-family: Georgia;
    margin-right: 5px;
    text-align: center;
    width: 122px;
}

#topvidarea {
    margin-left: 24%;
    margin-right: 20%;
    margin-top: 15px;
    max-width: 400px;
}

#footer a {
    font-size: 8px;
    margin: 0;
    padding: 12px;
    text-indent: 1px;
}

.f {
    float: none;
    margin-top: -2px;
    padding-left: 0;
}

.pipe { display: none; }

}

A: The root problem here is that you're using content (pipe characters) for presentation (decoration). Avoiding this is one of the main reasons to use CSS in the first place. Imagine a sight-impaired person using your site. How is their screen reader supposed to pronounce "|"? If you're not sure, chances are it should be moved from the content layer (HTML) to the presentation layer (CSS). (In reality screen readers are smart enough to avoid this common pitfall, but it's still a useful mental exercise.)
You can, as @ChrisN suggests, use border-right or -left but another option is to use the :after selector. For example, instead of this:

Foo
 |

Bar
 |

Baz

Remove the pipes from your content:

Foo

Bar

Baz

And then use the :after selector in your presentation layer (CSS) to put pipes between them:

@media ... {
  nav li:after {
    content: "|";
  }

  /* no "|" after the last one, though */
  nav li:last-child:after {
    content: normal;
  }
}

You can of course use padding properties to put the desired amount of space around the "|"s.
This approach avoids weighing down your page with additional markup and also gives you more flexibility than e.g. border-right, since you could use an image, or several characters or symbols, or some combination, instead of just a straight line.

A: Your best bet would probably be to change your pipes to border-rights (or border-lefts) and add spacing to make them appear like pipes, or (not recommended) wrap your pipe characters in s or the like. Then you can hide them at will.
But, no, you cannot just hide characters in that fashion via CSS.

A: I don't think you can specifically hide characters like that, but you could so something like (very simplified example..)
 |  Home  | </span About

Then in your media query target it
.noshow { display: none }

This is untidy, but it works.


text:
Q: Yii2-Working with multiple check boxes in gridview I have a gridview in which there also a checkbox.
    <?= Html::a('Disconnect', ['dco'], ['class' => 'btn btn-success', 'id'=>'dco']) ?>
    <?= Html::a('Connect', ['rco'], ['class' => 'btn btn-info','id'=>'rco']) ?>

<?php Pjax::begin(); ?>

        <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [

        ['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
            return ['value' => $d['msn']];
        }],

        'customer_id',
        'dept_name:ntext',
        'sub_div_name',
        'division_name',

        'allowed_units',
        'msn',

        'units_consumed',
        [
            'label' => 'Disconnected',
            'attribute' => 'disconnected',
            'format'=>'raw',
            'contentOptions' => ['style'=>'text-align:center'],
            'value' => function($model){
                return $model->disconnected == 1 ? '' : '';
            },
            'filter' => Html::activeDropDownList($searchModel, 'disconnected', [''=>'All','1'=>'Yes','0'=>'No'], ['class' => 'form-control']),
        ],

        'active_energy_total_m',

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>

I am using ajax for sending checked data to the controller.
There is two buttons Disconnect and Connect. On the checkbox checked and after clicking any of the two buttons, the corresponding selected item will be connected or disconnected.
$DCOurl = Url::toRoute(['/hescolog/dco']);
$RCOurl = Url::toRoute(['/hescolog/rco']);
$(document).ready(function () {
//DCO
 $('#dco').on('click',function(e) {

       e.preventDefault();
 var strValue = "";
    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!=="")
        {
        strValue = strValue + " , " + this.value;

        }
    else
       strValue = this.value;

});

   // alert(strValue);
$.ajax({
     url: '$DCOurl',
     type: 'POST',
     dataType: 'json',
     data: {data:strValue},
     success: function(data) {
        alert(data);
     }
  });

 });

 $('#rco').on('click',function(e) {
e.preventDefault();
 var strValue = "";
    $('input[name="selection[]"]:checked').each(function() {

    if(strValue!=="")
        {
        strValue = strValue + " , " + this.value;

        }
    else
       strValue = this.value;

});
    // alert(strValue);
$.ajax({
     url: '$RCOurl',
     type: 'POST',
     dataType: 'json',
     data: {data:strValue},
     success: function(data) {
        alert(data);
     }
  });
  });

  });

Controller
if(Yii::$app->request->isAjax && Yii::$app->request->post())
{
   $data = explode(',',$_POST['data']);
   foreach($data as $value)
   {
      //...... other code
   }
}

Now the problem I am facing is when I check all the checkboxes and click on any of the buttons, only the 1st checkbox checked an item is connect or disconnect.
Although while checking the controller `` I can see both the items against checkbox checked.
array(2) { [0]=> string(13) "002995000100 " [1]=> string(13) " 002992002018" }

Update 1
Against these two buttons, I have a SOAP service
 if(Yii::$app->request->isAjax && Yii::$app->request->isPost)
    {
        $data = explode(',',$_POST['data']);

        foreach($data as $value)
        {
            $ic++;
            $msn = $value;

            $xml_post_string = /** @lang text */
                '<soapenv:Envelope
            xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
            xmlns:soap="http://soap.inf.hexing.cn">
            <soapenv:Header/>
            <soapenv:Body>
            <soap:doCommand>

            <arg0><![CDATA[<?xml version="1.0" encoding="utf-8"?>
            <RequestMessage
            xmlns="http://iec.ch/TC57/2011/schema/message"
            xmlns:m="http://iec.ch/TC57/2011/EndDeviceControls#"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://iec.ch/TC57/2011/schema/message
            Message.xsd">

            <Verb>create</Verb>
            <Noun>EndDeviceControls</Noun>
            <Revision>2.0</Revision>
            <Timestamp>2016-01-01T00:00:00+04:30</Timestamp>
            <Source>MDM</Source>
            <AsyncReplyFlag>true</AsyncReplyFlag>
      <ReplyAddress>http://ip:port/AmiWeb/services/Metering</ReplyAddress>
            <AckRequired>true</AckRequired>
            <User>
            <UserID>'.$userName.'</UserID>
            </User>
            <MessageID>83c643e6-85c5-43c0-9e0a-fa1deb469b72</MessageID>
            <CorrelationID>1001</CorrelationID>
            <Property>
            <Name>password</Name>
            <Value>'.$password.'</Value>
            </Property>
            <Property>
            <Name>timeout(m)</Name>
            <Value>30</Value>
            </Property>

            <Payload>
            <m:EndDeviceControls>
            <m:EndDeviceControl>
            <m:reason>Disconnect/Reconnect</m:reason>
            <m:EndDeviceControlType ref="3.0.211.23"/>
            <m:EndDevices>
            <m:mRID>'.$msn.'</m:mRID>
            <m:Names>
            <m:name>Disconnect</m:name>
            <m:NameType>
            <m:name>ControlType</m:name>
            </m:NameType>
            </m:Names>
            </m:EndDevices>
            </m:EndDeviceControl>
            </m:EndDeviceControls>
            </Payload>
            </RequestMessage>
            ]]></arg0>
            </soap:doCommand>
            </soapenv:Body>
            </soapenv:Envelope>';

            $headers = array(
                "Content-type: text/xml;charset=\"utf-8\"",
                "Accept: text/xml",
                "Cache-Control: no-cache",
                "Pragma: no-cache",
                "Content-length: ".strlen($xml_post_string),
            ); //SOAPAction: your op URL

            $url = $soapUrl;

            // PHP cURL  for https connection

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            //curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

            // converting
            $response = curl_exec($ch);
            curl_close($ch);
            $domd=new DOMDocument();

            if(!$domd->loadXML($response)){
                throw new \RuntimeException("failed to parse XML!");
            }
            $inner_xml=$domd->getElementsByTagName("return")->item(0)->textContent;
            if(!($domd2=@DOMDocument::loadXML($inner_xml))){
                throw new \RuntimeException("failed to parse inner_xml!");
            }
            $AsyncReplyFlag=$domd2->getElementsByTagName("AsyncReplyFlag")->item(0)->textContent;

            if ($AsyncReplyFlag =='true')
            {
                $ds = 1;

                $disconnected_at = date('Y-m-d H:i:s');

                try {
                    Yii::$app->db->createCommand(/** @lang text */
                        "update
                     `accurate_mam`.`daily_log`
                     set
                     `disconnected` = '$ds',
                     `diconnected_at` = '$disconnected_at',
                     `reconnected_at` = NULL
                      where `msn` = '$msn' ;

                       ")->execute(); //update master table

                    Yii::$app->db->createCommand(/** @lang text */
                        "update
                    `accurate_mam`.`log_disconnected`
                    set

                    `disconnected_at` = '$disconnected_at'
                     where `msn` = '$msn'")->execute();// update log disconnected table
                } catch (Exception $e) {
                } // updating the master table
            }

        }

    }

I don't know what is the issue and why I am not able to process both the records.
Any help would be highly appreciated.

A: Because you left a comment here, I used the beginForm method:
in View

  <?php Pjax::begin() ?>
  <?=Html::beginForm(['test'],'post');?>

    <?= Html::submitButton('Disconnect', ['class' => 'btn btn-success', 'name'=>'dco', 'value'=>'dco', 'id'=>'dco','style'=>'margin:0 10px;']) ?>
    <?= Html::submitButton('Connect', ['class' => 'btn btn-primary', 'name'=>'rco', 'value'=>'rco','id'=>'rco']) ?>

    <?= GridView::widget([
      'dataProvider' => $dataProvider,
      'filterModel' => $searchModel,
    'columns' => [

        ['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
            return ['value' => $d['msn']];
        }],

        'customer_id',
        'dept_name:ntext',
        'sub_div_name',
        'division_name',

        'allowed_units',
        'msn',

        'units_consumed',
        [
            'label' => 'Disconnected',
            'attribute' => 'disconnected',
            'format'=>'raw',
            'contentOptions' => ['style'=>'text-align:center'],
            'value' => function($model){
                return $model->disconnected == 1 ? '' : '';
            },
            'filter' => Html::activeDropDownList($searchModel, 'disconnected', [''=>'All','1'=>'Yes','0'=>'No'], ['class' => 'form-control']),
        ],

        'active_energy_total_m',

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>

  <?= Html::endForm();?>
  <?php Pjax::end() ?>

in controllers
public function actionTest()
{
    $searchModel  = \Yii::createObject(\app\models\TestSearch::className());
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

  if ( Yii::$app->request->post() ) {

      $arr_select=(array)Yii::$app->request->post('selection');  //An array of selected items (checkbox)
      $dco=Yii::$app->request->post('dco');  // submitButton Disconnect
      $rco=Yii::$app->request->post('rco');  // submitButton Connect

      if ($dco === 'dco') {
           //code for Disconnect here ($query)
           // example:  $modelTest::updateAll(['disconnected' => 1], ['msn' => $arr_select]);
      } elseif ($rco == 'rco') {
           //code for Connect here ($query)
      }

    }

    return $this->render('test', [
        'dataProvider' => $dataProvider,
        'searchModel'  => $searchModel,
    ]);
}

You can optimize your code in the controller.
Of course, I think if you use the following method, it is better (a button and ...).
You can easily decide on the controller.
<?= Html::dropDownList('action','',[ 'Connect' =>'Connect','Disconnect' =>'Disconnect'],['prompt' => 'Please select','class'=> 'field-black input-sm']) ?>
<?= Html::submitButton('Apply', ['class' => 'btn btn-success','style'=>'margin:0 10px;']) ?>

You can place the above code instead of the two submitButton. Then decide on the controller according to the dropDownList value. Like below:
also add:, 'data-pjax'=>''
$_action=Yii::$app->request->post('action'); // dropDown
$arr_select=(array)Yii::$app->request->post('selection'); //selected items


text:
Q: Serialize file input for AJAX call to controller I'm having some issues serializing file inputs to pass via ajax to a MVC controller. I have a form that a user can upload one or more images. I want to then pass those image to a controller via ajax. The issue seems to be with the data value. I'm getting the following error in the console window:
Uncaught ReferenceError: ImageUploads is not defined
Here is my code:
@using (Html.BeginForm("CreateGallery", "User", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="ImageUploads"  id="upload-button" multiple="multiple" />
    <button type="button" class="btn btn-default" id="create-thumbnails">Submit</button>
}

<script>
    $(document).ready(function () {
        $("#create-thumbnails").click(function () {
            $.ajax({
                type: 'POST',
                url: '@Url.Action("DisplayThumbnails", "User")',
                dataType: 'json',
                data: ImageUploads,
                success: function (data) {
                    alert(data);
                },
                error: function (ex) {
                    alert("error!");
                }
            });
        })
    });
</script>


text:
Q: Lagged Dependents I am in a scenario where I am trying to forecast 2014 call volume in a call center based on prior call volumes in 2013 and 2012.  How do I difference 2014 call volume, and how do I lag 2012 and 2013 call volume so that I can run a statistically sound model?  Also I have access to data on these call volumes by week and by day, is not by day a better choice than by week?

A: What you want to do is to model daily data and the roll the forecasts upto weekly/monthly/quarterly/annual projections. You will need to incorporate day-of-the-week effects; week-of-the-year effects; month-of-the-year effects; level shifts ; local time trends ; holiday effects around each of the knowm holidays and special events and any needed ARIMA structure while taking into account unusual values/changes in parameters over time and changes in error variance over time. You might want to look at http://www.autobox.com/cms/index.php/news/47-can-forecasting-help-me-staff-a-specific-call-center- for some guidance. In terms or transparency I was one of the developers of AUTOBOX.

A: If you are an R user, the timeSeries package provides functions for lagging and differencing time series.


text:
Q: Working with date ranges in PostgreSQL to define active sites in a period of time (years) I am working with a PostgreSQL database of archaeological sites that stores their year of foundation (start_date) and the year where they were abandoned (end_date) as date fields. These years can be Before the Common Era (BCE) or Common Era (CE) and they range between BCE 900 to nowadays, since some of the sites were abandoned in the past, but many of them are still inhabited. Here is a snapshot of the data I am using to give you a better idea of what I am dealing with.
My aim is to build a query to define the sites that were occupied between two specific years (BCE 27 and CE 235) using this dataset. This is a graphic showing this objective,  which should result in the selection of Sites A, B, C and D, but not E. For this purpose, I have tried several solutions:
select site_id, name, type, start_date, end_date
from site_date
where start_date between '0027-01-01 BC' and '0235-01-01';

...shows sites starting between these two years, but not those active between them.
select site_id, name, type, start_date, end_date
from site_date
where end_date >= '0235-01-01';

...shows sites ending before CE 235.
...as well as variations of the previous.
I realized that these applications were actually defining the sites whose start and end dates fall within BCE 27 and CE 235, but not those (still active in this period) whose foundation was before the start date and whose abandonment was after the end date. How to solve this issue?

A: Pseudo code...
Where (start_date <= 27BCE and end_date >= 27BCE)
OR
(start_date between 27BCE and 235CE)

A: It sounds like what you want is anything that has a start_date <='0235-01-01' AND end_date >='0027-01-01 BC'.

A: AS per graphic shown, I understood sample data  is here, you wanted A, B, C and D but not E, these site were having end date > '0027-01-01 BC'
and these site exists between BCE 27 and CE 235,
select * from site_date
where end_date > '0027-01-01 BC'

A: Postgres fully understands BCE dates and therefore all date functions work properly with them. Unfortunately some instances do not display them correctly and will display '2021-01-01 BC' and '2021-01-01' exactly the same. You may actually need to use to_char(date_column, 'FMyyyy-mm-dd bc') to get the proper display.

The following converts your date sets (start_date, end_date) and the desired date start, end dates into a daterange then uses the overlaps operator (&&) to determine where any part of the (start_date, end_date) falls within the specified range. (See demo here. It also adds a row with a null end date to show how still inhabited can work.)
with target_range(founded_date,abandoned_date) as
     ( values (date '0027-01-01 BC', date '0235-01-01') )
select s.*
  from sites         s
  join target_range  tr
    on (  daterange(s.start_date, s.end_date, '[]')  &&
          daterange(tr.founded_date,tr.abandoned_date, '[]')
       ) ;

Additional Ref: make_date function