问:
clEnqueueNDRangeKernel Isn't running over full global range
I have a kernel.

```<code>__kernel void unprimed_grid_int(__global double *ar_u,
                                __global double *ap_u,
                                __global double *az_u,
                                __global const double *x_p,
                                __global const double *y_p,
                                __global const double *z_p,
                                __global const double *jx_p,
                                __global const double *jy_p,
                                __global const double *jz_p,
                                const uint nr,
                                const uint nz,
                                const uint nv,
                                const double rmin,
                                const double dr,
                                const double zmin,
                                const double dz,
                                const double dv,
                                const double dvol,
                                const uint p_size,
                                const uint offset) {

    const size_t i = get_global_id(0);

    const size_t ri = (i + offset)%nr;
    const size_t zi = ((i + offset)/nr)%nz;
    const size_t vi = ((i + offset)/(nr*nz))%nv;

    const double r = ri*dr + rmin;
    const double z = zi*dz + zmin;
    const double v = vi*dv;

    const double x = r*cos(v);
    const double y = r*sin(v);

    double ax = 0.0;
    double ay = 0.0;
    double az = 0.0;

    for (uint j = 0; j < p_size; j++) {
        const double dx = x_p[j] - x;
        const double dy = y_p[j] - y;
        const double dz = z_p[j] - z;

        const double rp = sqrt(dx*dx + dy*dy + dz*dz);

        ax += jx_p[j]/rp;
        ay += jy_p[j]/rp;
        az += jz_p[j]/rp;
    }

    ax *= dvol;
    ay *= dvol;
    az *= dvol;

    ar_u[i] += x/r*ax + y/r*ay;
    ap_u[i] += -y/r*ax + x/r*ay;
    az_u[i] += az;
}
</code>```

That i'm calling from

```<code>    const size_t offset = 0;
    clEnqueueNDRangeKernel(device->queue, device->kernels["int"], 1, &offset, &device->u_chunk, NULL, static_cast<cl_uint>(wait.size()), wait.data(), &event);
</code>```

with a global work size (device->u_chunk) of 734208. However the kernel, when run on my GPU, is only running over the first 2560 work items. I have checked the global work size inside the kernel by printing the value of get_global_size(0). If I add a print statement to check that what items of get_global_id(0), it runs over the full range.

What would cause a kernel to not run over the full range?

Update

To add an add an example of what's happening, here is a plot of the code output.

As you can see the kernel did not run over the full range. To further demonstrate this, I ran the test case suggested by one of the answers. I modified my kernel to add an extra argument.

```<code>__kernel void unprimed_grid_int(..., __global uint *test) {
   ...
   if (get_global_id(0) == 5) { //  Reran with 5 changed to 700000
      test[0] == 10;
   }
}
</code>```

For the global id value below where the output appears to cutoff (2560), I read back the correct value of 10. For a global id value above the cutoff, I get the incorrect value returned.

答: I figured out why my kernel wasn't operating over the full global range. The problem stems from the for loop in the kernel. p_size is on the order of 700000 iterations. This caused the kernel to take a long time to execute. Since my GPU's are connected to displays, the kernel is timing out so the UI doesn't lock up.

Body:
I have a kernel.

__kernel void unprimed_grid_int(__global double *ar_u,
                                __global double *ap_u,
                                __global double *az_u,
                                __global const double *x_p,
                                __global const double *y_p,
                                __global const double *z_p,
                                __global const double *jx_p,
                                __global const double *jy_p,
                                __global const double *jz_p,
                                const uint nr,
                                const uint nz,
                                const uint nv,
                                const double rmin,
                                const double dr,
                                const double zmin,
                                const double dz,
                                const double dv,
                                const double dvol,
                                const uint p_size,
                                const uint offset) {

    const size_t i = get_global_id(0);

    const size_t ri = (i + offset)%nr;
    const size_t zi = ((i + offset)/nr)%nz;
    const size_t vi = ((i + offset)/(nr*nz))%nv;

    const double r = ri*dr + rmin;
    const double z = zi*dz + zmin;
    const double v = vi*dv;

    const double x = r*cos(v);
    const double y = r*sin(v);

    double ax = 0.0;
    double ay = 0.0;
    double az = 0.0;

    for (uint j = 0; j < p_size; j++) {
        const double dx = x_p[j] - x;
        const double dy = y_p[j] - y;
        const double dz = z_p[j] - z;

        const double rp = sqrt(dx*dx + dy*dy + dz*dz);

        ax += jx_p[j]/rp;
        ay += jy_p[j]/rp;
        az += jz_p[j]/rp;
    }

    ax *= dvol;
    ay *= dvol;
    az *= dvol;

    ar_u[i] += x/r*ax + y/r*ay;
    ap_u[i] += -y/r*ax + x/r*ay;
    az_u[i] += az;
}

That i'm calling from

    const size_t offset = 0;
    clEnqueueNDRangeKernel(device->queue, device->kernels["int"], 1, &offset, &device->u_chunk, NULL, static_cast<cl_uint>(wait.size()), wait.data(), &event);

with a global work size (device->u_chunk) of 734208. However the kernel, when run on my GPU, is only running over the first 2560 work items. I have checked the global work size inside the kernel by printing the value of get_global_size(0). If I add a print statement to check that what items of get_global_id(0), it runs over the full range.

What would cause a kernel to not run over the full range?

Update

To add an add an example of what's happening, here is a plot of the code output.

As you can see the kernel did not run over the full range. To further demonstrate this, I ran the test case suggested by one of the answers. I modified my kernel to add an extra argument.

__kernel void unprimed_grid_int(..., __global uint *test) {
   ...
   if (get_global_id(0) == 5) { //  Reran with 5 changed to 700000
      test[0] == 10;
   }
}

For the global id value below where the output appears to cutoff (2560), I read back the correct value of 10. For a global id value above the cutoff, I get the incorrect value returned.


来源: stackexchange

问:
Errors in opscenterd.log after starting repair service
After upgrading from Opscenter 5.x > 6.0.8 > 6.1.0 > 6.1.1, I see lots of errors and warnings in the opscenterd.log, like the following. I'm using DSE 4.8.10. I've turned on the Repair Service, which seems to be working as expected. But I see WARNings in the log. Are these anything to be concerned about?</p>

```<code>2017-06-27 01:00:00,356 [local] ERROR: The best practice rule 'Tombstone count' has failed. (MainThread)
2017-06-27 01:00:00,358 [local] ERROR: The best practice rule 'Wide partitions' has failed. (MainThread)
2017-06-27 01:00:00,451 [local] ERROR: The best practice rule 'Secondary indexes cardinality' has failed. (MainThread)
2017-06-27 13:10:11,672 [opscenterd]  WARN: Unknown request 54688d7f-7c5f-4bcb-bc4d-07b7a0a79c3c (running {'started': 1498569009, 'details': u'Repair session f260e7b0-5b39-11e7-87cf-612516369059 for range (1042910172352712044,1065269862139026652] finished', 'details-type': None}) (MainThread)
2017-06-27 13:12:40,885 [opscenterd]  WARN: Unknown request 341c9bc9-1c00-4771-aa64-27206ad4152a (running {'started': 1498569160, 'details': u'Repair session 4c3d5c50-5b3a-11e7-87cf-612516369059 for range (-1555782662812296764,-1538702344225528661] finished', 'details-type': None}) (MainThread)
</code>```

答:
OpsCenter is warning about repair sessions on the Cassandra nodes that it doesn't recognize. They could be sessions that are hung up; there are a number of tickets related to that in Cassandra 2.1.x and older:

https://issues.apache.org/jira/browse/CASSANDRA-10012

https://issues.apache.org/jira/browse/CASSANDRA-10992

https://issues.apache.org/jira/browse/CASSANDRA-10961

https://issues.apache.org/jira/browse/CASSANDRA-12901

You could try to clean up these sessions by invoking forceTerminateAllRepairSessions via JMX on the StorageSession mbean. Or, a rolling restart on the cluster should do the trick.

Regardless, OpsCenter's Repair Service will operate normally.

ContentLicense: CC BY-SA 3.0

Body:
After upgrading from Opscenter 5.x > 6.0.8 > 6.1.0 > 6.1.1, I see lots of errors and warnings in the opscenterd.log, like the following. I'm using DSE 4.8.10. I've turned on the Repair Service, which seems to be working as expected. But I see WARNings in the log. Are these anything to be concerned about?

2017-06-27 01:00:00,356 [local] ERROR: The best practice rule 'Tombstone count' has failed. (MainThread)
2017-06-27 01:00:00,358 [local] ERROR: The best practice rule 'Wide partitions' has failed. (MainThread)
2017-06-27 01:00:00,451 [local] ERROR: The best practice rule 'Secondary indexes cardinality' has failed. (MainThread)
2017-06-27 13:10:11,672 [opscenterd]  WARN: Unknown request 54688d7f-7c5f-4bcb-bc4d-07b7a0a79c3c (running {'started': 1498569009, 'details': u'Repair session f260e7b0-5b39-11e7-87cf-612516369059 for range (1042910172352712044,1065269862139026652] finished', 'details-type': None}) (MainThread)
2017-06-27 13:12:40,885 [opscenterd]  WARN: Unknown request 341c9bc9-1c00-4771-aa64-27206ad4152a (running {'started': 1498569160, 'details': u'Repair session 4c3d5c50-5b3a-11e7-87cf-612516369059 for range (-1555782662812296764,-1538702344225528661] finished', 'details-type': None}) (MainThread)


问:
Regex-How to prevent repeated special characters?
I don't have an experience on Regular Expressions. I need to a regular expression which doesn't allow to repeat of special characters (+-*/& etc.)
The string can contain digits, alphanumerics, and special characters.

This should be valid : abc,df

This should be invalid : abc-,df

i will be really appreciated if you can help me ! Thanks for advance.

答:
Two solutions presented so far match a string that is not allowed.

But the tilte is How to prevent..., so I assume that the regex
should match the allowed string. It means that the regex should:

match the whole string if it does not contain 2
consecutive special characters,

not match otherwise.

You can achieve this putting together the following parts:

^ - start of string anchor,

(?!.*[...]{2}) - a negative lookahead for 2 consecutive special
characters (marked here as ...), in any place,

a regex matching the whole (non-empty) string,

$ - end of string anchor.

So the whole regex should be:

```<code>^(?!.*[!@#$%^&*()\-_+={}[\]|\\;:'",<.>\/?]{2}).+$
</code>```

Note that within a char class (between [ and ]) a backslash
escaping the following char should be placed before - (if in
the middle of the sequence), closing square bracket,
a backslash itself and / (regex terminator).

Or if you want to apply the regex to individual words (not the whole
string), then the regex should be:

```<code>\b(?!\S*[!@#$%^&*()\-_+={}[\]|\\;:'",<.>\/?]{2})\S+
</code>```

Body:
Two solutions presented so far match a string that is not allowed.

But the tilte is How to prevent..., so I assume that the regex
should match the allowed string. It means that the regex should:

match the whole string if it does not contain 2
consecutive special characters,

not match otherwise.

You can achieve this putting together the following parts:

^ - start of string anchor,

(?!.*[...]{2}) - a negative lookahead for 2 consecutive special
characters (marked here as ...), in any place,

a regex matching the whole (non-empty) string,

$ - end of string anchor.

So the whole regex should be:

^(?!.*[!@#$%^&*()\-_+={}[\]|\\;:'",<.>\/?]{2}).+$

Note that within a char class (between [ and ]) a backslash
escaping the following char should be placed before - (if in
the middle of the sequence), closing square bracket,
a backslash itself and / (regex terminator).

Or if you want to apply the regex to individual words (not the whole
string), then the regex should be:

\b(?!\S*[!@#$%^&*()\-_+={}[\]|\\;:'",<.>\/?]{2})\S+


问:
How do I get MySQL to return a ranking tied to a subquery?
I'm trying to make a chart that includes a couple variables charting the sum of ticket sales to a college sporting event by year and where it ranks among the other events present in the database. I'm having trouble figuring out a way to make the rank correspond to each row's individual year.

Here's what I'm starting with:

```<code>SELECT
Year as year,
School,
`Ticket Sales`,
(SELECT
    COUNT(School)+1
    FROM schools
    WHERE Year = 2016 AND `Ticket Sales` > (
        SELECT `Ticket Sales`
            FROM schools
            WHERE School = "College" AND Year = 2016)
        ) as Rank
FROM schools
WHERE School = "College"
ORDER BY Year DESC
</code>```

And here's what I'm getting back (notice it gives 15 - the rank for the first year - for every instance):

```<code>Year    School  Ticket Sales Rank
2016    College 29054868    15
2015    College 29586555    15
2014    College 26928635    15
2013    College 25888524    15
2012    College 23432735    15
2011    College 26467598    15
2010    College 18395654    15
2009    College 20711850    15
2008    College 17107971    15
2007    College 17287093    15
2006    College 15351891    15
2005    College 12767307    15
</code>```

Edit: To be clear, the number under rank should be different for each year. 2015's rank is different than 2016's and different than 2014's was, etc.

答:
I believe this is what you are trying to accomplish :

```<code>SELECT Year,
       School,
       sum(`Ticket Sales`) as `Ticket Sales`,
       Count(*) as Rank
FROM schools
WHERE School = "College"
GROUP BY Year,
      School
ORDER BY Year DESC
</code>```

See sample result here.

Body:
I'm trying to make a chart that includes a couple variables charting the sum of ticket sales to a college sporting event by year and where it ranks among the other events present in the database. I'm having trouble figuring out a way to make the rank correspond to each row's individual year.

Here's what I'm starting with:

SELECT
Year as year,
School,
`Ticket Sales`,
(SELECT
    COUNT(School)+1
    FROM schools
    WHERE Year = 2016 AND `Ticket Sales` > (
        SELECT `Ticket Sales`
            FROM schools
            WHERE School = "College" AND Year = 2016)
        ) as Rank
FROM schools
WHERE School = "College"
ORDER BY Year DESC

And here's what I'm getting back (notice it gives 15 - the rank for the first year - for every instance):

Year    School  Ticket Sales Rank
2016    College 29054868    15
2015    College 29586555    15
2014    College 26928635    15
2013    College 25888524    15
2012    College 23432735    15
2011    College 26467598    15
2010    College 18395654    15
2009    College 20711850    15
2008    College 17107971    15
2007    College 17287093    15
2006    College 15351891    15
2005    College 12767307    15

Edit: To be clear, the number under rank should be different for each year. 2015's rank is different than 2016's and different than 2014's was, etc.

Body:
I believe this is what you are trying to accomplish :

SELECT Year,
       School,
       sum(`Ticket Sales`) as `Ticket Sales`,
       Count(*) as Rank
FROM schools
WHERE School = "College"
GROUP BY Year,
      School
ORDER BY Year DESC

See sample result here.


问:
Ionic menu toggling caused page to not displaying property
Page displayed correctly when it is open. However some elements become not visible when I toggle the menu. Things such as icon, text, images.</p>

```<code> >ionic info
 ordova CLI: 7.0.1
Ionic CLI Version: 2.2.3
Ionic App Lib Version: 2.2.1
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Windows 10
Node Version: v6.10.2
Xcode version: Not installed
</code>```

答:
This is a temp fix for people also having this problem.

I found out the problem only happens when you scroll down then open the menu.
So all I did is to use scrollToTop method when user taps the menu.

 still waiting on the real solution.

Body:
Page displayed correctly when it is open. However some elements become not visible when I toggle the menu. Things such as icon, text, images.

 >ionic info
 ordova CLI: 7.0.1
Ionic CLI Version: 2.2.3
Ionic App Lib Version: 2.2.1
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Windows 10
Node Version: v6.10.2
Xcode version: Not installed


问:
How to figure out who owns a worker thread that is still running when my app exits?
Not long after upgrading to VS2010, my application won't shut down cleanly.  If I close the app and then hit pause in the IDE, I see this:

The problem is, there's no context.  The call stack just says [External code], which isn't too helpful.

Here's what I've done so far to try to narrow down the problem:

deleted all extraneous plugins to minimize the number of worker threads launched

set breakpoints in my code anywhere I create worker threads (and delegates + BeginInvoke, since I think they are labeled "Worker Thread" in the debugger anyway).  None were hit.

set IsBackground = true for all threads

While I could do the next brute force step, which is to roll my code back to a point where this didn't happen and then look over all of the change logs, this isn't terribly efficient.  Can anyone recommend a better way to figure this out, given the notable lack of information presented by the debugger?

The only other things I can think of include:

read up on WinDbg and try to use it to stop anytime a thread is started.  At least, I thought that was possible...  :)

comment out huge blocks of code until the app closes properly, then start uncommenting until it doesn't.

UPDATE

Perhaps this information will be of use.  I decided to use WinDbg and attach to my application.  I then closed it, and switched to thread 0 and dumped the stack contents.  Here's what I have:

```<code>ThreadCount:      6
UnstartedThread:  0
BackgroundThread: 1
PendingThread:    0
DeadThread:       4
Hosted Runtime:   no
                                   PreEmptive   GC Alloc                Lock
       ID  OSID ThreadOBJ    State GC           Context       Domain   Count APT Exception
   0    1  1c70 005a65c8      6020 Enabled  02dac6e0:02dad7f8 005a03c0     0 STA
   2    2  1b20 005b1980      b220 Enabled  00000000:00000000 005a03c0     0 MTA (Finalizer)
XXXX    3       08504048     19820 Enabled  00000000:00000000 005a03c0     0 Ukn
XXXX    4       08504540     19820 Enabled  00000000:00000000 005a03c0     0 Ukn
XXXX    5       08516a90     19820 Enabled  00000000:00000000 005a03c0     0 Ukn
XXXX    6       08517260     19820 Enabled  00000000:00000000 005a03c0     0 Ukn
0:008> ~0s
eax=c0674960 ebx=00000000 ecx=00000000 edx=00000000 esi=0040f320 edi=005a65c8
eip=76c37e47 esp=0040f23c ebp=0040f258 iopl=0         nv up ei pl nz na po nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000202
USER32!NtUserGetMessage+0x15:
76c37e47 83c404          add     esp,4
0:000> !clrstack
OS Thread Id: 0x1c70 (0)
Child SP IP       Call Site
0040f274 76c37e47 [InlinedCallFrame: 0040f274]
0040f270 6baa8976 DomainBoundILStubClass.IL_STUB_PInvoke(System.Windows.Interop.MSG ByRef, System.Runtime.InteropServices.HandleRef, Int32, Int32)*** WARNING: Unable to verify checksum for C:\Windows\assembly\NativeImages_v4.0.30319_32\WindowsBase\d17606e813f01376bd0def23726ecc62\WindowsBase.ni.dll

0040f274 6ba924c5 [InlinedCallFrame: 0040f274] MS.Win32.UnsafeNativeMethods.IntGetMessageW(System.Windows.Interop.MSG ByRef, System.Runtime.InteropServices.HandleRef, Int32, Int32)
0040f2c4 6ba924c5 MS.Win32.UnsafeNativeMethods.GetMessageW(System.Windows.Interop.MSG ByRef, System.Runtime.InteropServices.HandleRef, Int32, Int32)
0040f2dc 6ba8e5f8 System.Windows.Threading.Dispatcher.GetMessage(System.Windows.Interop.MSG ByRef, IntPtr, Int32, Int32)
0040f318 6ba8d579 System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame)
0040f368 6ba8d2a1 System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame)
0040f374 6ba7fba0 System.Windows.Threading.Dispatcher.Run()
0040f380 62e6ccbb System.Windows.Application.RunDispatcher(System.Object)*** WARNING: Unable to verify checksum for C:\Windows\assembly\NativeImages_v4.0.30319_32\PresentationFramewo#\7f91eecda3ff7ce478146b6458580c98\PresentationFramework.ni.dll

0040f38c 62e6c8ff System.Windows.Application.RunInternal(System.Windows.Window)
0040f3b0 62e6c682 System.Windows.Application.Run(System.Windows.Window)
0040f3c0 62e6c30b System.Windows.Application.Run()
0040f3cc 001f00bc MyApplication.App.Main() [C:\code\trunk\MyApplication\obj\Debug\GeneratedInternalTypeHelper.g.cs @ 24]
0040f608 66c421db [GCFrame: 0040f608]
</code>```

EDIT -- not sure if this helps, but the main thread's call stack looks like this:

```<code>    [Managed to Native Transition]
>   WindowsBase.dll!MS.Win32.UnsafeNativeMethods.GetMessageW(ref System.Windows.Interop.MSG msg, System.Runtime.InteropServices.HandleRef hWnd, int uMsgFilterMin, int uMsgFilterMax) + 0x15 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.GetMessage(ref System.Windows.Interop.MSG msg, System.IntPtr hwnd, int minMessage, int maxMessage) + 0x48 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame = {System.Windows.Threading.DispatcherFrame}) + 0x85 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame) + 0x49 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.Run() + 0x4c bytes
    PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) + 0x17 bytes
    PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) + 0x6f bytes
    PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window) + 0x26 bytes
    PresentationFramework.dll!System.Windows.Application.Run() + 0x1b bytes
</code>```

I did a search on it and found some posts related to WPF GUIs hanging, and maybe that'll give me some more clues.

答: Add logging to all your code to log the method and thread ID.  You can use a regex replace to put it at the start of every single method.  Then run the app and shut down.  See what log messages have the same thread id as the worker thread that doesn't shut down.</p>

ContentLicense: CC BY-SA 2.5

Body:
Not long after upgrading to VS2010, my application won't shut down cleanly.  If I close the app and then hit pause in the IDE, I see this:

The problem is, there's no context.  The call stack just says [External code], which isn't too helpful.

Here's what I've done so far to try to narrow down the problem:

deleted all extraneous plugins to minimize the number of worker threads launched

set breakpoints in my code anywhere I create worker threads (and delegates + BeginInvoke, since I think they are labeled "Worker Thread" in the debugger anyway).  None were hit.

set IsBackground = true for all threads

While I could do the next brute force step, which is to roll my code back to a point where this didn't happen and then look over all of the change logs, this isn't terribly efficient.  Can anyone recommend a better way to figure this out, given the notable lack of information presented by the debugger?

The only other things I can think of include:

read up on WinDbg and try to use it to stop anytime a thread is started.  At least, I thought that was possible...  :)

comment out huge blocks of code until the app closes properly, then start uncommenting until it doesn't.

UPDATE

Perhaps this information will be of use.  I decided to use WinDbg and attach to my application.  I then closed it, and switched to thread 0 and dumped the stack contents.  Here's what I have:

ThreadCount:      6
UnstartedThread:  0
BackgroundThread: 1
PendingThread:    0
DeadThread:       4
Hosted Runtime:   no
                                   PreEmptive   GC Alloc                Lock
       ID  OSID ThreadOBJ    State GC           Context       Domain   Count APT Exception
   0    1  1c70 005a65c8      6020 Enabled  02dac6e0:02dad7f8 005a03c0     0 STA
   2    2  1b20 005b1980      b220 Enabled  00000000:00000000 005a03c0     0 MTA (Finalizer)
XXXX    3       08504048     19820 Enabled  00000000:00000000 005a03c0     0 Ukn
XXXX    4       08504540     19820 Enabled  00000000:00000000 005a03c0     0 Ukn
XXXX    5       08516a90     19820 Enabled  00000000:00000000 005a03c0     0 Ukn
XXXX    6       08517260     19820 Enabled  00000000:00000000 005a03c0     0 Ukn
0:008> ~0s
eax=c0674960 ebx=00000000 ecx=00000000 edx=00000000 esi=0040f320 edi=005a65c8
eip=76c37e47 esp=0040f23c ebp=0040f258 iopl=0         nv up ei pl nz na po nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000202
USER32!NtUserGetMessage+0x15:
76c37e47 83c404          add     esp,4
0:000> !clrstack
OS Thread Id: 0x1c70 (0)
Child SP IP       Call Site
0040f274 76c37e47 [InlinedCallFrame: 0040f274]
0040f270 6baa8976 DomainBoundILStubClass.IL_STUB_PInvoke(System.Windows.Interop.MSG ByRef, System.Runtime.InteropServices.HandleRef, Int32, Int32)*** WARNING: Unable to verify checksum for C:\Windows\assembly\NativeImages_v4.0.30319_32\WindowsBase\d17606e813f01376bd0def23726ecc62\WindowsBase.ni.dll

0040f274 6ba924c5 [InlinedCallFrame: 0040f274] MS.Win32.UnsafeNativeMethods.IntGetMessageW(System.Windows.Interop.MSG ByRef, System.Runtime.InteropServices.HandleRef, Int32, Int32)
0040f2c4 6ba924c5 MS.Win32.UnsafeNativeMethods.GetMessageW(System.Windows.Interop.MSG ByRef, System.Runtime.InteropServices.HandleRef, Int32, Int32)
0040f2dc 6ba8e5f8 System.Windows.Threading.Dispatcher.GetMessage(System.Windows.Interop.MSG ByRef, IntPtr, Int32, Int32)
0040f318 6ba8d579 System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame)
0040f368 6ba8d2a1 System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame)
0040f374 6ba7fba0 System.Windows.Threading.Dispatcher.Run()
0040f380 62e6ccbb System.Windows.Application.RunDispatcher(System.Object)*** WARNING: Unable to verify checksum for C:\Windows\assembly\NativeImages_v4.0.30319_32\PresentationFramewo#\7f91eecda3ff7ce478146b6458580c98\PresentationFramework.ni.dll

0040f38c 62e6c8ff System.Windows.Application.RunInternal(System.Windows.Window)
0040f3b0 62e6c682 System.Windows.Application.Run(System.Windows.Window)
0040f3c0 62e6c30b System.Windows.Application.Run()
0040f3cc 001f00bc MyApplication.App.Main() [C:\code\trunk\MyApplication\obj\Debug\GeneratedInternalTypeHelper.g.cs @ 24]
0040f608 66c421db [GCFrame: 0040f608]

EDIT -- not sure if this helps, but the main thread's call stack looks like this:

    [Managed to Native Transition]
>   WindowsBase.dll!MS.Win32.UnsafeNativeMethods.GetMessageW(ref System.Windows.Interop.MSG msg, System.Runtime.InteropServices.HandleRef hWnd, int uMsgFilterMin, int uMsgFilterMax) + 0x15 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.GetMessage(ref System.Windows.Interop.MSG msg, System.IntPtr hwnd, int minMessage, int maxMessage) + 0x48 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame = {System.Windows.Threading.DispatcherFrame}) + 0x85 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame) + 0x49 bytes
    WindowsBase.dll!System.Windows.Threading.Dispatcher.Run() + 0x4c bytes
    PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) + 0x17 bytes
    PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) + 0x6f bytes
    PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window) + 0x26 bytes
    PresentationFramework.dll!System.Windows.Application.Run() + 0x1b bytes

I did a search on it and found some posts related to WPF GUIs hanging, and maybe that'll give me some more clues.


问:
Changing ConsoleKeyInfo into int
I am new to the programing c#. I tried to program a simple program that would run in cmd. I thought that it would randomly creat a noumber and the user would put in the numbers and he/she would try to guess the randomly created one. The program would tell you if it is lower or higher then the number you putted in... I started programing but I came to the problem... I can not compare noumber putted in by user and the randomly generated one.

This is the code...

```<code>class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Guess the number!");
        Random randomObject = new Random();
        int RandNoumber = randomObject.Next(9999) + 1;
        ConsoleKeyInfo keyinfo = Console.ReadKey();
        if (keyinfo < RandNoumber) //This is where I got an error msg
        {
        }
    }
}
</code>```

Thank you for all the support!

MP

答:
You could use Consol.ReadLine and then parse the value the user entered

```<code>static void Main(string[] args)
{
    Console.WriteLine("Guess the number!");
    Random randomObject = new Random();
    int RandNoumber = randomObject.Next(9999) + 1;

    int enteredNumber;
    while (true)
    {
        bool parsed = int.TryParse(Console.ReadLine(), out enteredNumber);

        if (parsed)
        {
            if (enteredNumber < RandNoumber)
            {
                Console.WriteLine("Wrong it's higher");
            }
            else if (enteredNumber > RandNoumber)
            {
                Console.WriteLine("Wrong it's lower");
            }
            else
            {
                Console.WriteLine("Good Job!");
                //Do victory dance
                return;
            }
        }
        else
        {
            Console.WriteLine("Please enter a number");
        }
    }
}
</code>```

Title: Changing ConsoleKeyInfo into int

Body:
I am new to the programing c#. I tried to program a simple program that would run in cmd. I thought that it would randomly creat a noumber and the user would put in the numbers and he/she would try to guess the randomly created one. The program would tell you if it is lower or higher then the number you putted in... I started programing but I came to the problem... I can not compare noumber putted in by user and the randomly generated one.

This is the code...

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Guess the number!");
        Random randomObject = new Random();
        int RandNoumber = randomObject.Next(9999) + 1;
        ConsoleKeyInfo keyinfo = Console.ReadKey();
        if (keyinfo < RandNoumber) //This is where I got an error msg
        {
        }
    }
}

Thank you for all the support!

MP

Body:
You could use Consol.ReadLine and then parse the value the user entered

static void Main(string[] args)
{
    Console.WriteLine("Guess the number!");
    Random randomObject = new Random();
    int RandNoumber = randomObject.Next(9999) + 1;

    int enteredNumber;
    while (true)
    {
        bool parsed = int.TryParse(Console.ReadLine(), out enteredNumber);

        if (parsed)
        {
            if (enteredNumber < RandNoumber)
            {
                Console.WriteLine("Wrong it's higher");
            }
            else if (enteredNumber > RandNoumber)
            {
                Console.WriteLine("Wrong it's lower");
            }
            else
            {
                Console.WriteLine("Good Job!");
                //Do victory dance
                return;
            }
        }
        else
        {
            Console.WriteLine("Please enter a number");
        }
    }
}


问:
How do I get child elements from class list object?
think I have some class of same content

```<code> <div class="parentclass">

         <div class="childClass">
         </div>
         <div class="childClass">
         </div>
         <div class="childClass">
         </div>
    </div>

  <div class="parentclass">

         <div class="childClass">
         </div>
         <div class="childClass">
         </div>
         <div class="childClass">
         </div>
    </div>
</code>```

I can get all the parent class object in an array by

```<code>var pClassList= document.getElementsByClassName("parentclass");
</code>```

My question is how can I access the child classes "childClass" from pClassList array calling it index like

```<code>var childClassList1= pClassList[0].getElementsByClassName("childClass");
var childClassList2= pClassList[1].getElementsByClassName("childClass");
</code>```

答:
Could be:

```<code>var childClassList1= pClassList[0].getElementsByClassName("childClass")[0];
var childClassList2= pClassList[1].getElementsByClassName("childClass")[0];
</code>```

I prefer to use JQuery, in this case it would be.

```<code>var pClassList = $(".parentclass")
var childClassList1 = $(pClassList[0]).children().first()
var childClassList2 = $(pClassList[1]).children().first()
</code>```

Body:
think I have some class of same content

I can get all the parent class object in an array by

var pClassList= document.getElementsByClassName("parentclass");

My question is how can I access the child classes "childClass" from pClassList array calling it index like

var childClassList1= pClassList[0].getElementsByClassName("childClass");
var childClassList2= pClassList[1].getElementsByClassName("childClass");

Body:
Could be:

var childClassList1= pClassList[0].getElementsByClassName("childClass")[0];
var childClassList2= pClassList[1].getElementsByClassName("childClass")[0];

I prefer to use JQuery, in this case it would be.

var pClassList = $(".parentclass")
var childClassList1 = $(pClassList[0]).children().first()
var childClassList2 = $(pClassList[1]).children().first()


问:
How to make a span from user selection (js)
I want to make a text editor. It should work the way all text editors work (including this one i am using right now), so the user makes a selection of the text, presses a button or whatever, and then some function is executed.
I want my editor to work in the following way:
1. User selects
2. Function selected() is triggered that makes a span around the selected text.
3. When user clicks a button such as "B" or "I", they invoke functions that change .style of the span element.
For now I figured out how to get string from user selection, nothing more than that. </p>

```<code>    <body>
        <textarea onselect="selected()">Some text here, more text here.</textarea>
    </body>
    <script>
        function selected() {
var preselection = window.getSelection();
    selection = preselection.toString();
    console.log(selection);
}
    </script>
</code>```

答:
textareas can't contain spans, so you will need to use something like this if you decide to use spans:

```<code><p contenteditable="true" ...
</code>```

You probably don't want to fire your function every time a user makes a selection. Instead, just run the function if a user presses a button (like the bold button) and then pick up the selected text, if any, using something like:

```<code>document.getSelection().toString()
</code>```

Now adding a  object to an HTML element is pretty easy, but the big challenge here is that you don't know if your selection will cross other span objects (like if the user already added some formatting). Notice that stackoverflow inserts characters like ** in the edit area and then does one pass to add in tags like . This is possible in a text area as well, so you wouldn't need contenteditable="true".

It is possible to analyze what is in your selection and then collect all elements involved, and rewrite them as needed. You would have to get all parent objects involved in the selection and then add  elements around the text inside each of the parent objects.

To simplify this, you might make a rule that only one level of tags is allowed in your editable region, and then always re-write for that so that the results would only have one level of span:

```<code><span class="bold">This whole sentence is italic and </span><span class="italic_bold">this half is also bold.</span> with no nesting of these span tags.
</code>```

Investigating these properties might help with dealing with nesting: https://developer.mozilla.org/en-US/docs/Web/API/Selection

These string commands might also help:
https://www.w3schools.com/jsref/jsref_obj_string.asp

Body:
I want to make a text editor. It should work the way all text editors work (including this one i am using right now), so the user makes a selection of the text, presses a button or whatever, and then some function is executed.
I want my editor to work in the following way:
1. User selects
2. Function selected() is triggered that makes a span around the selected text.
3. When user clicks a button such as "B" or "I", they invoke functions that change .style of the span element.
For now I figured out how to get string from user selection, nothing more than that.

        <textarea onselect="selected()">Some text here, more text here.</textarea>

Body:
textareas can't contain spans, so you will need to use something like this if you decide to use spans:

<p contenteditable="true" ...

You probably don't want to fire your function every time a user makes a selection. Instead, just run the function if a user presses a button (like the bold button) and then pick up the selected text, if any, using something like:

document.getSelection().toString()

Now adding a <span> object to an HTML element is pretty easy, but the big challenge here is that you don't know if your selection will cross other span objects (like if the user already added some formatting). Notice that stackoverflow inserts characters like ** in the edit area and then does one pass to add in tags like <strong>. This is possible in a text area as well, so you wouldn't need contenteditable="true".

It is possible to analyze what is in your selection and then collect all elements involved, and rewrite them as needed. You would have to get all parent objects involved in the selection and then add <span> elements around the text inside each of the parent objects.

To simplify this, you might make a rule that only one level of tags is allowed in your editable region, and then always re-write for that so that the results would only have one level of span:

<span class="bold">This whole sentence is italic and </span><span class="italic_bold">this half is also bold.</span> with no nesting of these span tags.

Investigating these properties might help with dealing with nesting: https://developer.mozilla.org/en-US/docs/Web/API/Selection

These string commands might also help:
https://www.w3schools.com/jsref/jsref_obj_string.asp


问:
How to get number of properties from file stream
I save particular object in external file like this:

```<code> public void SaveSettings(string SavedFilePath, object Class)
        {

            //open the stream to write the new file
            using (Stream StreamFile = File.Open(SavedFilePath, FileMode.CreateNew))
            {
                //instantiate the binary formatter object
                BinaryFormatter binformat = new BinaryFormatter();

                //loop through all properties in input object
                foreach (PropertyInfo prop in Class.GetType().GetProperties())
                {
                    //if the property is serailizable then serialize it and write its name and value in external file
                    if (prop.PropertyType.IsSerializable)
                        binformat.Serialize(StreamFile, prop.GetValue(Class, null));

                }

                //close the stream
                StreamFile.Close();
            }
        }
</code>```

And then I load the same object back like this:

```<code> public void LoadSettings(string ConfigFile, object Class)
        {
            //open the stream to read the file
            using (Stream StreamFile = File.Open(ConfigFile, FileMode.Open))
            {
                //instantiate the binary formatter object
                BinaryFormatter binformat = new BinaryFormatter();

                //loop through all properties in input object
                foreach (PropertyInfo prop in Class.GetType().GetProperties())
                {
                    //if the property is serailizable then deserialize it and read its name and value, and write this in a memory object
                    if (prop.PropertyType.IsSerializable)
                    {
                        object objValue = binformat.Deserialize(StreamFile);
                        prop.SetValue(Class, objValue, null);
                    }
                }

                //close the stream
                StreamFile.Close();
            }

        }
</code>```

What I want to achieve is that if prior to loading, the number of properties in current object changes, then I want to count the number of serialized objects in stream and loop through them, and then map them to those in current object, rather than looping through the properties in current object. Is this possible?

答:
There is no obvious way to count the number of objects in the stream.  Instead you could:

Serialize a count of objects as the first object in the stream, or

Deserialize while StreamFile.Position < StreamFile.Length.

That being said, you have a more basic problem.  From the documentation from Type.GetProperties():

The GetProperties method does not return properties in a particular
  order, such as alphabetical or declaration order. Your code must not
  depend on the order in which properties are returned, because that
  order varies.

Your code depends entirely on this order not changing.

As an alternative, you could store a name/value dictionary of properties like so:

```<code>public void SaveSettings(string SavedFilePath, object Class)
{
    //open the stream to write the new file
    using (Stream StreamFile = File.Open(SavedFilePath, FileMode.CreateNew))
    {
        //instantiate the binary formatter object
        BinaryFormatter binformat = new BinaryFormatter();

        //loop through all properties in input object
        var query = Class.GetType().GetProperties()
            //Make sure the property is read/write without index parameters
            .Where(p => p.GetIndexParameters().Length == 0 && p.CanRead && p.CanWrite && p.GetGetMethod() != null && p.GetSetMethod() != null)
            //if the property is serializable then serialize it and write its name and value in external file
            .Where(p => p.PropertyType.IsSerializable);

        // Create a dictionary of property names and values.
        // Note that if there are duplicate property names because a derived
        // class hides a property via a "public new" declaration, then
        // an exception will get thrown during serialization.
        var dictionary = query.ToDictionary(p => p.Name, p => p.GetValue(Class, null));

        binformat.Serialize(StreamFile, dictionary);
    }
}

public void LoadSettings(string ConfigFile, object Class)
{
    //open the stream to read the file
    using (Stream StreamFile = File.Open(ConfigFile, FileMode.Open))
    {
        //instantiate the binary formatter object
        BinaryFormatter binformat = new BinaryFormatter();

        var dictionary = (IDictionary<string, object>)binformat.Deserialize(StreamFile);

        //loop through all properties in input object
        foreach (var pair in dictionary)
        {
            var property = Class.GetType().GetProperty(pair.Key);
            if (property != null)
                property.SetValue(Class, pair.Value, null);
        }
    }
}
</code>```

This scheme has at least some resilience against properties being added, removed or reordered.

That being said, I don't recommend using BinaryFormatter for long-term persistence of objects.  For reasons why, see What are the deficiencies of the built-in BinaryFormatter based .Net serialization?  Instead, you might consider XML, JSON, or Protocol buffer serialization.

Body:
I save particular object in external file like this:

 public void SaveSettings(string SavedFilePath, object Class)
        {

            //open the stream to write the new file
            using (Stream StreamFile = File.Open(SavedFilePath, FileMode.CreateNew))
            {
                //instantiate the binary formatter object
                BinaryFormatter binformat = new BinaryFormatter();

                //loop through all properties in input object
                foreach (PropertyInfo prop in Class.GetType().GetProperties())
                {
                    //if the property is serailizable then serialize it and write its name and value in external file
                    if (prop.PropertyType.IsSerializable)
                        binformat.Serialize(StreamFile, prop.GetValue(Class, null));

                }

                //close the stream
                StreamFile.Close();
            }
        }

And then I load the same object back like this:

 public void LoadSettings(string ConfigFile, object Class)
        {
            //open the stream to read the file
            using (Stream StreamFile = File.Open(ConfigFile, FileMode.Open))
            {
                //instantiate the binary formatter object
                BinaryFormatter binformat = new BinaryFormatter();

                //loop through all properties in input object
                foreach (PropertyInfo prop in Class.GetType().GetProperties())
                {
                    //if the property is serailizable then deserialize it and read its name and value, and write this in a memory object
                    if (prop.PropertyType.IsSerializable)
                    {
                        object objValue = binformat.Deserialize(StreamFile);
                        prop.SetValue(Class, objValue, null);
                    }
                }

                //close the stream
                StreamFile.Close();
            }

        }

What I want to achieve is that if prior to loading, the number of properties in current object changes, then I want to count the number of serialized objects in stream and loop through them, and then map them to those in current object, rather than looping through the properties in current object. Is this possible?

Body:
There is no obvious way to count the number of objects in the stream.  Instead you could:

Serialize a count of objects as the first object in the stream, or

Deserialize while StreamFile.Position < StreamFile.Length.

That being said, you have a more basic problem.  From the documentation from Type.GetProperties():

The GetProperties method does not return properties in a particular
  order, such as alphabetical or declaration order. Your code must not
  depend on the order in which properties are returned, because that
  order varies.

Your code depends entirely on this order not changing.

As an alternative, you could store a name/value dictionary of properties like so:

public void SaveSettings(string SavedFilePath, object Class)
{
    //open the stream to write the new file
    using (Stream StreamFile = File.Open(SavedFilePath, FileMode.CreateNew))
    {
        //instantiate the binary formatter object
        BinaryFormatter binformat = new BinaryFormatter();

        //loop through all properties in input object
        var query = Class.GetType().GetProperties()
            //Make sure the property is read/write without index parameters
            .Where(p => p.GetIndexParameters().Length == 0 && p.CanRead && p.CanWrite && p.GetGetMethod() != null && p.GetSetMethod() != null)
            //if the property is serializable then serialize it and write its name and value in external file
            .Where(p => p.PropertyType.IsSerializable);

        // Create a dictionary of property names and values.
        // Note that if there are duplicate property names because a derived
        // class hides a property via a "public new" declaration, then
        // an exception will get thrown during serialization.
        var dictionary = query.ToDictionary(p => p.Name, p => p.GetValue(Class, null));

        binformat.Serialize(StreamFile, dictionary);
    }
}

public void LoadSettings(string ConfigFile, object Class)
{
    //open the stream to read the file
    using (Stream StreamFile = File.Open(ConfigFile, FileMode.Open))
    {
        //instantiate the binary formatter object
        BinaryFormatter binformat = new BinaryFormatter();

        var dictionary = (IDictionary<string, object>)binformat.Deserialize(StreamFile);

        //loop through all properties in input object
        foreach (var pair in dictionary)
        {
            var property = Class.GetType().GetProperty(pair.Key);
            if (property != null)
                property.SetValue(Class, pair.Value, null);
        }
    }
}

This scheme has at least some resilience against properties being added, removed or reordered.

That being said, I don't recommend using BinaryFormatter for long-term persistence of objects.  For reasons why, see What are the deficiencies of the built-in BinaryFormatter based .Net serialization?  Instead, you might consider XML, JSON, or Protocol buffer serialization.


问:
In Quickblox, how can we rotate a video (90 degrees, for example) in Android app (QBRTCSurfaceView)?
We are streaming a video chat using Quickblox and we'd like to be able to rotate it (90, 180, 270 degrees).

In the iOS SDK this seems possible, but with Android there doesn't seem to be a setting. How can we get around this and display the video rotated? Thanks!

答:
You can use a View method : void setRotation (float rotation) like below :

```<code>your_vide_view.setRotation(90f);
or
your_vide_view.setRotation(180f);
or
your_vide_view.setRotation(270f);
</code>```

this method work for sdk >15

you should also add this condition :

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

            your_vide_view.setRotation(180f);
        }
</code>```

Body:
You can use a View method : void setRotation (float rotation) like below :

your_vide_view.setRotation(90f);
or
your_vide_view.setRotation(180f);
or
your_vide_view.setRotation(270f);

this method work for sdk >15

you should also add this condition :

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

            your_vide_view.setRotation(180f);
        }


问:
Use gulp task to change urls in css file
Hi I am writing a gulp task to change the original urls in my fonts.css file.
The urls need to change to point to another path once fractal (styleguide) is built.

The current urls in the file look like this url('/assets/fonts/font.ttf');

I want my gulp task to look in the file fonts.css

and replace all the url to look like url(./font.ttf);

here is the task

```<code>var config = require('../config');
if (!config.tasks.js) return;

var gulp = require('gulp');
var replace = require('gulp-replace');

var fontURL = function () {
    return gulp.src('../site/fractal/components/preview/fonts.css')
    .pipe(replace('url("/assets/fonts/', 'url("./'))
}

gulp.task('font:url', ['fractal'], fontURL);
module.exports = fontURL
</code>```

I am incorporating this task along with several others in the fractal:build task so that when someone runs that command to power up the styleguide this is taken care of dynamically instead of one having to change many paths/urls. However this task is not working. Is there another way to accomplish what I want?

A snippit of the fonts.css file and an example of all the css urls I want to change (there are many more)

```<code>@font-face {
  font-family: 'Overpass';
  font-style: normal;
  font-weight: 400;
  src: local('Overpass Regular'), local('Overpass-Regular'), url('/assets/fonts/overpass-bold-webfont.eot');
  src: local('Overpass Regular'), local('Overpass-Regular'), url('/assets/fonts/overpass-regular-webfont.eot?#iefix') format('embedded-opentype'),
       local('Overpass Regular'), local('Overpass-Regular'), url('/assets/fonts/overpass-regular-webfont.woff2') format('woff2'),
       local('Overpass Regular'), local('Overpass-Regular'), url('/assets/fonts/overpass-regular-webfont.woff') format('woff'),
       local('Overpass Regular'), local('Overpass-Regular'), url('/assets/fonts/overpass-regular-webfont.ttf') format('truetype'),
       local('Overpass Regular'), local('Overpass-Regular'), url('/assets/fonts/overpass-regular-webfont.svg#overpass') format('svg');
}
</code>```

答:
Quick question: do you save the modified files at some point?  Your fontURL() has no gulp.dest.

Also, I would simplify this

```<code>.pipe(replace('url("/assets/fonts/', 'url("./'))
</code>```

Change that to :

```<code>.pipe(replace( '/assets/fonts/', './') )
</code>```

Body:
Hi I am writing a gulp task to change the original urls in my fonts.css file.
The urls need to change to point to another path once fractal (styleguide) is built.

The current urls in the file look like this url('/assets/fonts/font.ttf');

I want my gulp task to look in the file fonts.css

and replace all the url to look like url(./font.ttf);

here is the task

var config = require('../config');
if (!config.tasks.js) return;

var gulp = require('gulp');
var replace = require('gulp-replace');

var fontURL = function () {
    return gulp.src('../site/fractal/components/preview/fonts.css')
    .pipe(replace('url("/assets/fonts/', 'url("./'))
}

gulp.task('font:url', ['fractal'], fontURL);
module.exports = fontURL

I am incorporating this task along with several others in the fractal:build task so that when someone runs that command to power up the styleguide this is taken care of dynamically instead of one having to change many paths/urls. However this task is not working. Is there another way to accomplish what I want?

A snippit of the fonts.css file and an example of all the css urls I want to change (there are many more)

@font-face {
  font-family: 'Overpass';
  font-style: normal;
  font-weight: 400;
  src: local('Overpass Regular'), local('Overpass-Regular'), url('/assets/fonts/overpass-bold-webfont.eot');
  src: local('Overpass Regular'), local('Overpass-Regular'), url('/assets/fonts/overpass-regular-webfont.eot?#iefix') format('embedded-opentype'),
       local('Overpass Regular'), local('Overpass-Regular'), url('/assets/fonts/overpass-regular-webfont.woff2') format('woff2'),
       local('Overpass Regular'), local('Overpass-Regular'), url('/assets/fonts/overpass-regular-webfont.woff') format('woff'),
       local('Overpass Regular'), local('Overpass-Regular'), url('/assets/fonts/overpass-regular-webfont.ttf') format('truetype'),
       local('Overpass Regular'), local('Overpass-Regular'), url('/assets/fonts/overpass-regular-webfont.svg#overpass') format('svg');
}

Body:
Quick question: do you save the modified files at some point?  Your fontURL() has no gulp.dest.

Also, I would simplify this

.pipe(replace('url("/assets/fonts/', 'url("./'))

Change that to :

.pipe(replace( '/assets/fonts/', './') )


问:
Curly Braces Inside a _.find Lodash Statement in an AngularJS app
I inherited a monster mess of an AngularJS project at my new job. I've been trying to resolve a bug recently that has the following Lodash statement:

```<code> var group = _.find(groupList, {id: id});
</code>```

From the documentation available on https://lodash.com/docs/3.10.1#find, which is the closest I can find to version 3.7.0, the _.find function iterates over a collection and returns the first object that the statement is "truthy" for. The second item inside the expression would represent a function to be executed.

However, I am confused about what the {id: id} is doing in this instance. Is this an Angular expression? What is it doing here exactly? Any help would be much appreciated.

答:
Maybe try reading all the documentation in the link you posted? Specifically look at the Examples:

```<code>var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];

_.result(_.find(users, function(chr) {
  return chr.age < 40;
}), 'user');
// => 'barney'

// using the `_.matches` callback shorthand
_.result(_.find(users, { 'age': 1, 'active': true }), 'user');
// => 'pebbles'

// using the `_.matchesProperty` callback shorthand
_.result(_.find(users, 'active', false), 'user');
// => 'fred'

// using the `_.property` callback shorthand
_.result(_.find(users, 'active'), 'user');
// => 'barney'
</code>```

I believe the 2nd example that says

// using the _.matches callback shorthand

answers your question.

Body:
I inherited a monster mess of an AngularJS project at my new job. I've been trying to resolve a bug recently that has the following Lodash statement:

 var group = _.find(groupList, {id: id});

From the documentation available on https://lodash.com/docs/3.10.1#find, which is the closest I can find to version 3.7.0, the _.find function iterates over a collection and returns the first object that the statement is "truthy" for. The second item inside the expression would represent a function to be executed.

However, I am confused about what the {id: id} is doing in this instance. Is this an Angular expression? What is it doing here exactly? Any help would be much appreciated.

Body:
Maybe try reading all the documentation in the link you posted? Specifically look at the Examples:

var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];

_.result(_.find(users, function(chr) {
  return chr.age < 40;
}), 'user');
// => 'barney'

// using the `_.matches` callback shorthand
_.result(_.find(users, { 'age': 1, 'active': true }), 'user');
// => 'pebbles'

// using the `_.matchesProperty` callback shorthand
_.result(_.find(users, 'active', false), 'user');
// => 'fred'

// using the `_.property` callback shorthand
_.result(_.find(users, 'active'), 'user');
// => 'barney'

I believe the 2nd example that says

// using the _.matches callback shorthand

answers your question.


问:
FB is not defined, yet Javascript code runs smoothly
I've only started Javascript a few days ago, so this question might seem basic.
I've written some Javascript code to interact with the Facebook API.

The goal is to display all the pages managed by a user when he logs in via a Facebook login button.

The code seems to work as it does what it's supposed to do.

However, the console gives me the error "FB is not defined".

I've read all the other questions about this error and it seems to be linked to the asynchronous loading of the SDK, but i can't seem to figure this out.

How come i still get this error?

******EDIT 07/07/2017*******
Google Chrome's console gives me the "FB is not defined error" at the FB.getLoginStatus line of this portion of code:

```<code>function checkLoginStatus() {
    FB.getLoginStatus(function (response) {
        if (response.status === 'connected') {
            getPagesList();
        } else {
            document.getElementById('pageslist').style.display = 'none'; //Hides the div when people are not connected
            document.getElementById('pagestatistics').style.display = 'none'; //Hides the div when people are not connected
        }
    });
}
</code>```

It also points to the following part, which seems to be the issue since, when i remove it from the code, the error disappears:

```<code>//Here below, _5h0o is the class of the logout button
//This checks the login status AFTER the user clicks on logout thanks to setTimeout
    document.getElementsByClassName('_5h0o').onclick = setTimeout(function() {
        checkLoginStatus();
    }, 100);
</code>```

Here is the full code:

//Initialize Facebook SDK + Check Login Status

//Facebook Login Button

//Display the pages (in the form of clickable spans) for which the user has reading rights

```

答:
Try encapsulating your getPagesList inside document ready.</p>

```<code>$(document).ready(function(){
     getPagesList(){
      ...
     }
  });
</code>```

Body:
I've only started Javascript a few days ago, so this question might seem basic.
I've written some Javascript code to interact with the Facebook API.

The goal is to display all the pages managed by a user when he logs in via a Facebook login button.

The code seems to work as it does what it's supposed to do.

However, the console gives me the error "FB is not defined".

I've read all the other questions about this error and it seems to be linked to the asynchronous loading of the SDK, but i can't seem to figure this out.

How come i still get this error?

******EDIT 07/07/2017*******
Google Chrome's console gives me the "FB is not defined error" at the FB.getLoginStatus line of this portion of code:

function checkLoginStatus() {
    FB.getLoginStatus(function (response) {
        if (response.status === 'connected') {
            getPagesList();
        } else {
            document.getElementById('pageslist').style.display = 'none'; //Hides the div when people are not connected
            document.getElementById('pagestatistics').style.display = 'none'; //Hides the div when people are not connected
        }
    });
}

It also points to the following part, which seems to be the issue since, when i remove it from the code, the error disappears:

//Here below, _5h0o is the class of the logout button
//This checks the login status AFTER the user clicks on logout thanks to setTimeout
    document.getElementsByClassName('_5h0o').onclick = setTimeout(function() {
        checkLoginStatus();
    }, 100);

Here is the full code:

//Initialize Facebook SDK + Check Login Status

//Facebook Login Button

//Display the pages (in the form of clickable spans) for which the user has reading rights

Body:
Try encapsulating your getPagesList inside document ready.

$(document).ready(function(){
     getPagesList(){
      ...
     }
  });


问:
Cancel button press if user moves finger off button
Here is my very standard button onTouchListener:

```<code>b.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN) {
            b.setPressed(true);
        }
        if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP) {
            b.setPressed(false);
            // Do the button action stuff here
        }
        return true;
    }
});
</code>```

When the user presses down on the button I set the button to "pressed". When the user lifts the finger I set the button to "not pressed" and then do the stuff the button is supposed to do.

This is all great except for the case where the user presses the button and then, while continuing to keep the finger down, moves the finger outside of the button area. When the finger is lifted the ACTION_UP stuff runs anyway. I would like for this behavior to act as a "cancel" of the button press. So, as soon as the pressed finger moves outside the button area I'd like to b.setPressed(false); and then NOT do the button action stuff when the finger is raised.

I've tried using MotionEvent.ACTION_CANCEL and MotionEvent.ACTION_OUTSIDE (as suggested by How to detect when finger slides off the ImageButton?) but I must be missing something because they're not working.

From Detect when a user moves off of a button in Android it would appear that this can be done with event.getX() and event.getY(). If getX() is negative you're off the left and if getY() is negative you're off the top, but to figure out if you're off the right or bottom I'll have to figure out the size of the button and then... there has to be a simpler way. Is there?

答:
Since no one posted any code, here is one. A Boolean is used to indicate when the respective actions should be performed.

The MotionEvent.ACTION_MOVE event is handled to check if the finger is moved out of the bounds. If yes, b.setPressed(false); is called and the boolean is used to indicate that MotionEvent.ACTION_UP shouldn't be fired the next time, ie to cancel the button click.

And in MotionEvent.ACTION_UP, call b.setPressed(false); only if our boolean doesn't indicate a skip (as mentioned above). And if it does, invert the boolean so that button action stuff would execute the next time.

```<code>private Boolean notNow = false;
private Rect rect;    // Variable rect to hold the bounds of the view

b.setOnTouchListener(new OnTouchListener(){
    @Override
    public boolean onTouch(View v, MotionEvent event){
        if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN){
            b.setPressed(true);
            rect = new Rect(v.Left, v.Top, v.Right, v.Bottom);
        }
        if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP){
            if (!notNow){
                b.setPressed(false);
            }
            else //button press canceled
                notNow = false;
        }
        if((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_MOVE){
            if(!notNow)
                if (!rect.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY())){
                    // finger moved out of bounds
                    b.setPressed(false);
                    notNow = true; //cancel button press the next time
                }
        }

        return true;
});
</code>```

Body:
Here is my very standard button onTouchListener:

b.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN) {
            b.setPressed(true);
        }
        if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP) {
            b.setPressed(false);
            // Do the button action stuff here
        }
        return true;
    }
});

When the user presses down on the button I set the button to "pressed". When the user lifts the finger I set the button to "not pressed" and then do the stuff the button is supposed to do.

This is all great except for the case where the user presses the button and then, while continuing to keep the finger down, moves the finger outside of the button area. When the finger is lifted the ACTION_UP stuff runs anyway. I would like for this behavior to act as a "cancel" of the button press. So, as soon as the pressed finger moves outside the button area I'd like to b.setPressed(false); and then NOT do the button action stuff when the finger is raised.

I've tried using MotionEvent.ACTION_CANCEL and MotionEvent.ACTION_OUTSIDE (as suggested by How to detect when finger slides off the ImageButton?) but I must be missing something because they're not working.

From Detect when a user moves off of a button in Android it would appear that this can be done with event.getX() and event.getY(). If getX() is negative you're off the left and if getY() is negative you're off the top, but to figure out if you're off the right or bottom I'll have to figure out the size of the button and then... there has to be a simpler way. Is there?

Body:
Since no one posted any code, here is one. A Boolean is used to indicate when the respective actions should be performed.

The MotionEvent.ACTION_MOVE event is handled to check if the finger is moved out of the bounds. If yes, b.setPressed(false); is called and the boolean is used to indicate that MotionEvent.ACTION_UP shouldn't be fired the next time, ie to cancel the button click.

And in MotionEvent.ACTION_UP, call b.setPressed(false); only if our boolean doesn't indicate a skip (as mentioned above). And if it does, invert the boolean so that button action stuff would execute the next time.

private Boolean notNow = false;
private Rect rect;    // Variable rect to hold the bounds of the view

b.setOnTouchListener(new OnTouchListener(){
    @Override
    public boolean onTouch(View v, MotionEvent event){
        if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN){
            b.setPressed(true);
            rect = new Rect(v.Left, v.Top, v.Right, v.Bottom);
        }
        if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP){
            if (!notNow){
                b.setPressed(false);
            }
            else //button press canceled
                notNow = false;
        }
        if((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_MOVE){
            if(!notNow)
                if (!rect.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY())){
                    // finger moved out of bounds
                    b.setPressed(false);
                    notNow = true; //cancel button press the next time
                }
        }

        return true;
});


问:
logrotate - compression files modified x number of days
Is there a way to get logrotate to only compress files modified X number of days ago (e.g. mtime +2)</p>

答:
Well you can use delaycompress to wait one more cycle. Basically if you rotate daily then it will keep yesterdays logs uncompressed.

Besides that you could try not using logrotate to compress the files and write a bash script to run like once a day and compress all files older than a certain date.

Here is a tutorial to bash that I personally like: http://www.linuxconfig.org/Bash_scripting_Tutorial


问:
Generate signed apk without typing key
First of all here goes my signinConfigs:

```<code>signingConfigs {
        development {
            storeFile file("mykey.jks") //Path to the keystore file
            keyAlias "mykey"
            storePassword "mykeydev"
            keyPassword "mykeydev"
        }
        production {
            storeFile file("mykey.jks") //Path to the keystore file
            keyAlias "mykey"
            storePassword "mykeyprod"
            keyPassword "mykeyprod"
        }
}
</code>```

And now my flavors:

```<code>productFlavors {
    development{
        applicationId "br.com.myapp.dev"
        signingConfig signingConfigs.development
        resValue "string", "app_name", "DEV"
    }

    production {
        applicationId "br.com.myapp"
        signingConfig signingConfigs.production
        resValue "string", "app_name", "PROD"
    }
}
</code>```

I have under by buildTypes this:

```<code>buildTypes {
    release {
        minifyEnabled false
        productFlavors.production.signingConfig signingConfigs.production
        productFlavors.development.signingConfig signingConfigs.development
    }
}
</code>```

And here goes my question, Why am I asked for keyPassword and storePassword every time i want to generate a new signed apk file, if all keys and stuff are inside my .gradle file?

答:
If you have provided keystore path and credentials in gradle. Then for generating signed apks follow this steps.

Go to Build Variants

Select build variants as release

Click the play/run button

Apk will be published in Project/build/outputs/apk folder

Title: Generate signed apk without typing key

Body:
First of all here goes my signinConfigs:

signingConfigs {
        development {
            storeFile file("mykey.jks") //Path to the keystore file
            keyAlias "mykey"
            storePassword "mykeydev"
            keyPassword "mykeydev"
        }
        production {
            storeFile file("mykey.jks") //Path to the keystore file
            keyAlias "mykey"
            storePassword "mykeyprod"
            keyPassword "mykeyprod"
        }
}

And now my flavors:

productFlavors {
    development{
        applicationId "br.com.myapp.dev"
        signingConfig signingConfigs.development
        resValue "string", "app_name", "DEV"
    }

    production {
        applicationId "br.com.myapp"
        signingConfig signingConfigs.production
        resValue "string", "app_name", "PROD"
    }
}

I have under by buildTypes this:

buildTypes {
    release {
        minifyEnabled false
        productFlavors.production.signingConfig signingConfigs.production
        productFlavors.development.signingConfig signingConfigs.development
    }
}

And here goes my question, Why am I asked for keyPassword and storePassword every time i want to generate a new signed apk file, if all keys and stuff are inside my .gradle file?


问:
Operate a task on all word files in a folder and all sub folders VBA
I am fairly new to this site and this is my first post.  Here we go:
I am writing a fairly simple code on VBA that replace a certain chain of character by nothing.  I have that part figured out, however I would like to operate that code on all the files in a big folder containing sub folder on and on.... I saw a similar question asked on here before, but it does not work for me since i'm trying to put in a "If" in the code to verify the file is a word file and if it is then it calls the operation ( secondSubRoutine ) who does the required task on the file. If someone could tell me why it's not capable to find the word files, it would be really helpful!

Aurelion.

```<code>Sub domino()

Dim FileSystem As Object
Dim HostFolder As String

HostFolder = "C:\CLIENTS"

Set FileSystem = CreateObject("Scripting.FileSystemObject")
DoFolder FileSystem.GetFolder(HostFolder)
End Sub
Sub DoFolder(Folder)
    Dim SubFolder
    For Each SubFolder In Folder.SubFolders
        DoFolder SubFolder
    Next
    Dim File
    For Each File In Folder.Files

        If File.Name = "*.docx" Then

             Documents.Open FileName:=File

             Call secondSubRoutine

             ActiveDocument.Save
             ActiveDocument.Close

        ElseIf File.Name = "*.doc" Then

            Documents.Open FileName:=path & File

            Call secondSubRoutine

            ActiveDocument.Save
            ActiveDocument.Close

        End If

    Next

End Sub
</code>```

答:
Try this:</p>

```<code>For Each File In Folder.Files
    If Right(File.Name, 5) = ".docx" Or Right(File.Name, 4) = ".doc" Then

         Documents.Open FileName:=File.Path

         Call secondSubRoutine

         With ActiveDocument
            .Save
            .Close
        End With
    End If
Next
</code>```

Body:
I am fairly new to this site and this is my first post.  Here we go:
I am writing a fairly simple code on VBA that replace a certain chain of character by nothing.  I have that part figured out, however I would like to operate that code on all the files in a big folder containing sub folder on and on.... I saw a similar question asked on here before, but it does not work for me since i'm trying to put in a "If" in the code to verify the file is a word file and if it is then it calls the operation ( secondSubRoutine ) who does the required task on the file. If someone could tell me why it's not capable to find the word files, it would be really helpful!

Aurelion.

Sub domino()

Dim FileSystem As Object
Dim HostFolder As String

HostFolder = "C:\CLIENTS"

Set FileSystem = CreateObject("Scripting.FileSystemObject")
DoFolder FileSystem.GetFolder(HostFolder)
End Sub
Sub DoFolder(Folder)
    Dim SubFolder
    For Each SubFolder In Folder.SubFolders
        DoFolder SubFolder
    Next
    Dim File
    For Each File In Folder.Files

        If File.Name = "*.docx" Then

             Documents.Open FileName:=File

             Call secondSubRoutine

             ActiveDocument.Save
             ActiveDocument.Close

        ElseIf File.Name = "*.doc" Then

            Documents.Open FileName:=path & File

            Call secondSubRoutine

            ActiveDocument.Save
            ActiveDocument.Close

        End If

    Next

End Sub

Body:
Try this:

For Each File In Folder.Files
    If Right(File.Name, 5) = ".docx" Or Right(File.Name, 4) = ".doc" Then

         Documents.Open FileName:=File.Path

         Call secondSubRoutine

         With ActiveDocument
            .Save
            .Close
        End With
    End If
Next


问:
Using GetListItems with Ajax call from SharePoint 2010
I'm trying to write an ajax call to retrieve list items from SharePoint using Lists.asmx

I keep getting a 302 error even though I'm folling the formatting  correctly. Am I missing something?

Code

```<code>function makeSoapCall(listName){
    var soapEnv =
    "<?xml version='1.0' encoding='utf-8'?> " +
    "<soap12:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap12='http://www.w3.org/2003/05/soap-envelope'> " +
        "<soap12:Body> " +
            "<GetList xmlns='http://schemas.microsoft.com/sharepoint/soap/'> " +
                "<listName>Webpostings Approvers</listName> " +
            "</GetList> " +
        "</soap12:Body> " +
    "</soap12:Envelope>";

        $.ajax({
            url: "http://webpub.ex.com/_vti_bin/Lists.asmx",
            type: "POST",
            dataType: "xml",
            data: soapEnv,
            contentType: "application/soap+xml; charset=utf-8"
        });
    }
</code>```

Response

```<code>http://webpub.ex.com/_layouts/error.aspx?ErrorText=Request format is unrecognized.
</code>```

答:
Since you need list items . You have to use Getlistitems instead Getlist.</p>

```<code> function getSharepointListData (myList) {

       var listName = myList;

    var soapEnv =
        "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> \
            <soapenv:Body> \
                 <GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \
                    <listName>"+listName+"</listName> \
                    <viewFields> \
                        <ViewFields> \
                           <FieldRef Name='Author' /> \
                       </ViewFields> \
                    </viewFields> \
                </GetListItems> \
            </soapenv:Body> \
        </soapenv:Envelope>";

    $.ajax({
        url: "http:URL/_vti_bin/lists.asmx",
        type: "POST",
        dataType: "xml",
        data: soapEnv,
        complete: processResult,
        contentType: "text/xml; charset=\"utf-8\""
    });
</code>```

Body:
I'm trying to write an ajax call to retrieve list items from SharePoint using Lists.asmx

I keep getting a 302 error even though I'm folling the formatting  correctly. Am I missing something?

Code

function makeSoapCall(listName){
    var soapEnv =
    "<?xml version='1.0' encoding='utf-8'?> " +
    "<soap12:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap12='http://www.w3.org/2003/05/soap-envelope'> " +
        "<soap12:Body> " +
            "<GetList xmlns='http://schemas.microsoft.com/sharepoint/soap/'> " +
                "<listName>Webpostings Approvers</listName> " +
            "</GetList> " +
        "</soap12:Body> " +
    "</soap12:Envelope>";

        $.ajax({
            url: "http://webpub.ex.com/_vti_bin/Lists.asmx",
            type: "POST",
            dataType: "xml",
            data: soapEnv,
            contentType: "application/soap+xml; charset=utf-8"
        });
    }

Response

http://webpub.ex.com/_layouts/error.aspx?ErrorText=Request format is unrecognized.

Body:
Since you need list items . You have to use Getlistitems instead Getlist.

 function getSharepointListData (myList) {

       var listName = myList;

    var soapEnv =
        "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> \
            <soapenv:Body> \
                 <GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \
                    <listName>"+listName+"</listName> \
                    <viewFields> \
                        <ViewFields> \
                           <FieldRef Name='Author' /> \
                       </ViewFields> \
                    </viewFields> \
                </GetListItems> \
            </soapenv:Body> \
        </soapenv:Envelope>";

    $.ajax({
        url: "http:URL/_vti_bin/lists.asmx",
        type: "POST",
        dataType: "xml",
        data: soapEnv,
        complete: processResult,
        contentType: "text/xml; charset=\"utf-8\""
    });


问:
What is a Win32 Exception the system cannot find the file specified
I have a problem with Process.Start(), i want it to open specified file when I double click on tree node.

This is my code where it should open file

```<code> String path = "C:\\Users\\........\\something";

        private void treePrica_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            try {

                String TreeNodeName = treePrica.SelectedNode.ToString().Replace("TreeNode: ", String.Empty);
                MessageBox.Show(this.path + "\\" + TreeNodeName);

                Process.Start(this.path + "\\" + TreeNodeName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
</code>```

When i double click on any of the nodes containing .txt file it throws exception like this

答: just use string path = @"c:/something"; and make sure you add the extension to the total path!</p>

Body:
I have a problem with Process.Start(), i want it to open specified file when I double click on tree node.

This is my code where it should open file

 String path = "C:\\Users\\........\\something";

        private void treePrica_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            try {

                String TreeNodeName = treePrica.SelectedNode.ToString().Replace("TreeNode: ", String.Empty);
                MessageBox.Show(this.path + "\\" + TreeNodeName);

                Process.Start(this.path + "\\" + TreeNodeName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

When i double click on any of the nodes containing .txt file it throws exception like this


问:
Running ChromeDriver with Python selenium on Heroku
So I have a Flask server on Heroku which has been working fine as expected for some time.Now, as per new requirements, I need to add functionality to the Flask server to fetch a page from an external website.Because of reasons best known to me, I am using Selenium along with Chrome web driver to do this.Locally I was able to set this up and it works fine but I am quite unsure as to how to set it up on the Heroku server. I read a bit about buildpacks and found this buildpack for ChromeDriver :

```<code>https://elements.heroku.com/buildpacks/jimmynguyc/heroku-buildpack-chromedriver
</code>```

However, I am not sure how to proceed further.How do I install chromium browser itself and what else is needed to tie it all up ?

答:
I had the same issue and the following steps worked fine for me:

I added the following buildpacks on heroku:
https://github.com/heroku/heroku-buildpack-xvfb-google-chrome
(to install chrome, since chromedriver requires it) and
https://github.com/heroku/heroku-buildpack-chromedriver.

I created an environment variable GOOGLE_CHROME_BIN, with the path of chrome on heroku: /app/.apt/usr/bin/google-chrome and an environment variable called CHROMEDRIVER_PATH with the path of chromedriver on heroku: /app/.chromedriver/bin/chromedriver.

In my python file, I configured chromedriver:

```<code>chrome_options = Options()
chrome_options.binary_location = GOOGLE_CHROME_BIN
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--no-sandbox')
driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH, chrome_options=chrome_options)
</code>```

(First, I tried to configure chromedriver with no arguments, but I faced the following error: "Chrome failed to start: crashed". --disable-gpu and --no-sandbox solved the problem for me).

Body:
So I have a Flask server on Heroku which has been working fine as expected for some time.Now, as per new requirements, I need to add functionality to the Flask server to fetch a page from an external website.Because of reasons best known to me, I am using Selenium along with Chrome web driver to do this.Locally I was able to set this up and it works fine but I am quite unsure as to how to set it up on the Heroku server. I read a bit about buildpacks and found this buildpack for ChromeDriver :

https://elements.heroku.com/buildpacks/jimmynguyc/heroku-buildpack-chromedriver

However, I am not sure how to proceed further.How do I install chromium browser itself and what else is needed to tie it all up ?

Body:
I had the same issue and the following steps worked fine for me:

I added the following buildpacks on heroku:
https://github.com/heroku/heroku-buildpack-xvfb-google-chrome
(to install chrome, since chromedriver requires it) and
https://github.com/heroku/heroku-buildpack-chromedriver.

I created an environment variable GOOGLE_CHROME_BIN, with the path of chrome on heroku: /app/.apt/usr/bin/google-chrome and an environment variable called CHROMEDRIVER_PATH with the path of chromedriver on heroku: /app/.chromedriver/bin/chromedriver.

In my python file, I configured chromedriver:

chrome_options = Options()
chrome_options.binary_location = GOOGLE_CHROME_BIN
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--no-sandbox')
driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH, chrome_options=chrome_options)

(First, I tried to configure chromedriver with no arguments, but I faced the following error: "Chrome failed to start: crashed". --disable-gpu and --no-sandbox solved the problem for me).


问:
How to list all datasets in h5py file?
I have a h5py file storing numpy arrays, but I got Object doesn't exist error when trying to open it with the dataset name I remember, so is there a way I can list what datasets the file has?

```<code>   with h5py.File('result.h5','r') as hf:
        #How can I list all dataset I have saved in hf?
</code>```

答:
You have to use the keys method. This will give you a List of unicode strings of your dataset and group names.
For example:

```<code>Datasetnames=hf.keys()
</code>```

Another gui based method would be to use HDFView.
https://support.hdfgroup.org/products/java/release/download.html

ContentLicense: CC BY-SA 4.0

Title: How to list all datasets in h5py file?

Body:
I have a h5py file storing numpy arrays, but I got Object doesn't exist error when trying to open it with the dataset name I remember, so is there a way I can list what datasets the file has?

   with h5py.File('result.h5','r') as hf:
        #How can I list all dataset I have saved in hf?

Body:
You have to use the keys method. This will give you a List of unicode strings of your dataset and group names.
For example:

Datasetnames=hf.keys()

Another gui based method would be to use HDFView.
https://support.hdfgroup.org/products/java/release/download.html


问:
How to fetch data about current user in ASP .NET MVC?
So, I added a new Parameter to my ApplicationUser class, which is called SocialName. I would like to display it when user is logged in, at the top right corner. There, we have this piece of code:

```<code>@Html.ActionLink("Hello, " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
</code>```

Now the thing is, I would like to display parameter other than Current user's username. I found passing the model to the Partial View problematic because I need to do it for every single action, otherwise I will have Null Reference. Do you have any ideas how to do this?

答:
You can easily display info about user in partial view by Html.Action() method without passing info to every action. For example:

Your page/layout/...:

```<code><ul class="nav navbar-nav navbar-right">
    @Html.Action("HeaderUserInfo", "Common")
</ul>
</code>```

CommonController.cs:

```<code>public ActionResult HeaderUserInfo()
{
    var user = _workContext.CurrentUser; //get info about user
    var model = new HeaderUserInfoModel
    {
        Username = user.Username,
        UserId = user.Id
    };
    return PartialView(model);
}
</code>```

and partial view HeaderUserInfo.cshtml:

```<code>@model Models.Common.HeaderUserInfoModel

<span><i class="icon fa fa-user"></i> @Model.Username</span>
</code>```

Body:
So, I added a new Parameter to my ApplicationUser class, which is called SocialName. I would like to display it when user is logged in, at the top right corner. There, we have this piece of code:

@Html.ActionLink("Hello, " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })

Now the thing is, I would like to display parameter other than Current user's username. I found passing the model to the Partial View problematic because I need to do it for every single action, otherwise I will have Null Reference. Do you have any ideas how to do this?

Body:
You can easily display info about user in partial view by Html.Action() method without passing info to every action. For example:

Your page/layout/...:

<ul class="nav navbar-nav navbar-right">
    @Html.Action("HeaderUserInfo", "Common")
</ul>

CommonController.cs:

public ActionResult HeaderUserInfo()
{
    var user = _workContext.CurrentUser; //get info about user
    var model = new HeaderUserInfoModel
    {
        Username = user.Username,
        UserId = user.Id
    };
    return PartialView(model);
}

and partial view HeaderUserInfo.cshtml:

@model Models.Common.HeaderUserInfoModel

<span><i class="icon fa fa-user"></i> @Model.Username</span>


问:
Clickable dots on Bokeh Plots
I'm working on a dashboard where the user clicks on one of many dots on a regular scatter plot to get more information about that dot. Each dot represents a group of data, and when clicked on, the user should be able to see a table in which the related group of data is listed.

The table will be listed right next to the plot, and the rows will change every time a new dot (or multiple dots) is selected.

I'll then need to add filters to this table, so it needs to be interactive too. The plot does not change during filtering, only the related data in the table will.

I've seen the following example, which achieves the exact opposite that I want to achieve:

```<code>from bokeh.plotting import Figure, output_file, show
from bokeh.models import CustomJS
from bokeh.models.sources import ColumnDataSource
from bokeh.layouts import column, row
from bokeh.models.widgets import DataTable, TableColumn, Toggle

from random import randint
import pandas as pd

output_file("data_table_subset_example.html")

data = dict(
        x=[randint(0, 100) for i in range(10)],
        y=[randint(0, 100) for i in range(10)],
        z=['some other data'] * 10
    )
df = pd.DataFrame(data)
#filtering dataframes with pandas keeps the index numbers consistent
filtered_df = df[df.x < 80]

#Creating CDSs from these dataframes gives you a column with indexes
source1 = ColumnDataSource(df) # FIGURE
source2 = ColumnDataSource(filtered_df) # TABLE - FILTERED

fig1 = Figure(plot_width=200, plot_height=200)
fig1.circle(x='x', y='y', source=source1)

columns = [
        TableColumn(field="x", title="X"),
        TableColumn(field="z", title="Text"),
    ]
data_table = DataTable(source=source2, columns=columns, width=400, height=280)

button = Toggle(label="Select")
button.callback = CustomJS(args=dict(source1=source1, source2=source2), code="""
        var inds_in_source2 = source2.get('selected')['1d'].indices;
        var d = source2.get('data');
        var inds = []

        if (inds_in_source2.length == 0) { return; }

        for (i = 0; i < inds_in_source2.length; i++) {
            inds.push(d['index'][i])
        }

        source1.get('selected')['1d'].indices = inds
        source1.trigger('change');
    """)

show(column(fig1, data_table, button))
</code>```

I tried replacing source1 and source2 inside the button callback in an attempt to reverse the filtering (i.e. choose a point on the figure and filter the data table). But the data table is not filtered at all, instead the row that corresponds to the data point is simply selected. Any idea how to filter out the rest of the rows that are not selected on the plot?

答:
I found the answer in another question: Bokeh DataTable won't update after trigger('change') without clicking on header

Apparently the data table change needs to be triggered too.

Title: Clickable dots on Bokeh Plots

Body:
I'm working on a dashboard where the user clicks on one of many dots on a regular scatter plot to get more information about that dot. Each dot represents a group of data, and when clicked on, the user should be able to see a table in which the related group of data is listed.

The table will be listed right next to the plot, and the rows will change every time a new dot (or multiple dots) is selected.

I'll then need to add filters to this table, so it needs to be interactive too. The plot does not change during filtering, only the related data in the table will.

I've seen the following example, which achieves the exact opposite that I want to achieve:

from bokeh.plotting import Figure, output_file, show
from bokeh.models import CustomJS
from bokeh.models.sources import ColumnDataSource
from bokeh.layouts import column, row
from bokeh.models.widgets import DataTable, TableColumn, Toggle

from random import randint
import pandas as pd

output_file("data_table_subset_example.html")

data = dict(
        x=[randint(0, 100) for i in range(10)],
        y=[randint(0, 100) for i in range(10)],
        z=['some other data'] * 10
    )
df = pd.DataFrame(data)
#filtering dataframes with pandas keeps the index numbers consistent
filtered_df = df[df.x < 80]

#Creating CDSs from these dataframes gives you a column with indexes
source1 = ColumnDataSource(df) # FIGURE
source2 = ColumnDataSource(filtered_df) # TABLE - FILTERED

fig1 = Figure(plot_width=200, plot_height=200)
fig1.circle(x='x', y='y', source=source1)

columns = [
        TableColumn(field="x", title="X"),
        TableColumn(field="z", title="Text"),
    ]
data_table = DataTable(source=source2, columns=columns, width=400, height=280)

button = Toggle(label="Select")
button.callback = CustomJS(args=dict(source1=source1, source2=source2), code="""
        var inds_in_source2 = source2.get('selected')['1d'].indices;
        var d = source2.get('data');
        var inds = []

        if (inds_in_source2.length == 0) { return; }

        for (i = 0; i < inds_in_source2.length; i++) {
            inds.push(d['index'][i])
        }

        source1.get('selected')['1d'].indices = inds
        source1.trigger('change');
    """)

show(column(fig1, data_table, button))

I tried replacing source1 and source2 inside the button callback in an attempt to reverse the filtering (i.e. choose a point on the figure and filter the data table). But the data table is not filtered at all, instead the row that corresponds to the data point is simply selected. Any idea how to filter out the rest of the rows that are not selected on the plot?


问:
Custom dropdown default selected item
I'm using the following styled dropdown menu:

https://codepen.io/wallaceerick/pen/ctsCz

```<code><select id="mounth">
    <option value="hide">-- Month --</option>
    <option value="january" rel="icon-temperature">January</option>
    <option value="february">February</option>
    <option value="march">March</option>
    <option value="april">April</option>
    <option value="may">May</option>
    <option value="june">June</option>
    <option value="july">July</option>
    <option value="august">August</option>
    <option value="september">September</option>
    <option value="october">October</option>
    <option value="november">November</option>
    <option value="december">December</option>
</select>
</code>```

I am using it to let users select their birth date month. So the first time they signup, they select the month and it's saved. When user wants to edit their profile, I need a way to select the previously selected month for them. Ideas on how to pre-select one of the months are appreciated!

答:
Try this...

```<code>$("#mounth option[value='hide']").each(function() {
$(this).remove();
}
</code>```

Note, month is spelled wrong. And you might want to actually store the values as the numeric month, January is 1, etc.

Title: Custom dropdown default selected item

Body:
I'm using the following styled dropdown menu:

https://codepen.io/wallaceerick/pen/ctsCz

<select id="mounth">
    <option value="hide">-- Month --</option>
    <option value="january" rel="icon-temperature">January</option>
    <option value="february">February</option>
    <option value="march">March</option>
    <option value="april">April</option>
    <option value="may">May</option>
    <option value="june">June</option>
    <option value="july">July</option>
    <option value="august">August</option>
    <option value="september">September</option>
    <option value="october">October</option>
    <option value="november">November</option>
    <option value="december">December</option>
</select>

I am using it to let users select their birth date month. So the first time they signup, they select the month and it's saved. When user wants to edit their profile, I need a way to select the previously selected month for them. Ideas on how to pre-select one of the months are appreciated!

Body:
Try this...

$("#mounth option[value='hide']").each(function() {
$(this).remove();
}

Note, month is spelled wrong. And you might want to actually store the values as the numeric month, January is 1, etc.