问:
Batch file - Windows 10. How to move files based on mid part of their name to folders named after that part
Would you help me with this simple task i'm struggling with?
 Here's the scenario.

We have a folder, let's called it "Folder1", with a huge amount of files named with six pairs of numbers, like this

"78 28 96 32 94 93.jpg"

"52 67 30 29 63 40.jpg"

"17 33 07 11 08 00.jpg"

"16 34 33 05 41 53.jpg"

Next to this files we have folders named from "00" to "99". And inside each of this folders we have another set of folders named the same way.

So, what we need to do is to move this files into the existent folders based on the 4th and 5th pair of numbers in their names, like this

"78 28 96 32 94 93.jpg" should be moved to "Folder1\ 32 \ 94"

"52 67 30 29 63 40.jpg" should be moved to "Folder1\ 29 \ 63"

"17 33 07 11 08 00.jpg" should be moved to "Folder1\ 11 \ 08"

and so on.

How can we do this with a batch file in "Folder1"?

The folders already exist, we only need to move the files.

Thanks!

答:
@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
FOR /f "delims=" %%a IN (
 'dir /b /a-d "%sourcedir%\?? ?? ?? ?? ?? ??.jpg" '
 ) DO (
 FOR /f "tokens=4,5delims= " %%p IN ("%%~na") DO (
  ECHO MOVE "%sourcedir%\%%a" "%sourcedir%\%%p\%%q\"
 )
)

GOTO :EOF
```

You would need to change the setting of sourcedir to suit your circumstances.

Perform a directory-scan of files (only) matching the mask supplied and then with the name part of each filename found, select tokens 4 and 5 to %%p and %%q.

The required MOVE commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO MOVE to MOVE to actually move the files.  Append >nul to suppress report messages (eg. 1 file moved)

Body:
@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
FOR /f "delims=" %%a IN (
 'dir /b /a-d "%sourcedir%\?? ?? ?? ?? ?? ??.jpg" '
 ) DO (
 FOR /f "tokens=4,5delims= " %%p IN ("%%~na") DO (
  ECHO MOVE "%sourcedir%\%%a" "%sourcedir%\%%p\%%q\"
 )
)

GOTO :EOF

You would need to change the setting of sourcedir to suit your circumstances.

Perform a directory-scan of files (only) matching the mask supplied and then with the name part of each filename found, select tokens 4 and 5 to %%p and %%q.

The required MOVE commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO MOVE to MOVE to actually move the files.  Append >nul to suppress report messages (eg. 1 file moved)


来源: stackexchange

问:
Host git repository on GitHub and VSTS
I currently have my project hosted on VSTS (Visual Studio Team Services) and I would also like to host it on GitHub. I like VSTS because I used it at my internship and got very used to it but I also like the familiar feel of GitHub and I know that my friends who are also going to be working on this project with me will prefer GitHub.

Is it possible to host the code in both places and have each of them update accordingly not matter where you push your code?

For example if someone else clones the repo from GitHub, make changes, and pushes them to GitHub can I make it so VSTS automatically picks up those changes, or vise-versa?

答:
The Short and Sweet Answer

Technically possible. But it's a bit like carrying two watches on your wrist... you'll have trouble keeping them synchronized, and you'll never be sure which one is "true". I suspect that after trying it for a month or two, you and/or your team will naturally abandon one and use the other exclusively.

The Long-Winded Answer

Git is inherently and intentionally de-centralized. Servers are no more or less important than individual computers. The repo on your machine carries the same history and the same core features as the repos on VSTS and GitHub.

The problem, of course, is that total anarchy leads to confusion and inefficiency. Humans, by and large, strongly prefer hierarchy and leadership. So, even though the technology is de-centralized, we are not, and we tend to get together and choose one particular repo as our source of truth. If it's not in that repo, then it's not "official". (Even when there are multiple repos, individuals tend to be loyal to one and only one, to the exclusion of all others.)

As an example, in the early days of git, before there were hosted solutions, Linus Torvalds' personal Linux repo was the source of truth. Sure, you could have your own, but everyone more or less recognized that his version was the most complete and most up-to-date and the most likely to stay that way, so everyone sent him their pull requests and based their new work off his master branch.

The same is going to be true for your project. You can set up as many hosted solutions as you want, but you will quickly find that, for each developer, only two repos will be significant... their personal repo, and the repo that they push and pull to and from (their "remote"). You'll find this is true for you as well. The effort required to keep VSTS updated will quickly feel redundant and unnecessary... you already have an up-to-date repo on GitHub, and your personal repo is where you do all of your work anyway, so why are you even trying to keep a second remote up-to-date?

You can try it for a while if you want to, and I'm sure you could use some clever hooks to keep VSTS mostly up-to-date, but over time the effort and expense (in time, if not money) will probably lead you to abandon it and just work with GitHub. If you really, strongly prefer VSTS, then you should set that up instead of GitHub. You can always migrate later... it's relatively easy to do with git... but you will probably find that having one remote active at a time is going to be better for everyone involved.

ContentLicense: CC BY-SA 3.0

Title: Host git repository on GitHub and VSTS


问:
How to take photo from webcam every one minute?
I'm trying to take a snapshot through my webcam.
This is my code:

```<code>using System;
using System.Text;
using System.Drawing;
using System.Threading;

using AForge.Video.DirectShow;
using AForge.Video;

namespace WebCamShot
{
    class Program
    {
        static FilterInfoCollection WebcamColl;
        static VideoCaptureDevice Device;

        static void Main(string[] args)
        {
            WebcamColl = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            Console.WriteLine("Press Any Key To Capture Photo !");
            Console.ReadKey();
            Device = new VideoCaptureDevice(WebcamColl[0].MonikerString);
            Device.NewFrame += Device_NewFrame;
            Device.Start();
            Console.ReadLine();
        }

        static void Device_NewFrame(object sender, NewFrameEventArgs e)
        {
            Bitmap Bmp = (Bitmap)e.Frame.Clone();
            Bmp.Save("D:\\Foo\\Bar.png");
            Console.WriteLine("Snapshot Saved.");
            /*
            Console.WriteLine("Stopping ...");
            Device.SignalToStop();
            Console.WriteLine("Stopped .");
            */
        }
    }
}
</code>```

It works well, but now I want to use my code for taking a snapshot every one minute.

Due to this reason, I added this line of code: Thread.Sleep(1000 * 60); // 1000 Milliseconds (1 Second) * 60 == One minute.

Unfortunately, This line doesn't giving me the wanted result - It still taking the snapshots like earlier, but it just saving the photos in the file every minute. What I actually want to do, is that my code will trigger the "Device_NewFrame" event every one minute.

How can I do it? I will glad to get some help.. Thhank You !

EDIT: As Armen Aghajanyan offered, I added timer to my code.
This timer Initializes the device object every one minute, registers the new Device object to the Device_NewFrame event and starts the activity of the Device.
After that, I'm uncommented this code in the event's body:

```<code>Console.WriteLine("Stopping ...");
Device.SignalToStop();
Console.WriteLine("Stopped .");
</code>```

Now the code is taking a snapshot every one minute.

答:
```<code> private static void TimerThread(object obj)
    {
        int delay = (int)obj;
        while (true)
        {
            takePhotos = true;
            Thread.Sleep(delay);
        }
    }
static void Main(string[] args)
    {
        WebcamColl = new FilterInfoCollection(FilterCategory.VideoInputDevice);
        Console.WriteLine("Press Any Key To Capture Photo !");
        Console.ReadKey();
        Device = new VideoCaptureDevice(WebcamColl[0].MonikerString);
        Device.NewFrame += Device_NewFrame;
        Device.Start();
        Thread timer=new Thread(TimerThread);
         timer.Start(60000);
        Console.ReadLine();
    }

    static void Device_NewFrame(object sender, NewFrameEventArgs e)
    {
       if(!takePhotos)return;
        Bitmap Bmp = (Bitmap)e.Frame.Clone();
        Bmp.Save("D:\\Foo\\Bar.png");
        takePhotos=false;
        Console.WriteLine("Snapshot Saved.");
        /*
        Console.WriteLine("Stopping ...");
        Device.SignalToStop();
        Console.WriteLine("Stopped .");
        */
    }
</code>```

Declare a static variable takePhotos and initialize with true

Body:
I'm trying to take a snapshot through my webcam.
This is my code:

using System;
using System.Text;
using System.Drawing;
using System.Threading;

using AForge.Video.DirectShow;
using AForge.Video;

namespace WebCamShot
{
    class Program
    {
        static FilterInfoCollection WebcamColl;
        static VideoCaptureDevice Device;

        static void Main(string[] args)
        {
            WebcamColl = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            Console.WriteLine("Press Any Key To Capture Photo !");
            Console.ReadKey();
            Device = new VideoCaptureDevice(WebcamColl[0].MonikerString);
            Device.NewFrame += Device_NewFrame;
            Device.Start();
            Console.ReadLine();
        }

        static void Device_NewFrame(object sender, NewFrameEventArgs e)
        {
            Bitmap Bmp = (Bitmap)e.Frame.Clone();
            Bmp.Save("D:\\Foo\\Bar.png");
            Console.WriteLine("Snapshot Saved.");
            /*
            Console.WriteLine("Stopping ...");
            Device.SignalToStop();
            Console.WriteLine("Stopped .");
            */
        }
    }
}

It works well, but now I want to use my code for taking a snapshot every one minute.

Due to this reason, I added this line of code: Thread.Sleep(1000 * 60); // 1000 Milliseconds (1 Second) * 60 == One minute.

Unfortunately, This line doesn't giving me the wanted result - It still taking the snapshots like earlier, but it just saving the photos in the file every minute. What I actually want to do, is that my code will trigger the "Device_NewFrame" event every one minute.

How can I do it? I will glad to get some help.. Thhank You !

EDIT: As Armen Aghajanyan offered, I added timer to my code.
This timer Initializes the device object every one minute, registers the new Device object to the Device_NewFrame event and starts the activity of the Device.
After that, I'm uncommented this code in the event's body:

Console.WriteLine("Stopping ...");
Device.SignalToStop();
Console.WriteLine("Stopped .");

Now the code is taking a snapshot every one minute.

Body:
 private static void TimerThread(object obj)
    {
        int delay = (int)obj;
        while (true)
        {
            takePhotos = true;
            Thread.Sleep(delay);
        }
    }
static void Main(string[] args)
    {
        WebcamColl = new FilterInfoCollection(FilterCategory.VideoInputDevice);
        Console.WriteLine("Press Any Key To Capture Photo !");
        Console.ReadKey();
        Device = new VideoCaptureDevice(WebcamColl[0].MonikerString);
        Device.NewFrame += Device_NewFrame;
        Device.Start();
        Thread timer=new Thread(TimerThread);
         timer.Start(60000);
        Console.ReadLine();
    }

    static void Device_NewFrame(object sender, NewFrameEventArgs e)
    {
       if(!takePhotos)return;
        Bitmap Bmp = (Bitmap)e.Frame.Clone();
        Bmp.Save("D:\\Foo\\Bar.png");
        takePhotos=false;
        Console.WriteLine("Snapshot Saved.");
        /*
        Console.WriteLine("Stopping ...");
        Device.SignalToStop();
        Console.WriteLine("Stopped .");
        */
    }

Declare a static variable takePhotos and initialize with true


问:
Hide frame in custom ContentView
I'm using a content view page called CardViewTemplate.xaml in my ListView to render some content with two frames, one of them should be visible and the other not, at the same time.

```<code>        <ContentView xmlns="http://xamarin.com/schemas/2014/forms"
                     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
        ...>
        <Frame  IsVisible="{Binding IsNotBreak}" IsClippedToBounds="True">
    .... content ....
        </Frame>
        <Frame IsVisible="{Binding IsBreak}" IsClippedToBounds="True">
    --content 2-
        </Frame>
      </ContentView>
</code>```

and the above page used in list view to bind and view some data to listview like below code:

```<code><ListView x:Name="listView" SelectedItem="{Binding SelcetedItem,Mode=TwoWay}"
          RowHeight="-1"
          ItemsSource="{Binding SelectedCard}" HasUnevenRows="True"   >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Custom:CardViewTemplate/>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</code>```

Unexpectedly  my list view shows only the second frame and it looks like attached image:

答:
That is because ContentView is supposed to have only one child, and the second Frame is overriding the first Frame.

Try adding a view-container like AbsoluteLayout, or Grid to hold the two frame(s) inside ContentView:

```<code><ContentView xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    ...>
    <AbsoluteLayout>

        <Frame  IsVisible="{Binding IsNotBreak}" IsClippedToBounds="True">
    .... content ....
        </Frame>
        <Frame IsVisible="{Binding IsBreak}" IsClippedToBounds="True">
    --content 2-
        </Frame>

    </AbsoluteLayout>
</ContentView>
</code>```

Title: Hide frame in custom ContentView

Body:
I'm using a content view page called CardViewTemplate.xaml in my ListView to render some content with two frames, one of them should be visible and the other not, at the same time.

        <ContentView xmlns="http://xamarin.com/schemas/2014/forms"
                     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
        ...>
        <Frame  IsVisible="{Binding IsNotBreak}" IsClippedToBounds="True">
    .... content ....
        </Frame>
        <Frame IsVisible="{Binding IsBreak}" IsClippedToBounds="True">
    --content 2-
        </Frame>
      </ContentView>

and the above page used in list view to bind and view some data to listview like below code:

<ListView x:Name="listView" SelectedItem="{Binding SelcetedItem,Mode=TwoWay}"
          RowHeight="-1"
          ItemsSource="{Binding SelectedCard}" HasUnevenRows="True"   >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Custom:CardViewTemplate/>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>

Unexpectedly  my list view shows only the second frame and it looks like attached image:

Body:
That is because ContentView is supposed to have only one child, and the second Frame is overriding the first Frame.

Try adding a view-container like AbsoluteLayout, or Grid to hold the two frame(s) inside ContentView:

<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    ...>
    <AbsoluteLayout>

        <Frame  IsVisible="{Binding IsNotBreak}" IsClippedToBounds="True">
    .... content ....
        </Frame>
        <Frame IsVisible="{Binding IsBreak}" IsClippedToBounds="True">
    --content 2-
        </Frame>

    </AbsoluteLayout>
</ContentView>


问:
Create data set from probability distribution
In R I need to create a data set where there are 57 0's, 203 1's, 383 2's and so forth. I thought I would be able to create the data set from the probability distribution:

```<code>sample_dist <- sample(c(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14), size = 2608,
replace = FALSE, prob = c(57/2608, 203/2608, 383/2608, 525/2608, 532/2608,
 408/2608, 273/2608, 139/2608, 45/2608, 27/2608, 10/2608, 4/2608, 0/2608, 1/2608, 1/2608))
</code>```

but this dosen't work. If I set replace = TRUE I get a sample from the same distribution but with replacement, which does not yield exactly the data set that I want.
What am I doing wrong? Is the even a good approach to creating such a data set or do you have a more elegant approach?

答:
Something like this:</p>

```<code>ccc <- c(rep(0, 57), rep(1, 203), rep(2, 383)) #and so on
ccc <- sample(ccc) # shuffle values
cdf <- data.frame(r = ccc) # if you want data frame
</code>```

Body:
In R I need to create a data set where there are 57 0's, 203 1's, 383 2's and so forth. I thought I would be able to create the data set from the probability distribution:

sample_dist <- sample(c(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14), size = 2608,
replace = FALSE, prob = c(57/2608, 203/2608, 383/2608, 525/2608, 532/2608,
 408/2608, 273/2608, 139/2608, 45/2608, 27/2608, 10/2608, 4/2608, 0/2608, 1/2608, 1/2608))

but this dosen't work. If I set replace = TRUE I get a sample from the same distribution but with replacement, which does not yield exactly the data set that I want.
What am I doing wrong? Is the even a good approach to creating such a data set or do you have a more elegant approach?

Body:
Something like this:

ccc <- c(rep(0, 57), rep(1, 203), rep(2, 383)) #and so on
ccc <- sample(ccc) # shuffle values
cdf <- data.frame(r = ccc) # if you want data frame


问:
invalid initialization of non-const reference of type ‘std::string& from an rvalue of type ‘std::basic_string<char>
```<code>bool hasWord(int y, int x, string &word) {
    if(!inRange(y, x)) return false;
    if(board[y][x] != word[0])  return false;
    if(word.size() == 1) return true;
    for(int direction = 0; direction < 8; direction++) {
        int nextX = x + dx[direction];
        int nextY = y + dy[direction];
        if(hasWord(nextY, nextX, word.substr(1)))  // <--- This
            return true;
    }
return false; }
</code>```

error: invalid initialization of non-const reference of type ‘std::string& {aka std::basic_string&}’ from an rvalue of type ‘std::basic_string’
   if(hasWord(nextY, nextX, word.substr(1)))

why the reason I was wrong?

答:
The reason of the error is that in this call

```<code>if(hasWord(nextY, nextX, word.substr(1)))
                         ^^^^^^^^^^^^^^
</code>```

there is created a temporary object of the type std::string and you are trying to bind a non-constant reference with the temporary object.

If the string is not changed in the function then just declare the function  like

```<code>bool hasWord(int y, int x, const string &word) {
                           ^^^^^
</code>```

Body:
bool hasWord(int y, int x, string &word) {
    if(!inRange(y, x)) return false;
    if(board[y][x] != word[0])  return false;
    if(word.size() == 1) return true;
    for(int direction = 0; direction < 8; direction++) {
        int nextX = x + dx[direction];
        int nextY = y + dy[direction];
        if(hasWord(nextY, nextX, word.substr(1)))  // <--- This
            return true;
    }
return false; }

error: invalid initialization of non-const reference of type ‘std::string& {aka std::basic_string&}’ from an rvalue of type ‘std::basic_string’
   if(hasWord(nextY, nextX, word.substr(1)))

why the reason I was wrong?

Body:
The reason of the error is that in this call

if(hasWord(nextY, nextX, word.substr(1)))
                         ^^^^^^^^^^^^^^

there is created a temporary object of the type std::string and you are trying to bind a non-constant reference with the temporary object.

If the string is not changed in the function then just declare the function  like

bool hasWord(int y, int x, const string &word) {
                           ^^^^^


问:
Group columns in ExtJS Grid
I am new to ExtJS and cannot seem to figure out how to group columns with its own header.  An example of what I'm trying to accomplish is below:

```<code>+-----------------------+-----------------------+
|        Group 1        |        Group 2        |
+-------+-------+-------+-------+-------+-------+
| col1  | col2  | col3  | col4  | col5  | col6  |
+-------+-------+-------+-------+-------+-------+
|                                               |
|                 data goes here                |
|                                               |
+-----------------------------------------------+
</code>```

Obviously, by default I can get col1 through col6 as they are the standard columns.  However, I want to add the group names above them.  How would I go about doing this or is there a resource that already shows how to do this?  I have searched Google for about an hour with no prevail.  Thanks in advance for your help!

答:
It looks like you are looking for the pivot grid:

http://dev.sencha.com/deploy/dev/examples/pivotgrid/simple.html

ContentLicense: CC BY-SA 2.5

Title: Group columns in ExtJS Grid

Body:
I am new to ExtJS and cannot seem to figure out how to group columns with its own header.  An example of what I'm trying to accomplish is below:

+-----------------------+-----------------------+
|        Group 1        |        Group 2        |
+-------+-------+-------+-------+-------+-------+
| col1  | col2  | col3  | col4  | col5  | col6  |
+-------+-------+-------+-------+-------+-------+
|                                               |
|                 data goes here                |
|                                               |
+-----------------------------------------------+

Obviously, by default I can get col1 through col6 as they are the standard columns.  However, I want to add the group names above them.  How would I go about doing this or is there a resource that already shows how to do this?  I have searched Google for about an hour with no prevail.  Thanks in advance for your help!


问:
Getting Error Like RequestsLimitError: You just made too many request to instagram API in node js?
I am work with isntagram api in node js. i have one array and in the array store above 20k up instagram id. and  then i am do foreach on that array and one by one take instagram id and go for the take bio but that time i am getting error like this RequestsLimitError: You just made too many request to instagram API. i am try every 5 call after set time out also but still i am getting same error so how can resolved this error any one know how can fix it then please let me know.

Here this is my code =>

```<code>var InstaId = ["12345687",20k more id store here in the array]

        var changesessionFlage = 0;
        async.each(InstaId, function (id, callback) {
            async.parallel([
                function (cb) {
                    if (id) {
                        setTimeout(function () {
                            Client.Account.getById(sess, id).then(function (bio) {
                                console.log("changesessionFlage" + changesessionFlage);
                                changesessionFlage++
                                //console.log("bio : ", bio._params);   // here  i am getting bio one by one user

                                if (changesessionFlage == 6) {
                                    changesessionFlage = 0;
                                }

                                cb(null, bio._params);

                            })
                           .catch(function (err) {
                               console.log("get boi: ", err)
                               cb(null, bio._params);
                           })
                          }, (changesessionFlage == 5) ? 10000 : 0)
                    }
                }
            ], function (err, results) {
                if (err) {
                    console.log(err);
                    return;
                }
                Result = results
                callback();
            });
        }, function (err) {
            if (err) {
                console.log(err);
                return;
            }
            else {
                console.log("Result=>", Result)
                if (Result) {
                    console.log("Result[0]=>", Result[0])
                    var ws = XLSX.utils.json_to_sheet(Result[0]);
                    var wb = XLSX.utils.book_new();
                    XLSX.utils.book_append_sheet(wb, ws, "People");
                    var wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
                    res.end(wbout, 'binary');
                }
            }
        });
</code>```

any one know how can fix this issue then please help me.

答:
Your setTimeout is use incorrectly, all API calls are made at once after 10000 delay.

Since this is a one time job, just split the 20K usernames to 4K batches and execute them every hour. This way you will be under the 5k/hr API limit

Body:
I am work with isntagram api in node js. i have one array and in the array store above 20k up instagram id. and  then i am do foreach on that array and one by one take instagram id and go for the take bio but that time i am getting error like this RequestsLimitError: You just made too many request to instagram API. i am try every 5 call after set time out also but still i am getting same error so how can resolved this error any one know how can fix it then please let me know.

Here this is my code =>

var InstaId = ["12345687",20k more id store here in the array]

        var changesessionFlage = 0;
        async.each(InstaId, function (id, callback) {
            async.parallel([
                function (cb) {
                    if (id) {
                        setTimeout(function () {
                            Client.Account.getById(sess, id).then(function (bio) {
                                console.log("changesessionFlage" + changesessionFlage);
                                changesessionFlage++
                                //console.log("bio : ", bio._params);   // here  i am getting bio one by one user

                                if (changesessionFlage == 6) {
                                    changesessionFlage = 0;
                                }

                                cb(null, bio._params);

                            })
                           .catch(function (err) {
                               console.log("get boi: ", err)
                               cb(null, bio._params);
                           })
                          }, (changesessionFlage == 5) ? 10000 : 0)
                    }
                }
            ], function (err, results) {
                if (err) {
                    console.log(err);
                    return;
                }
                Result = results
                callback();
            });
        }, function (err) {
            if (err) {
                console.log(err);
                return;
            }
            else {
                console.log("Result=>", Result)
                if (Result) {
                    console.log("Result[0]=>", Result[0])
                    var ws = XLSX.utils.json_to_sheet(Result[0]);
                    var wb = XLSX.utils.book_new();
                    XLSX.utils.book_append_sheet(wb, ws, "People");
                    var wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
                    res.end(wbout, 'binary');
                }
            }
        });

any one know how can fix this issue then please help me.


问:
Mapbox GL: Get Layer IDs
I have a map with a few dozen layers, each with a unique ID. I have checkboxes to turn the layers on and off, for which I need a single array of all the layer IDs. I can't figure out how to loop through all of the map layers to capture the layer IDs. I tried using map.getLayer() but this returns the layer as an object, not the layer ID as a string. I want to loop through all of the map layers and push the layer ID strings to a new array. How do I do this?

```<code>mapboxgl.accessToken = "myaccesstoken";

var map = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/mymapboxstyle",
center: [-71.0664, 42.358],
minZoom: 14 //
});

map.on("style.load", function () {

map.addSource("contours", {
    type: "vector",
    url: "mapbox://mapbox.mapbox-terrain-v2"
    });

map.addSource("hDistricts-2017", {
    "type": "vector",
    "url": "mapbox://mysource"
    });

map.addLayer({
    "id": "contours",
    "type": "line",
    "source": "contours",
    "source-layer": "contour",
    "layout": {
        "visibility": "none",
        "line-join": "round",
        "line-cap": "round"
        },
    "paint": {
        "line-color": "#877b59",
        "line-width": 1
        }
     });

map.addLayer({
    "id": "Back Bay Architectural District",
    "source": "hDistricts-2017",
    "source-layer": "Boston_Landmarks_Commission_B-7q48wq",
    "type": "fill",
    "layout": {
        "visibility": "none"
        },
    "filter": ["==", "OBJECTID", 13],
    "paint": {
        "fill-color": "#192E39",
        "fill-outline-color": "#000000",
        "fill-opacity": 0.5
        }
    });

});

var layerIds = [];

function getIds() {

  //here I need to iterate through map layers to get id strings.
  //how do I do this???

 layerIds.push(    ); //then push those ids to new array.

 console.log(layerIds); //["contours", "Back Bay Architectural District"]

}
</code>```

答:
You have the layer ids when you add the layer; you can save them then:</p>

```<code>function addLayer(map, options, layerIds) {
    map.addLayer(options);
    layerIds.push(options.id);
}

addLayer(map, {
    "id": "Back Bay Architectural District",
    "source": "hDistricts-2017",
    "source-layer": "Boston_Landmarks_Commission_B-7q48wq",
    "type": "fill",
    "layout": {
        "visibility": "none"
        },
    "filter": ["==", "OBJECTID", 13],
    "paint": {
        "fill-color": "#192E39",
        "fill-outline-color": "#000000",
        "fill-opacity": 0.5
        }
    },
    layerIds);
</code>```

Title: Mapbox GL: Get Layer IDs

Body:
I have a map with a few dozen layers, each with a unique ID. I have checkboxes to turn the layers on and off, for which I need a single array of all the layer IDs. I can't figure out how to loop through all of the map layers to capture the layer IDs. I tried using map.getLayer() but this returns the layer as an object, not the layer ID as a string. I want to loop through all of the map layers and push the layer ID strings to a new array. How do I do this?

mapboxgl.accessToken = "myaccesstoken";

var map = new mapboxgl.Map({
container: "map",
style: "mapbox://styles/mymapboxstyle",
center: [-71.0664, 42.358],
minZoom: 14 //
});

map.on("style.load", function () {

map.addSource("contours", {
    type: "vector",
    url: "mapbox://mapbox.mapbox-terrain-v2"
    });

map.addSource("hDistricts-2017", {
    "type": "vector",
    "url": "mapbox://mysource"
    });

map.addLayer({
    "id": "contours",
    "type": "line",
    "source": "contours",
    "source-layer": "contour",
    "layout": {
        "visibility": "none",
        "line-join": "round",
        "line-cap": "round"
        },
    "paint": {
        "line-color": "#877b59",
        "line-width": 1
        }
     });

map.addLayer({
    "id": "Back Bay Architectural District",
    "source": "hDistricts-2017",
    "source-layer": "Boston_Landmarks_Commission_B-7q48wq",
    "type": "fill",
    "layout": {
        "visibility": "none"
        },
    "filter": ["==", "OBJECTID", 13],
    "paint": {
        "fill-color": "#192E39",
        "fill-outline-color": "#000000",
        "fill-opacity": 0.5
        }
    });

});

var layerIds = [];

function getIds() {

  //here I need to iterate through map layers to get id strings.
  //how do I do this???

 layerIds.push(    ); //then push those ids to new array.

 console.log(layerIds); //["contours", "Back Bay Architectural District"]

}

Body:
You have the layer ids when you add the layer; you can save them then:

function addLayer(map, options, layerIds) {
    map.addLayer(options);
    layerIds.push(options.id);
}

addLayer(map, {
    "id": "Back Bay Architectural District",
    "source": "hDistricts-2017",
    "source-layer": "Boston_Landmarks_Commission_B-7q48wq",
    "type": "fill",
    "layout": {
        "visibility": "none"
        },
    "filter": ["==", "OBJECTID", 13],
    "paint": {
        "fill-color": "#192E39",
        "fill-outline-color": "#000000",
        "fill-opacity": 0.5
        }
    },
    layerIds);


问:
How can you write/delete/read a file in a different user account with the same ip address with python?
Recently, I learnt how to write/delete/read a file in Python (I am a beginner). However, something has got me thinking: is it possible to write/delete/read a file  in a different user account from the same network (i.e same ip address)? If so, how? Don't worry, I'll just try it at home. ;)</p>

答: If you can remove the file without Python, then you can remove it with Python. Otherwise, the answer is "no".</p>


问:
Modify uid in ldap repository
I'm developping an application spring-boot for get user information on Ldap repository using LdapTemplate.

I use user email as uid, when a user update his email I have to update his uid too. The problem is that the methods below work for all Person fields but not for UID. I get an error:

```<code>LDAP: error code 64 - value of naming attribute 'uid' is not present in entry
</code>```

This is a snippet:

```<code>public void updateUser(Person p) throws InvalidNameException {
    Name dn = buildDn(p);
    DirContextOperations context = ldapTemplate.lookupContext(dn);
    LdapMapper.mapToContext(p, context);
    ldapTemplate.modifyAttributes(context);
}
</code>```

BuildDn:

```<code>public Name buildDn(Person p) throws InvalidNameException {
    List<Rdn> lstRdn = new ArrayList<Rdn>();
    lstRdn.add(new Rdn("dc", "priv"));
    lstRdn.add(new Rdn("dc", "com"));
    lstRdn.add(new Rdn("ou", "customers"));
    lstRdn.add(new Rdn("ou", "myusers");
    lstRdn.add(new Rdn("uid", "oldUid"));

    Name name = new LdapName(lstRdn);

    return name;
}
</code>```

Mapper

```<code>public static void mapToContext(Person p, DirContextOperations context) {
    context.setAttributeValues("objectclass", new String[] { "top", "person", "inetOrgPerson", "organizationalPerson" });
    context.setAttributeValue("cn", p.getFirstName());
    context.setAttributeValue("sn", p.getLastName());
    context.setAttributeValue("mail", p.getEmail());
    context.setAttributeValue("userPassword", p.getPassword());
    context.setAttributeValue("uid", "NewUid");
}
</code>```

Would you have any ideas to fix this bug ?

Best regards

答:
You can't do a Modify on the uid field, instead you will have to rename the record to update the uid.

Like so:

ldapTemplate.rename("uid=oldUid,ou=People,dc=example,dc=com", "uid=newUid,ou=People,dc=example,dc=com")

instead of

ldapTemplate.modifyAttributes(context);.

Resource:
https://docs.spring.io/spring-ldap/docs/current/apidocs/org/springframework/ldap/core/LdapTemplate.html

Title: Modify uid in ldap repository

Body:
I'm developping an application spring-boot for get user information on Ldap repository using LdapTemplate.

I use user email as uid, when a user update his email I have to update his uid too. The problem is that the methods below work for all Person fields but not for UID. I get an error:

LDAP: error code 64 - value of naming attribute 'uid' is not present in entry

This is a snippet:

public void updateUser(Person p) throws InvalidNameException {
    Name dn = buildDn(p);
    DirContextOperations context = ldapTemplate.lookupContext(dn);
    LdapMapper.mapToContext(p, context);
    ldapTemplate.modifyAttributes(context);
}

BuildDn:

public Name buildDn(Person p) throws InvalidNameException {
    List<Rdn> lstRdn = new ArrayList<Rdn>();
    lstRdn.add(new Rdn("dc", "priv"));
    lstRdn.add(new Rdn("dc", "com"));
    lstRdn.add(new Rdn("ou", "customers"));
    lstRdn.add(new Rdn("ou", "myusers");
    lstRdn.add(new Rdn("uid", "oldUid"));

    Name name = new LdapName(lstRdn);

    return name;
}

Mapper

public static void mapToContext(Person p, DirContextOperations context) {
    context.setAttributeValues("objectclass", new String[] { "top", "person", "inetOrgPerson", "organizationalPerson" });
    context.setAttributeValue("cn", p.getFirstName());
    context.setAttributeValue("sn", p.getLastName());
    context.setAttributeValue("mail", p.getEmail());
    context.setAttributeValue("userPassword", p.getPassword());
    context.setAttributeValue("uid", "NewUid");
}

Would you have any ideas to fix this bug ?

Best regards


问:
SQL Query: Select most recent entry for each distinct field value?
i have this table POSITION:

```<code>CREATE TABLE `position` (
  `idposition` bigint(20) NOT NULL AUTO_INCREMENT,
  `latitude` varchar(45) DEFAULT NULL,
  `longitude` varchar(45) DEFAULT NULL,
  `timestamp` datetime DEFAULT NULL,
  `fk_email` varchar(100) DEFAULT NULL,
</code>```

with this population:

```<code>idposition  latitude    longitude   timestamp              fk_email
        1   39.49333    -0.33667    2010-12-10 17:15:39     david@test.es
         4  39.47333    -0.36167    2010-12-11 09:58:47     ronald@test.es
         5  39.50333    -0.34267    2010-12-10 21:11:10     david@test.es
        10  39.44333    -0.41667    2010-12-12 18:17:26     fanny@test.es
        11  39.45199    -0.31967    2010-12-12 21:01:18     victor@test.es
        12  39.52133    -0.36167    2010-12-12 17:43:11     carlos@test.es
        13  39.43199    -0.31967    2010-12-14 15:45:25     victor@test.es
        14  39.41199    -0.34567    2010-12-14 20:46:09     victor@test.es
        15  39.43433    -0.41667    2010-12-14 17:29:39     maria@test.es
        16  39.44133    -0.42667    2010-12-12 19:17:33     maria@test.es
        17  39.50333    -0.35667    2010-12-13 16:36:22     angel@test.es
        196     39.46454    -0.38978    0000-00-00 00:00:00     fanny@test.es
        271     33.63883    -0.45024    2010-12-17 11:36:45     fanny@test.es
        273     39.46680    -0.39452    2010-12-20 00:00:00     fanny@test.es
        441     39.44133    -0.41467    2010-12-15 17:45:13     carlos@test.es
        5326    39.47316    -0.38351    2011-01-18 18:09:56     pablo@upv.es
</code>```

ok, i want to make  SQL Query, that returns to me THE LAST (NEWEST) POSITION OF EACH FK_EMAIL, i mean, for each fk_email, the position with the last (newest) timestamp, only one position (te last) for each email.

it is possible to do it? can someone help me with the query? is too munch hard for me

答:
Try this:</p>

```<code>select * from
(select idposition, latitude, longitude, timestamp, fk_email, row_number() over(partition by fk_email order by timestamp desc) as rownumber
from position
) derived
where rownumber = 1
</code>```

Body:
i have this table POSITION:

CREATE TABLE `position` (
  `idposition` bigint(20) NOT NULL AUTO_INCREMENT,
  `latitude` varchar(45) DEFAULT NULL,
  `longitude` varchar(45) DEFAULT NULL,
  `timestamp` datetime DEFAULT NULL,
  `fk_email` varchar(100) DEFAULT NULL,

with this population:

idposition  latitude    longitude   timestamp              fk_email
        1   39.49333    -0.33667    2010-12-10 17:15:39     david@test.es
         4  39.47333    -0.36167    2010-12-11 09:58:47     ronald@test.es
         5  39.50333    -0.34267    2010-12-10 21:11:10     david@test.es
        10  39.44333    -0.41667    2010-12-12 18:17:26     fanny@test.es
        11  39.45199    -0.31967    2010-12-12 21:01:18     victor@test.es
        12  39.52133    -0.36167    2010-12-12 17:43:11     carlos@test.es
        13  39.43199    -0.31967    2010-12-14 15:45:25     victor@test.es
        14  39.41199    -0.34567    2010-12-14 20:46:09     victor@test.es
        15  39.43433    -0.41667    2010-12-14 17:29:39     maria@test.es
        16  39.44133    -0.42667    2010-12-12 19:17:33     maria@test.es
        17  39.50333    -0.35667    2010-12-13 16:36:22     angel@test.es
        196     39.46454    -0.38978    0000-00-00 00:00:00     fanny@test.es
        271     33.63883    -0.45024    2010-12-17 11:36:45     fanny@test.es
        273     39.46680    -0.39452    2010-12-20 00:00:00     fanny@test.es
        441     39.44133    -0.41467    2010-12-15 17:45:13     carlos@test.es
        5326    39.47316    -0.38351    2011-01-18 18:09:56     pablo@upv.es

ok, i want to make  SQL Query, that returns to me THE LAST (NEWEST) POSITION OF EACH FK_EMAIL, i mean, for each fk_email, the position with the last (newest) timestamp, only one position (te last) for each email.

it is possible to do it? can someone help me with the query? is too munch hard for me

Body:
Try this:

select * from
(select idposition, latitude, longitude, timestamp, fk_email, row_number() over(partition by fk_email order by timestamp desc) as rownumber
from position
) derived
where rownumber = 1


问:
wfdb supported jvm 1.8.0_112 (using Octave and Windows)?
I am trying to install wfdb into octave on 64 bit Windows. I used the run of the mill installer to grab octave 4.2 and the JRE 8u112, both are the 64 bit versions. wfdb seems to install correctly and all the paths seem to be fine, but when I call

```<code>>> wfdbdemo
</code>```

I get the following error:

```<code>error: Cannot load on unsupported JVM: Java 1.8.0_112
</code>```

I am guessing that the newest version of JVM is too new for the wfdb toolbox? What version of the JVM should I get in order to run this?

Later...

OK, so the latest version o f wfdb on github does have the JVM 8 jar, so I snagged that. Now I get the error:

```<code>octave> wfdbdemo
error: javaMethod: could not find library or dependencies: C:\Program Files\Java\jre1.8.0_112\bin\client\jvm.dll
</code>```

I've not seen any jre folder called client. Apparently the call to javaMethod (line 100 in wfdbloadlib.m) return this.

Later (again)...

So this is a bug that has to do with Java. I fiddled the registry so that it says 'server' instead of 'client' now, but I still get no joy. Now the problem is

```<code>octave> wfdbdemo
error: javaMethod: could not find library or dependencies: C:\Program Files\Java\jre1.8.0_112\bin\server\jvm.dll
</code>```

But, the path C:\Program Files\Java\jre1.8.0_112\bin\server\jvm.dll certainly is there and all things are 64 bit --- with the possible exception of the wfdb jar that comes with the source code on github.

答:
I also have difficulty as you:

wfdb error: Cannot load WFDB JAR on unsupported JVM: Java 1.8.0_151
  error: called from
      wfdbloadlib at line 107 column 9
      wfdb at line 11 column 10

Here is what did to resolve the error:

Install the 64-bit Windows JDK (i.e., 7u80). This will result in two  folders in C:\Program Files:

C:\Program Files\Java\jre7
C:\Program Files\Java\jdk1.7.0_80

Setting the following Environment Variable in Windows:

Go to C:\Program Files\Java\jre7\bin, create the folder client, copy all files from server folder to client.

Then it should work as shown here:

Body:
I am trying to install wfdb into octave on 64 bit Windows. I used the run of the mill installer to grab octave 4.2 and the JRE 8u112, both are the 64 bit versions. wfdb seems to install correctly and all the paths seem to be fine, but when I call

>> wfdbdemo

I get the following error:

error: Cannot load on unsupported JVM: Java 1.8.0_112

I am guessing that the newest version of JVM is too new for the wfdb toolbox? What version of the JVM should I get in order to run this?

Later...

OK, so the latest version o f wfdb on github does have the JVM 8 jar, so I snagged that. Now I get the error:

octave> wfdbdemo
error: javaMethod: could not find library or dependencies: C:\Program Files\Java\jre1.8.0_112\bin\client\jvm.dll

I've not seen any jre folder called client. Apparently the call to javaMethod (line 100 in wfdbloadlib.m) return this.

Later (again)...

So this is a bug that has to do with Java. I fiddled the registry so that it says 'server' instead of 'client' now, but I still get no joy. Now the problem is

octave> wfdbdemo
error: javaMethod: could not find library or dependencies: C:\Program Files\Java\jre1.8.0_112\bin\server\jvm.dll

But, the path C:\Program Files\Java\jre1.8.0_112\bin\server\jvm.dll certainly is there and all things are 64 bit --- with the possible exception of the wfdb jar that comes with the source code on github.


问:
Unity - How to separate the children of a game object linearly?
The goal is to "expand" a given model so that each piece is view able individually to the user so that the user can interact with each object separately (w/o worrying about which object they are in fact manipulating).

So, how to dynamically separate a game objects children linearly?

Linear example:

So in the example there is an empty game object, which is the parent of 3 objects: a cube, sphere, and capsule. As the object is composed currently, the user cannot see all of the children.

In the 'expansion' example, I take each of the children and separate them linearly on the same axis by dragging each manually along the same axis (x in this case). How would one do this dynamically?

First thought is to calculate number of children a game object has, and run a loop on the parent that will move each child an increasing distance depending on which child is being moved. Ex: child_1 moves 3 units along the x axis, child_2 moves 6 units, child_3 9 units, et cetera.

Is this the best way to go about this? First instinct says this won't work in all cases depending on the size an object takes up. One child object might be many times larger then another. If this is the case, would it be better to separate the object not by units, but by moving each child object outside of each others collision boundaries?

答:
int numChildren = gameObject.transform.childCount;
for (int i = 0; i<numChildren; i++)
{
    for (int a = i+1; a<numChildren; a++)
    {
        while (gameObject.transform.GetChild(a).GetComponentInChildren<Collider>().bounds.Intersects
            (gameObject.transform.GetChild(i).GetComponentInChildren<Collider>().bounds))
        {
            // print
            Debug.Log("Bounds intersecting " + i + ":" + a);

            // moving
            gameObject.transform.GetChild(a).GetComponentInChildren<Transform>()
                .transform.Translate(Vector3.right * 1f, Space.World);
        }
    }
}
```

1 - Gets the number of child objects

2 - Uses a nested for loop to see if a child's bounds intersects with any other childs bounds.

Ex: A gameobject has 4 children, objects zero, one, two, and three. The nested loop will compare object zero (0) against object one (1), 0 against 2, 0:3, 1:2, 1:3, 2:3. In this way it compares each child's collider.bounds with every other child's to ensure none of the child objects are touching.

3 - If the objects are touching, it moves the one comparing until it is no longer intersecting the one it compared with. Ex: 0:1 moves object 1 until it is no longer colliding with object zero.

NOTE: *1f (in 'moving') should be adjusted to the desired gap of separation between objects.

EDIT:: code is not robust, error checking and handling are not implemented here.

Body:
int numChildren = gameObject.transform.childCount;
for (int i = 0; i<numChildren; i++)
{
    for (int a = i+1; a<numChildren; a++)
    {
        while (gameObject.transform.GetChild(a).GetComponentInChildren<Collider>().bounds.Intersects
            (gameObject.transform.GetChild(i).GetComponentInChildren<Collider>().bounds))
        {
            // print
            Debug.Log("Bounds intersecting " + i + ":" + a);

            // moving
            gameObject.transform.GetChild(a).GetComponentInChildren<Transform>()
                .transform.Translate(Vector3.right * 1f, Space.World);
        }
    }
}

1 - Gets the number of child objects

2 - Uses a nested for loop to see if a child's bounds intersects with any other childs bounds.

Ex: A gameobject has 4 children, objects zero, one, two, and three. The nested loop will compare object zero (0) against object one (1), 0 against 2, 0:3, 1:2, 1:3, 2:3. In this way it compares each child's collider.bounds with every other child's to ensure none of the child objects are touching.

3 - If the objects are touching, it moves the one comparing until it is no longer intersecting the one it compared with. Ex: 0:1 moves object 1 until it is no longer colliding with object zero.

NOTE: *1f (in 'moving') should be adjusted to the desired gap of separation between objects.

EDIT:: code is not robust, error checking and handling are not implemented here.


问:
WPF Bind UserControl Property inside of the DataTemplate of a GridViewColumn.CellTemplate
I'm trying to figure out how to bind a property of a custom user control that is placed inside of the cell template of a list view control but it's not working. All of the DisplayMemberBinding fields are working as expected, and I'm getting the correct values, but inside of that custom control, nothing is updating.

WPF LIstView Control

```<code><ListView Margin="10" x:Name="lvHistory">
                <ListView.Resources>
                    <Style TargetType="{x:Type GridViewColumnHeader}">
                        <Setter Property="HorizontalContentAlignment" Value="Left" />
                    </Style>
                </ListView.Resources>
                <ListView.View>
                    <GridView>
                        <GridViewColumn Header="Database" Width="150" DisplayMemberBinding="{Binding ActiveBackup.Database.Name, Mode=TwoWay}"  />
                        <GridViewColumn Header="Start Time" Width="130" DisplayMemberBinding="{Binding ActiveBackup.StartTime, Mode=TwoWay}" />
                        <GridViewColumn Header="Time Elapsed" Width="100" DisplayMemberBinding="{Binding ActiveBackup.TimeElapsed, Mode=TwoWay}" />
                        <GridViewColumn Header="P2" Width="100" DisplayMemberBinding="{Binding Progress, Mode=TwoWay}" />
                        <GridViewColumn x:Name="progressColumn" Header="Progress" Width="150">
                            <GridViewColumn.CellTemplate>
                                <DataTemplate>
                                    <local:cProgressBarSmall x:Name="pr1" Value="{Binding Progress, Mode=TwoWay}" Visibility="Visible" />
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                        </GridViewColumn>
                    </GridView>
                </ListView.View>
            </ListView>
</code>```

Code-Behind in the cProgressBarSmall control.

```<code>public partial class cProgressBarSmall : UserControl
    {
        public ActiveBackup ActiveBackup { get; set; }

        public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(decimal), typeof(cProgressBarSmall));

        private decimal _value;
        public decimal Value
        {
            get
            {
                return (decimal) GetValue(ValueProperty);
            }
            set
            {
                _value = value;
                SetValue(ValueProperty, value);
                p1.Value = value.ToDoubleNotNull();
                pLabel.Text = value.ToPercent(0);
                if (value == 0)
                {
                    p1.Visibility = Visibility.Hidden;
                    pLabel.Visibility = Visibility.Hidden;
                }
                else if (value.ToDoubleNotNull() >= p1.Maximum)
                {
                    pLabel.Text = "Finished!";
                    pLabel.Foreground = new SolidColorBrush(Colors.Black);
                }
            }
        }
    }
}
</code>```

I can't find a way to access the "pr1" because it's in a DataTemplate and therefore not directly accessible from the code-behind. Does binding not work through? The column before it (the "P2" column) is just at test column I put in just to make sure that the value is in fact updating and it is and that displays correctly, however the "progressColumn" always just shows the default value.

Is there anything special to data binding inside of a ListView.View > GridView > GridViewColumn > GridViewColumn.CellTemplate > DataTemplate hierarchy?

答:
First, if you put a breakpoint in your setter you'll find that it's not hit by the binding. That's because the Binding is setting the dependency property, not the C# property. They're different. The C# property with get/set is an optional wrapper around the dependency property.

The correct way to do this is to have little or no code behind (code behind's not evil; you just don't need any for this one), but use a binding in the usercontrol xaml to update the UI. You can hide and show controls, and update label text, with style triggers in the usercontrol XAML. You don't need any code behind for this.

But here's the simplest way to adapt your existing code to something that works.

```<code>    public decimal Value
    {
        get { return (decimal)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }

    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register("Value", typeof(decimal), typeof(cProgressBarSmall),
            new PropertyMetadata(0m, Value_ChangedCallback));

    //  Has to be static
    private static void Value_ChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ((cProgressBarSmall)d).OnValueChanged();
    }

    private void OnValueChanged()
    {
        p1.Value = Value.ToDoubleNotNull();
        pLabel.Text = Value.ToPercent(0);
        if (Value == 0)
        {
            p1.Visibility = Visibility.Hidden;
            pLabel.Visibility = Visibility.Hidden;
        }
        else if (Value.ToDoubleNotNull() >= p1.Maximum)
        {
            pLabel.Text = "Finished!";
            pLabel.Foreground = new SolidColorBrush(Colors.Black);
        }
    }
</code>```

Body:
I'm trying to figure out how to bind a property of a custom user control that is placed inside of the cell template of a list view control but it's not working. All of the DisplayMemberBinding fields are working as expected, and I'm getting the correct values, but inside of that custom control, nothing is updating.

WPF LIstView Control

<ListView Margin="10" x:Name="lvHistory">
                <ListView.Resources>

                </ListView.Resources>
                <ListView.View>
                    <GridView>
                        <GridViewColumn Header="Database" Width="150" DisplayMemberBinding="{Binding ActiveBackup.Database.Name, Mode=TwoWay}"  />
                        <GridViewColumn Header="Start Time" Width="130" DisplayMemberBinding="{Binding ActiveBackup.StartTime, Mode=TwoWay}" />
                        <GridViewColumn Header="Time Elapsed" Width="100" DisplayMemberBinding="{Binding ActiveBackup.TimeElapsed, Mode=TwoWay}" />
                        <GridViewColumn Header="P2" Width="100" DisplayMemberBinding="{Binding Progress, Mode=TwoWay}" />
                        <GridViewColumn x:Name="progressColumn" Header="Progress" Width="150">
                            <GridViewColumn.CellTemplate>
                                <DataTemplate>
                                    <local:cProgressBarSmall x:Name="pr1" Value="{Binding Progress, Mode=TwoWay}" Visibility="Visible" />
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                        </GridViewColumn>
                    </GridView>
                </ListView.View>
            </ListView>

Code-Behind in the cProgressBarSmall control.

public partial class cProgressBarSmall : UserControl
    {
        public ActiveBackup ActiveBackup { get; set; }

        public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(decimal), typeof(cProgressBarSmall));

        private decimal _value;
        public decimal Value
        {
            get
            {
                return (decimal) GetValue(ValueProperty);
            }
            set
            {
                _value = value;
                SetValue(ValueProperty, value);
                p1.Value = value.ToDoubleNotNull();
                pLabel.Text = value.ToPercent(0);
                if (value == 0)
                {
                    p1.Visibility = Visibility.Hidden;
                    pLabel.Visibility = Visibility.Hidden;
                }
                else if (value.ToDoubleNotNull() >= p1.Maximum)
                {
                    pLabel.Text = "Finished!";
                    pLabel.Foreground = new SolidColorBrush(Colors.Black);
                }
            }
        }
    }
}

I can't find a way to access the "pr1" because it's in a DataTemplate and therefore not directly accessible from the code-behind. Does binding not work through? The column before it (the "P2" column) is just at test column I put in just to make sure that the value is in fact updating and it is and that displays correctly, however the "progressColumn" always just shows the default value.

Is there anything special to data binding inside of a ListView.View > GridView > GridViewColumn > GridViewColumn.CellTemplate > DataTemplate hierarchy?

Body:
First, if you put a breakpoint in your setter you'll find that it's not hit by the binding. That's because the Binding is setting the dependency property, not the C# property. They're different. The C# property with get/set is an optional wrapper around the dependency property.

The correct way to do this is to have little or no code behind (code behind's not evil; you just don't need any for this one), but use a binding in the usercontrol xaml to update the UI. You can hide and show controls, and update label text, with style triggers in the usercontrol XAML. You don't need any code behind for this.

But here's the simplest way to adapt your existing code to something that works.

    public decimal Value
    {
        get { return (decimal)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }

    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register("Value", typeof(decimal), typeof(cProgressBarSmall),
            new PropertyMetadata(0m, Value_ChangedCallback));

    //  Has to be static
    private static void Value_ChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ((cProgressBarSmall)d).OnValueChanged();
    }

    private void OnValueChanged()
    {
        p1.Value = Value.ToDoubleNotNull();
        pLabel.Text = Value.ToPercent(0);
        if (Value == 0)
        {
            p1.Visibility = Visibility.Hidden;
            pLabel.Visibility = Visibility.Hidden;
        }
        else if (Value.ToDoubleNotNull() >= p1.Maximum)
        {
            pLabel.Text = "Finished!";
            pLabel.Foreground = new SolidColorBrush(Colors.Black);
        }
    }


问:
Show progress bar when sending pages to the printer (WPF)
I am creating printouts in WPF using flow documents. These printouts are set in separate window where DocumentViewer is placed.
When user clicks print I would like to show a progress bar that informs about current page that is sending to the printer. How can I do this?</p>

答:
I'm not sure exactly where your print code is, or where you want the progress bar, but I did something similar to this recently. This will be in VB.net.

First of all, create a new progressbar in the same class as the code you use to send the page to the printer. Then, we're going to take advantage of the "top-down" order in a block of code to change the progress bar.

The progress bar's value should be set to "0" be default. Now, in the code for sending the page to the printer, you're going to increase the progressbar's value (such as with the code "MyProgressBar.Value = MyProgressBar.Value + 1"). Put this code in between each line of the code you want to show progress for.

I would change the "+ 1" part of the code, however, to another value, so your progress bar progresses equally after each step. If you have three lines of code, then use "+ 33" (100\3), four lines use "+ 25", etc.

Finally, at the end of the code, set "MyProgressBar.Value = 100"

This only works, however, if you have access to a code longer than one line. For one line of code, I'm not sure how this works, unless you can get to the block of code that line points to.

If you have to use code from another class, you may need to do something like...

```<code>Dim MyWindowWhereProgressIs As New MyWindowWhereProgressIs
</code>```

And then, each time you need to change the value, try...

```<code>MyWindowWhereProgressIs.MyProgressBar.Value = MyWindowWhereProgressIs.MyProgressBar.Value + 1
</code>```

I'm not entirely sure whether or not those last two lines of code will work, as I'm away from Visual Studio right now, but it is worth a shot.

Body:
I'm not sure exactly where your print code is, or where you want the progress bar, but I did something similar to this recently. This will be in VB.net.

First of all, create a new progressbar in the same class as the code you use to send the page to the printer. Then, we're going to take advantage of the "top-down" order in a block of code to change the progress bar.

The progress bar's value should be set to "0" be default. Now, in the code for sending the page to the printer, you're going to increase the progressbar's value (such as with the code "MyProgressBar.Value = MyProgressBar.Value + 1"). Put this code in between each line of the code you want to show progress for.

I would change the "+ 1" part of the code, however, to another value, so your progress bar progresses equally after each step. If you have three lines of code, then use "+ 33" (100\3), four lines use "+ 25", etc.

Finally, at the end of the code, set "MyProgressBar.Value = 100"

This only works, however, if you have access to a code longer than one line. For one line of code, I'm not sure how this works, unless you can get to the block of code that line points to.

If you have to use code from another class, you may need to do something like...

Dim MyWindowWhereProgressIs As New MyWindowWhereProgressIs

And then, each time you need to change the value, try...

MyWindowWhereProgressIs.MyProgressBar.Value = MyWindowWhereProgressIs.MyProgressBar.Value + 1

I'm not entirely sure whether or not those last two lines of code will work, as I'm away from Visual Studio right now, but it is worth a shot.


问:
stopForeground(true) called on a Service, gets me a classname null issue
This is how I start my service:

```<code>    public void startService(){
        if (!isRunningInForeground()) {
            Log.i("#foregroundservice", "Starting service");
            bindIntent = new Intent(PSLocationService.this, PSLocationService.class);
            startService(bindIntent);
        }
    }
</code>```

I do this on the onStartCommand:

```<code>   @Override
public int onStartCommand(Intent intent, int flags, int startId) {
    PSLocationService.startId = startId;
    if (PSApplicationClass.getInstance().isAutoPilotAllowed() || PSTrip.getActiveTrip() != null) {
        Log.i("#foregroundservice", "onStartCommand");
        Intent notificationIntent = new Intent(this, PSTimelineFragmentsActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        Notification notification = new Notification.Builder(this)
                .setPriority(Notification.PRIORITY_MAX)
                .setContentTitle(getText(R.string.passenger_name))
                .setContentText(getText(R.string.getStarted_switch_on_toplabel))
                .setSmallIcon(R.drawable.notification_icon)
                .setContentIntent(pendingIntent)
                .build();
        startForeground(1338, notification);
    }
    return super.onStartCommand(intent, flags, startId);
}
</code>```

And when I disconnect from googleApiClient, I want to stop it like this:

```<code>  if (isRunningInForeground()) {
        Log.i("#foregroundservice", "Stopping service: " + bindIntent);
        stopForeground(true);
        stopSelf();
    }
</code>```

It always crashes at stopForeground(true) method with this error:

```<code>11-10 12:59:50.026: E/AndroidRuntime(10731): java.lang.NullPointerException: class name is null
11-10 12:59:50.026: E/AndroidRuntime(10731):    at android.content.ComponentName.<init>(ComponentName.java:114)
11-10 12:59:50.026: E/AndroidRuntime(10731):    at android.app.Service.stopForeground(Service.java:671)
11-10 12:59:50.026: E/AndroidRuntime(10731):    at nl.hgrams.passenger.core.tracking.PSLocationService.disconnectLocationClient(PSLocationService.java:272)
</code>```

答:
Did manage to make it work by calling stopForeground(true) from an activity class, and not my ApplicationClass.
Also instead of stopForeground, i do this:

```<code>Intent serviceIntent = new Intent(context, PSLocationService.class);
context.stopService(serviceIntent);
</code>```

Body:
This is how I start my service:

    public void startService(){
        if (!isRunningInForeground()) {
            Log.i("#foregroundservice", "Starting service");
            bindIntent = new Intent(PSLocationService.this, PSLocationService.class);
            startService(bindIntent);
        }
    }

I do this on the onStartCommand:

   @Override
public int onStartCommand(Intent intent, int flags, int startId) {
    PSLocationService.startId = startId;
    if (PSApplicationClass.getInstance().isAutoPilotAllowed() || PSTrip.getActiveTrip() != null) {
        Log.i("#foregroundservice", "onStartCommand");
        Intent notificationIntent = new Intent(this, PSTimelineFragmentsActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        Notification notification = new Notification.Builder(this)
                .setPriority(Notification.PRIORITY_MAX)
                .setContentTitle(getText(R.string.passenger_name))
                .setContentText(getText(R.string.getStarted_switch_on_toplabel))
                .setSmallIcon(R.drawable.notification_icon)
                .setContentIntent(pendingIntent)
                .build();
        startForeground(1338, notification);
    }
    return super.onStartCommand(intent, flags, startId);
}

And when I disconnect from googleApiClient, I want to stop it like this:

  if (isRunningInForeground()) {
        Log.i("#foregroundservice", "Stopping service: " + bindIntent);
        stopForeground(true);
        stopSelf();
    }

It always crashes at stopForeground(true) method with this error:

11-10 12:59:50.026: E/AndroidRuntime(10731): java.lang.NullPointerException: class name is null
11-10 12:59:50.026: E/AndroidRuntime(10731):    at android.content.ComponentName.<init>(ComponentName.java:114)
11-10 12:59:50.026: E/AndroidRuntime(10731):    at android.app.Service.stopForeground(Service.java:671)
11-10 12:59:50.026: E/AndroidRuntime(10731):    at nl.hgrams.passenger.core.tracking.PSLocationService.disconnectLocationClient(PSLocationService.java:272)

Body:
Did manage to make it work by calling stopForeground(true) from an activity class, and not my ApplicationClass.
Also instead of stopForeground, i do this:

Intent serviceIntent = new Intent(context, PSLocationService.class);
context.stopService(serviceIntent);


问:
Validation of number input with max input and maximum of 2 decimal places doesn't work
I have a number input field in a form. And I've set the maximum number of decimal places to be 2 and the maximum value to be 99999999999999

If I try to submit a value of 99999999999999999 it detects it has too big and doesn't allow it.
If I try to submit 99.123 it detects it has too many decimal places and doesn't allow it.

But if I try to submit 99999999999996.123 it doesn't detect that it has too many decimal places.

How can I fix this?

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

app.controller('metadataCtrl', function ($scope, $http) {
    $scope.vm = { myItems : {} }

    $scope.item = {type: "a", value: 99999999999998};
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form ng-app="Appp" name="myForm" ng-controller="metadataCtrl">

  <input type="number"
         step="0.01"
         max="99999999999999"
         min="0"
         step-message="{name} can only have a maximum of 2 decimal places"
         ng-model="item.value"/>

  <input type="submit" value="Submit">

 </form></code>```

答:
It's not about decimal places, your input 99999999999996.123 is still lower than 99999999999999; max is not related  to decimal places but the number it self, if you want to validate decimal places you should create a directive validator you self. Furthermore, the step attribute doesn't limit decimal places but only specify that you have to use values that increments at the specified rate, that is, it will accept only values at multiples of the step.

Ref.: MDN web docs -<input>

Perhaps, you could use ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" that validates 2 decimal places. However, you will get problems using such a large number, because javascript number is defined by 64 bits so as the number grows you lose precision an it's hard to treat the input value as a number it self; for example: 9999999999999999 is evaluated to 10000000000000000.

The following example uses ng-pattern to validate decimal places, however, it doesn't prevent javascript Number pit falls.

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

app.controller('metadataCtrl', function($scope, $http) {
  $scope.vm = {
    myItems: {}
  }

  $scope.item = {
    type: "a",
    value: 9999999999999.99
  };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form ng-app="Appp" name="myForm" ng-controller="metadataCtrl">

  <input type="number"
         step="0.01"
         max="99999999999999"
         min="0"
         name="myField"
          ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/"
         ng-model="item.value"/>

  <input type="submit" value="Submit">
  <br>
  {{ myForm.myField.$error }}
  <br>
  <span ng-if="myForm.myField.$error.pattern">myField can only have a maximum of 2 decimal places</span>
</form></code>```

Body:
I have a number input field in a form. And I've set the maximum number of decimal places to be 2 and the maximum value to be 99999999999999

If I try to submit a value of 99999999999999999 it detects it has too big and doesn't allow it.
If I try to submit 99.123 it detects it has too many decimal places and doesn't allow it.

But if I try to submit 99999999999996.123 it doesn't detect that it has too many decimal places.

How can I fix this?

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

app.controller('metadataCtrl', function ($scope, $http) {
    $scope.vm = { myItems : {} }

    $scope.item = {type: "a", value: 99999999999998};
});

<form ng-app="Appp" name="myForm" ng-controller="metadataCtrl">

  <input type="number"
         step="0.01"
         max="99999999999999"
         min="0"
         step-message="{name} can only have a maximum of 2 decimal places"
         ng-model="item.value"/>

  <input type="submit" value="Submit">

 </form>

Body:
It's not about decimal places, your input 99999999999996.123 is still lower than 99999999999999; max is not related  to decimal places but the number it self, if you want to validate decimal places you should create a directive validator you self. Furthermore, the step attribute doesn't limit decimal places but only specify that you have to use values that increments at the specified rate, that is, it will accept only values at multiples of the step.

Ref.: MDN web docs -<input>

Perhaps, you could use ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" that validates 2 decimal places. However, you will get problems using such a large number, because javascript number is defined by 64 bits so as the number grows you lose precision an it's hard to treat the input value as a number it self; for example: 9999999999999999 is evaluated to 10000000000000000.

The following example uses ng-pattern to validate decimal places, however, it doesn't prevent javascript Number pit falls.

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

app.controller('metadataCtrl', function($scope, $http) {
  $scope.vm = {
    myItems: {}
  }

  $scope.item = {
    type: "a",
    value: 9999999999999.99
  };
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form ng-app="Appp" name="myForm" ng-controller="metadataCtrl">

  <input type="number"
         step="0.01"
         max="99999999999999"
         min="0"
         name="myField"
          ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/"
         ng-model="item.value"/>

  <input type="submit" value="Submit">
  <br>
  {{ myForm.myField.$error }}
  <br>
  <span ng-if="myForm.myField.$error.pattern">myField can only have a maximum of 2 decimal places</span>
</form>


问:
Dynamic QLabel misplacing in UI
I'm trying to create a program that accepts images through drag and drop and shows those images on my UI, then I want to rename them and save them.

I got the drag and drop to work, but I have some issues with my Image placement and I can't seem to find where I'm making my mistake.

In the image you see my UI during runtime, in the top left you can see a part of the image I dragged into the green zone(this is my drag and drop zone that accepts images). The position I actually want it to be in should be the red square. The green zone is a Dynamic created object called Imagehandler that I created to handle the drag and drop of the images. The Red square is my own class that inherits from QLabel, I called it myiconclass. This class should hold the actual image data.

I think my mistake has to do with the layouts, but I can't see it.

Could I get some help with this please?

Imagehandler.h

```<code>#ifndef IMAGEHANDLER_H
#define IMAGEHANDLER_H

#include <QObject>
#include <QWidget>
#include <QLabel>
#include <QDrag>
#include <QDragEnterEvent>
#include <QMimeData>
#include <QList>
#include <QDebug>

//this class is designed to help me take in the images with drag and drop

class ImageHandler : public QWidget
{
    Q_OBJECT
public:
    explicit ImageHandler(QWidget *parent = nullptr);

    QList<QImage> getImageListMemory() const;
    void setImageListMemory(const QList<QImage> &value);

    QList<QUrl> getUrlsMemory() const;
    void setUrlsMemory(const QList<QUrl> &value);

private:
    //QWidget Icon;
    QLabel Icon;
    QList <QImage> imageListMemory;
    QList <QUrl> urlsMemory;

protected:
    void dragEnterEvent(QDragEnterEvent * event);
    void dragLeaveEvent(QDragLeaveEvent * event);
    void dragMoveEvent(QDragMoveEvent * event);
    void dropEvent(QDropEvent * event);

signals:
    void transferImageSignal(QList <QImage>);

public slots:
};

#endif // IMAGEHANDLER_H
</code>```

mainwindow.h

```<code>#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QImageReader>
#include <QList>
#include <QWidget>
#include <QLabel>
#include <myiconclass.h>
#include <imagehandler.h>
#include <QGridLayout>
#include <QDebug>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

    QList<QImage> getImageListMemory() const;
    void setImageListMemory(const QList<QImage> &value);

private:
    Ui::MainWindow *ui;
    QLabel Icon;
    QList <QImage> imageListMemory;
    QList <QUrl> urlsMemory;
    QList<QWidget *> labelList;
    ImageHandler * ImageHandlerMemory;
    QGridLayout * grid2;
    QList <MyIconClass *> memory;

signals:

public slots:
    void setIconSlot(QList <QImage>);

};

#endif // MAINWINDOW_H
</code>```

myiconclass.h

```<code>#ifndef MYICONCLASS_H
#define MYICONCLASS_H

#include <QWidget>
#include <QLabel>

//this class is based on a Qlabel and is only made so it can help me with the actual images, gives me more members if I need it

class MyIconClass : public QLabel
{
    Q_OBJECT
public:
    explicit MyIconClass(QWidget *parent = nullptr);

    int getMyNumber() const;
    void setMyNumber(int value);

private:
    int myNumber;

signals:

public slots:
};

#endif // MYICONCLASS_H
</code>```

imagehandler.cpp

```<code>#include "imagehandler.h"

ImageHandler::ImageHandler(QWidget *parent) : QWidget(parent)
{
    setAcceptDrops(true);
}

QList<QImage> ImageHandler::getImageListMemory() const
{
    return imageListMemory;
}

void ImageHandler::setImageListMemory(const QList<QImage> &value)
{
    imageListMemory = value;
}

QList<QUrl> ImageHandler::getUrlsMemory() const
{
    return urlsMemory;
}

void ImageHandler::setUrlsMemory(const QList<QUrl> &value)
{
    urlsMemory = value;
}

void ImageHandler::dragEnterEvent(QDragEnterEvent * event)
{
    event->accept();
}

void ImageHandler::dragLeaveEvent(QDragLeaveEvent * event)
{
    event->accept();
}

void ImageHandler::dragMoveEvent(QDragMoveEvent * event)
{
    event->accept();
}

void ImageHandler::dropEvent(QDropEvent * event)
{
    QList <QImage> imageList2;

    QList <QUrl> urls;
    QList <QUrl>::iterator i;
    urls = event->mimeData()->urls();

    //imageList.append(event->mimeData()->imageData());

    foreach (const QUrl &url, event->mimeData()->urls())
    {
            QString fileName = url.toLocalFile();
            qDebug() << "Dropped file:" << fileName;
            qDebug()<<url.toString();

            QImage img;
            if(img.load(fileName))
            {
                imageList2.append(img);
            }

    }

  emit transferImageSignal(imageList2);

    this->setUrlsMemory(urls);
    this->setImageListMemory(imageList2);

}
</code>```

mainwindow.cpp

```<code>#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ImageHandler * handler = new ImageHandler(this);
    handler->show();
    QGridLayout *grid = new QGridLayout;

    grid->addWidget(handler, 0, 0);

    ui->groupBoxIcon->setLayout(grid);

    ImageHandlerMemory = handler;

    //connect(handler,SIGNAL(handler->transferImageSignal(QList <QUrl>)),this,SLOT(setIconSlot(QList <QUrl>)));
    connect(handler,SIGNAL(transferImageSignal(QList<QImage>)),this,SLOT(setIconSlot(QList<QImage>)));

}

MainWindow::~MainWindow()
{
    delete ui;
}

QList<QImage> MainWindow::getImageListMemory() const
{
    return imageListMemory;
}

void MainWindow::setImageListMemory(const QList<QImage> &value)
{
    imageListMemory = value;
}

void MainWindow::setIconSlot(QList<QImage> images)
{
    printf("succes!");
    this->setImageListMemory(images); //save the images to memory

    QGridLayout *grid = new QGridLayout; //create the grid layout I want my images to be in
    // create counters to remember the row and column in the grid
    int counterRow =0;
    int counterColumn =0;
    int counter3 =0;
    int counterImages = 0;

    //iterate over each image in the list
    QList <QImage>::iterator x;
    for(x = imageListMemory.begin(); x != imageListMemory.end(); x++)
    {
        MyIconClass * myLabel = new MyIconClass(this); //create an object of my own class (which is a Qlabel with an int member)
        QPixmap pixmap(QPixmap::fromImage(*x)); //create a pixmap from the image in the iteration
        myLabel->setPixmap(pixmap); //set the pixmap on my label object
        myLabel->show();
        memory.append(myLabel); //add it to the memory so I can recal it
        counterImages++;

    }

    while(counter3 < images.count())
    {
        grid2->addWidget(memory.value(counter3), counterRow, counterColumn);

        counterColumn++;
        counter3++;
        if(counterColumn >= 5)
        {
            counterRow++;
            counterColumn =0;
        }

    }
    if(ImageHandlerMemory->layout() == 0)
    {
        ImageHandlerMemory->setLayout(grid2);
    }

}
</code>```

myiconclass.cpp

```<code>#include "myiconclass.h"

MyIconClass::MyIconClass(QWidget *parent) :  QLabel(parent)
{

}

int MyIconClass::getMyNumber() const
{
    return myNumber;
}

void MyIconClass::setMyNumber(int value)
{
    myNumber = value;
}
</code>```

答:
As Benjamin T said I had to change this:

```<code>MyIconClass * myLabel = new MyIconClass(this);
</code>```

into this:

```<code>MyIconClass * myLabel = new MyIconClass(ImageHandlerMemory);
</code>```

Thanks Benjamin!

PS, I also had to add this line in my mainwindow constructor:

```<code>grid2 = new QGridLayout;
</code>```

ContentLicense: CC BY-SA 4.0

Title: Dynamic QLabel misplacing in UI

Body:
I'm trying to create a program that accepts images through drag and drop and shows those images on my UI, then I want to rename them and save them.

I got the drag and drop to work, but I have some issues with my Image placement and I can't seem to find where I'm making my mistake.

In the image you see my UI during runtime, in the top left you can see a part of the image I dragged into the green zone(this is my drag and drop zone that accepts images). The position I actually want it to be in should be the red square. The green zone is a Dynamic created object called Imagehandler that I created to handle the drag and drop of the images. The Red square is my own class that inherits from QLabel, I called it myiconclass. This class should hold the actual image data.

I think my mistake has to do with the layouts, but I can't see it.

Could I get some help with this please?

Imagehandler.h

#ifndef IMAGEHANDLER_H
#define IMAGEHANDLER_H

#include <QObject>
#include <QWidget>
#include <QLabel>
#include <QDrag>
#include <QDragEnterEvent>
#include <QMimeData>
#include <QList>
#include <QDebug>

//this class is designed to help me take in the images with drag and drop

class ImageHandler : public QWidget
{
    Q_OBJECT
public:
    explicit ImageHandler(QWidget *parent = nullptr);

    QList<QImage> getImageListMemory() const;
    void setImageListMemory(const QList<QImage> &value);

    QList<QUrl> getUrlsMemory() const;
    void setUrlsMemory(const QList<QUrl> &value);

private:
    //QWidget Icon;
    QLabel Icon;
    QList <QImage> imageListMemory;
    QList <QUrl> urlsMemory;

protected:
    void dragEnterEvent(QDragEnterEvent * event);
    void dragLeaveEvent(QDragLeaveEvent * event);
    void dragMoveEvent(QDragMoveEvent * event);
    void dropEvent(QDropEvent * event);

signals:
    void transferImageSignal(QList <QImage>);

public slots:
};

#endif // IMAGEHANDLER_H

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QImageReader>
#include <QList>
#include <QWidget>
#include <QLabel>
#include <myiconclass.h>
#include <imagehandler.h>
#include <QGridLayout>
#include <QDebug>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

    QList<QImage> getImageListMemory() const;
    void setImageListMemory(const QList<QImage> &value);

private:
    Ui::MainWindow *ui;
    QLabel Icon;
    QList <QImage> imageListMemory;
    QList <QUrl> urlsMemory;
    QList<QWidget *> labelList;
    ImageHandler * ImageHandlerMemory;
    QGridLayout * grid2;
    QList <MyIconClass *> memory;

signals:

public slots:
    void setIconSlot(QList <QImage>);

};

#endif // MAINWINDOW_H

myiconclass.h

#ifndef MYICONCLASS_H
#define MYICONCLASS_H

#include <QWidget>
#include <QLabel>

//this class is based on a Qlabel and is only made so it can help me with the actual images, gives me more members if I need it

class MyIconClass : public QLabel
{
    Q_OBJECT
public:
    explicit MyIconClass(QWidget *parent = nullptr);

    int getMyNumber() const;
    void setMyNumber(int value);

private:
    int myNumber;

signals:

public slots:
};

#endif // MYICONCLASS_H

imagehandler.cpp

#include "imagehandler.h"

ImageHandler::ImageHandler(QWidget *parent) : QWidget(parent)
{
    setAcceptDrops(true);
}

QList<QImage> ImageHandler::getImageListMemory() const
{
    return imageListMemory;
}

void ImageHandler::setImageListMemory(const QList<QImage> &value)
{
    imageListMemory = value;
}

QList<QUrl> ImageHandler::getUrlsMemory() const
{
    return urlsMemory;
}

void ImageHandler::setUrlsMemory(const QList<QUrl> &value)
{
    urlsMemory = value;
}

void ImageHandler::dragEnterEvent(QDragEnterEvent * event)
{
    event->accept();
}

void ImageHandler::dragLeaveEvent(QDragLeaveEvent * event)
{
    event->accept();
}

void ImageHandler::dragMoveEvent(QDragMoveEvent * event)
{
    event->accept();
}

void ImageHandler::dropEvent(QDropEvent * event)
{
    QList <QImage> imageList2;

    QList <QUrl> urls;
    QList <QUrl>::iterator i;
    urls = event->mimeData()->urls();

    //imageList.append(event->mimeData()->imageData());

    foreach (const QUrl &url, event->mimeData()->urls())
    {
            QString fileName = url.toLocalFile();
            qDebug() << "Dropped file:" << fileName;
            qDebug()<<url.toString();

            QImage img;
            if(img.load(fileName))
            {
                imageList2.append(img);
            }

    }

  emit transferImageSignal(imageList2);

    this->setUrlsMemory(urls);
    this->setImageListMemory(imageList2);

}

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ImageHandler * handler = new ImageHandler(this);
    handler->show();
    QGridLayout *grid = new QGridLayout;

    grid->addWidget(handler, 0, 0);

    ui->groupBoxIcon->setLayout(grid);

    ImageHandlerMemory = handler;

    //connect(handler,SIGNAL(handler->transferImageSignal(QList <QUrl>)),this,SLOT(setIconSlot(QList <QUrl>)));
    connect(handler,SIGNAL(transferImageSignal(QList<QImage>)),this,SLOT(setIconSlot(QList<QImage>)));

}

MainWindow::~MainWindow()
{
    delete ui;
}

QList<QImage> MainWindow::getImageListMemory() const
{
    return imageListMemory;
}

void MainWindow::setImageListMemory(const QList<QImage> &value)
{
    imageListMemory = value;
}

void MainWindow::setIconSlot(QList<QImage> images)
{
    printf("succes!");
    this->setImageListMemory(images); //save the images to memory

    QGridLayout *grid = new QGridLayout; //create the grid layout I want my images to be in
    // create counters to remember the row and column in the grid
    int counterRow =0;
    int counterColumn =0;
    int counter3 =0;
    int counterImages = 0;

    //iterate over each image in the list
    QList <QImage>::iterator x;
    for(x = imageListMemory.begin(); x != imageListMemory.end(); x++)
    {
        MyIconClass * myLabel = new MyIconClass(this); //create an object of my own class (which is a Qlabel with an int member)
        QPixmap pixmap(QPixmap::fromImage(*x)); //create a pixmap from the image in the iteration
        myLabel->setPixmap(pixmap); //set the pixmap on my label object
        myLabel->show();
        memory.append(myLabel); //add it to the memory so I can recal it
        counterImages++;

    }

    while(counter3 < images.count())
    {
        grid2->addWidget(memory.value(counter3), counterRow, counterColumn);

        counterColumn++;
        counter3++;
        if(counterColumn >= 5)
        {
            counterRow++;
            counterColumn =0;
        }

    }
    if(ImageHandlerMemory->layout() == 0)
    {
        ImageHandlerMemory->setLayout(grid2);
    }

}

myiconclass.cpp

#include "myiconclass.h"

MyIconClass::MyIconClass(QWidget *parent) :  QLabel(parent)
{

}

int MyIconClass::getMyNumber() const
{
    return myNumber;
}

void MyIconClass::setMyNumber(int value)
{
    myNumber = value;
}

Body:
As Benjamin T said I had to change this:

MyIconClass * myLabel = new MyIconClass(this);

into this:

MyIconClass * myLabel = new MyIconClass(ImageHandlerMemory);

Thanks Benjamin!

PS, I also had to add this line in my mainwindow constructor:

grid2 = new QGridLayout;


问:
How to unpivot columns and GROUP BY based on values in SQL Server?
I want to calculate distinct PID and VID counts per year.

Condition:

```<code>1. Separate count for column A or B or C or D  having value 1  ( A_to_D)
2. Separate count for column E  having value 1  (E)
3. Separate count for column F  having value 1   (F)
4. Separate count for ALL A to F column are NULL  (ALL_NULL)
</code>```

In the output I want a separate new column Alpha with the following values:

```<code>A_to_D, E, F and ALL_Null
</code>```

Current output of table:

```<code>PID VID Flag    Date        A       B       C       D       E       F
1   A1  0       10/17/2013  NULL    NULL    NULL    NULL    NULL    NULL
2   A2  1       5/27/2014   1       NULL    NULL    1       NULL    NULL
3   A3  NULL    2/23/2015   NULL    NULL    NULL    NULL    1       NULL
4   A4  NULL    12/6/2013   NULL    0       NULL    NULL    NULL    NULL
5   A5  NULL    7/14/2016   NULL    NULL    NULL    NULL    NULL    1
6   A6  NULL    4/29/2015   NULL    1       1       NULL    NULL    NULL
7   A7  1       9/30/2016   1       NULL    NULL    NULL    NULL    NULL
8   A8  NULL    6/28/2016   NULL    NULL    NULL    NULL    NULL    NULL
9   A9  1       11/20/2013  NULL    NULL    NULL    NULL    NULL    NULL
10  A10 2       10/8/2015   NULL    1       NULL    NULL    NULL    NULL
</code>```

Here:

```<code>select datepart(Year,date) ,Count(distinct PID) ,Count( distinct VID)
from table
where A is not null or B is Not NUll or C is not null
   or D is not null or E is not Null or F is not null
group by datepart(Year,date)
</code>```

Expected output:

```<code>Year        Count_PID       Count_VID       Alpha
2013                                        A_to_D
2013                                        E
2013                                        F
2013            2               2           ALL_NULL
2014            1               1           A_to_D
2014                                        E
2014                                        F
2014                                        ALL_NULL
2015            2               2           A_to_D
2015            1               1           E
2015                                        F
2015                                        ALL_NULL
2016            2               2           A_to_D
2016                                        E
2016            1                           F
2016            1                           ALL_NULL
</code>```

答:
I have followed the simple steps below to get to the result

1) pid_prep - Get the Year, PID and the Counts
2) vid_prep - Get the Year, VID and the Counts
3) pid_pivoted - Pivot the counts for PID
4) vid_pivoted - Pivot the counts for VID
5) main SELECT - Join pid_pivoted and vid_pivoted to get the result.

```<code>WITH pid_prep
AS
    (SELECT DISTINCT [PID], YEAR([Date]) AS Year,
           CASE WHEN [A] =1 OR [B] = 1 OR [C] = 1 OR [D] = 1 THEN 1 ELSE 0  END AS AToD,
           CASE WHEN [E] =1 THEN 1  ELSE 0 END AS E,
           CASE WHEN [F] =1 THEN 1  ELSE 0 END AS F,
           CASE WHEN COALESCE([A], [B], [C], [D], [E], [F]) IS NULL THEN 1 ELSE 0 END AS AllNull
      FROM @Table1),
vid_prep
AS
    (SELECT DISTINCT [VID], YEAR([Date]) AS Year,
           CASE WHEN [A] =1 OR [B] = 1 OR [C] = 1 OR [D] = 1 THEN 1 ELSE 0  END AS AToD,
           CASE WHEN [E] =1 THEN 1  ELSE 0 END AS E,
           CASE WHEN [F] =1 THEN 1  ELSE 0 END AS F,
           CASE WHEN COALESCE([A], [B], [C], [D], [E], [F]) IS NULL THEN 1 ELSE 0 END AS AllNull
      FROM @Table1),
pid_pivoted
AS
    (SELECT Year, cols, SUM(counts) AS counts
       FROM pid_prep
     UNPIVOT (counts for cols in (AToD, E, F, AllNull)) u
     GROUP BY Year, cols),
vid_pivoted
AS
    (SELECT Year, cols, SUM(counts) AS counts
       FROM vid_prep
     UNPIVOT (counts for cols in (AToD, E, F, AllNull)) v
      GROUP BY Year, cols)
SELECT pp.Year, NULLIF(pp.counts, 0) AS PID_counts, NULLIF(vp.counts, 0) AS VID_Counts, pp.cols
  FROM pid_pivoted pp LEFT JOIN
       vid_pivoted vp ON (pp.Year = vp.Year AND pp.cols = vp.cols)
ORDER BY pp.Year, pp.cols ;
</code>```

Output is as below. Let me know if you want anything explained.

Body:
I want to calculate distinct PID and VID counts per year.

Condition:

1. Separate count for column A or B or C or D  having value 1  ( A_to_D)
2. Separate count for column E  having value 1  (E)
3. Separate count for column F  having value 1   (F)
4. Separate count for ALL A to F column are NULL  (ALL_NULL)

In the output I want a separate new column Alpha with the following values:

A_to_D, E, F and ALL_Null

Current output of table:

PID VID Flag    Date        A       B       C       D       E       F
1   A1  0       10/17/2013  NULL    NULL    NULL    NULL    NULL    NULL
2   A2  1       5/27/2014   1       NULL    NULL    1       NULL    NULL
3   A3  NULL    2/23/2015   NULL    NULL    NULL    NULL    1       NULL
4   A4  NULL    12/6/2013   NULL    0       NULL    NULL    NULL    NULL
5   A5  NULL    7/14/2016   NULL    NULL    NULL    NULL    NULL    1
6   A6  NULL    4/29/2015   NULL    1       1       NULL    NULL    NULL
7   A7  1       9/30/2016   1       NULL    NULL    NULL    NULL    NULL
8   A8  NULL    6/28/2016   NULL    NULL    NULL    NULL    NULL    NULL
9   A9  1       11/20/2013  NULL    NULL    NULL    NULL    NULL    NULL
10  A10 2       10/8/2015   NULL    1       NULL    NULL    NULL    NULL

Here:

select datepart(Year,date) ,Count(distinct PID) ,Count( distinct VID)
from table
where A is not null or B is Not NUll or C is not null
   or D is not null or E is not Null or F is not null
group by datepart(Year,date)

Expected output:

Year        Count_PID       Count_VID       Alpha
2013                                        A_to_D
2013                                        E
2013                                        F
2013            2               2           ALL_NULL
2014            1               1           A_to_D
2014                                        E
2014                                        F
2014                                        ALL_NULL
2015            2               2           A_to_D
2015            1               1           E
2015                                        F
2015                                        ALL_NULL
2016            2               2           A_to_D
2016                                        E
2016            1                           F
2016            1                           ALL_NULL

Body:
I have followed the simple steps below to get to the result

1) pid_prep - Get the Year, PID and the Counts
2) vid_prep - Get the Year, VID and the Counts
3) pid_pivoted - Pivot the counts for PID
4) vid_pivoted - Pivot the counts for VID
5) main SELECT - Join pid_pivoted and vid_pivoted to get the result.

WITH pid_prep
AS
    (SELECT DISTINCT [PID], YEAR([Date]) AS Year,
           CASE WHEN [A] =1 OR [B] = 1 OR [C] = 1 OR [D] = 1 THEN 1 ELSE 0  END AS AToD,
           CASE WHEN [E] =1 THEN 1  ELSE 0 END AS E,
           CASE WHEN [F] =1 THEN 1  ELSE 0 END AS F,
           CASE WHEN COALESCE([A], [B], [C], [D], [E], [F]) IS NULL THEN 1 ELSE 0 END AS AllNull
      FROM @Table1),
vid_prep
AS
    (SELECT DISTINCT [VID], YEAR([Date]) AS Year,
           CASE WHEN [A] =1 OR [B] = 1 OR [C] = 1 OR [D] = 1 THEN 1 ELSE 0  END AS AToD,
           CASE WHEN [E] =1 THEN 1  ELSE 0 END AS E,
           CASE WHEN [F] =1 THEN 1  ELSE 0 END AS F,
           CASE WHEN COALESCE([A], [B], [C], [D], [E], [F]) IS NULL THEN 1 ELSE 0 END AS AllNull
      FROM @Table1),
pid_pivoted
AS
    (SELECT Year, cols, SUM(counts) AS counts
       FROM pid_prep
     UNPIVOT (counts for cols in (AToD, E, F, AllNull)) u
     GROUP BY Year, cols),
vid_pivoted
AS
    (SELECT Year, cols, SUM(counts) AS counts
       FROM vid_prep
     UNPIVOT (counts for cols in (AToD, E, F, AllNull)) v
      GROUP BY Year, cols)
SELECT pp.Year, NULLIF(pp.counts, 0) AS PID_counts, NULLIF(vp.counts, 0) AS VID_Counts, pp.cols
  FROM pid_pivoted pp LEFT JOIN
       vid_pivoted vp ON (pp.Year = vp.Year AND pp.cols = vp.cols)
ORDER BY pp.Year, pp.cols ;

Output is as below. Let me know if you want anything explained.