问:
Application Crashes on Thread Exit - C++
My application is crashing when it exits the thread function.  This is how my thread is initialized:

```<code>LPTHREAD_START_ROUTINE pThreadStart = (LPTHREAD_START_ROUTINE)NotifyWindowThreadFn;
void * pvThreadData = reinterpret_cast<void *>(_pobjSerialPort);

// Create the exit notify window thread event handle.
_hNotifyWindowThreadExitEvent = ::CreateEvent(
    NULL,                           // No security
    TRUE,                           // Create a manual-reset event object
    FALSE,                          // Initial state is non-signaled
    NULL                            // No name specified
    );

if ( _hNotifyWindowThreadExitEvent == NULL )
{
    TRACE(_T("CreateNotifyWindow : Failed to get a handle for the exit message-only window event.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
    return ::GetLastError();
}

// Create the notify window thread to begin execution on its own.
_hNotifyWindowThread = ::CreateThread(
    NULL,                           // No security attributes.
    0,                              // Use default initial stack size.
    pThreadStart,                   // Function to execute in new thread.
    pvThreadData,                   // Thread parameters.
    0,                              // Use default creation settings.
    NULL                            // Thread ID is not needed.
    );

if ( _hNotifyWindowThread == NULL )
{
    TRACE(_T("CreateNotifyWindow : Failed to create handle for message-only window thread.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
    return ::GetLastError();
}
</code>```

This is the portion of my thread function that gets executed:

```<code>DWORD NotifyWindowThreadFn( void * pParam )
{
    static CNotifyWindow * pobjNotifyWindow = NULL;
    CSerialPort * pobjSerialPort = reinterpret_cast<CSerialPort *>(pParam);

    // Create notify window to handle surprize removal/insertion events...
    try
    {
        pobjNotifyWindow = new CNotifyWindow();
    }
    catch ( DWORD error )
    {
        return error;                // 1. PC gets here
    }
    catch ( long error )
    {
        return error;
    }
    catch ( ... )
    {
        return ERROR_CANNOT_MAKE;
    }

    /* Other stuff that is not executed due to return. */

}                                     // 2. PC then gets here
</code>```

When the application crashes, Visual Studio gives me this error message:

Windows has triggered a breakpoint in CppTestConsole.exe.

This may be due to a corruption of the heap, which indicates a bug in CppTestConsole.exe or any of the DLLs it has loaded.

This may also be due to the user pressing F12 while CppTestConsole.exe has focus.

The output window may have more diagnostic information.

The output window doesn't have anything especially useful.  Only...

The thread 'NotifyWindowThreadFn' (0x414) has exited with code 0 (0x0).

Then it shows that a bunch of DLLs are unloaded.  When I click the Break button, the PC is at the end of _CrtIsValidHeapPointer in dbgheap.c.  Does anyone have any ideas as to why my application is crashing when the thread exits?  Should I not be returning directly from within a threaded function?  Thanks.

答: I might be wrong, but it seems like you're trying to create a window from a worker thread.  Don't do this.  Windows need the message pump in order to function, and there's only one message pump in your application -- it's in the main thread.</p>

Body:
My application is crashing when it exits the thread function.  This is how my thread is initialized:

LPTHREAD_START_ROUTINE pThreadStart = (LPTHREAD_START_ROUTINE)NotifyWindowThreadFn;
void * pvThreadData = reinterpret_cast<void *>(_pobjSerialPort);

// Create the exit notify window thread event handle.
_hNotifyWindowThreadExitEvent = ::CreateEvent(
    NULL,                           // No security
    TRUE,                           // Create a manual-reset event object
    FALSE,                          // Initial state is non-signaled
    NULL                            // No name specified
    );

if ( _hNotifyWindowThreadExitEvent == NULL )
{
    TRACE(_T("CreateNotifyWindow : Failed to get a handle for the exit message-only window event.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
    return ::GetLastError();
}

// Create the notify window thread to begin execution on its own.
_hNotifyWindowThread = ::CreateThread(
    NULL,                           // No security attributes.
    0,                              // Use default initial stack size.
    pThreadStart,                   // Function to execute in new thread.
    pvThreadData,                   // Thread parameters.
    0,                              // Use default creation settings.
    NULL                            // Thread ID is not needed.
    );

if ( _hNotifyWindowThread == NULL )
{
    TRACE(_T("CreateNotifyWindow : Failed to create handle for message-only window thread.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
    return ::GetLastError();
}

This is the portion of my thread function that gets executed:

DWORD NotifyWindowThreadFn( void * pParam )
{
    static CNotifyWindow * pobjNotifyWindow = NULL;
    CSerialPort * pobjSerialPort = reinterpret_cast<CSerialPort *>(pParam);

    // Create notify window to handle surprize removal/insertion events...
    try
    {
        pobjNotifyWindow = new CNotifyWindow();
    }
    catch ( DWORD error )
    {
        return error;                // 1. PC gets here
    }
    catch ( long error )
    {
        return error;
    }
    catch ( ... )
    {
        return ERROR_CANNOT_MAKE;
    }

    /* Other stuff that is not executed due to return. */

}                                     // 2. PC then gets here

When the application crashes, Visual Studio gives me this error message:

Windows has triggered a breakpoint in CppTestConsole.exe.

This may be due to a corruption of the heap, which indicates a bug in CppTestConsole.exe or any of the DLLs it has loaded.

This may also be due to the user pressing F12 while CppTestConsole.exe has focus.

The output window may have more diagnostic information.

The output window doesn't have anything especially useful.  Only...

The thread 'NotifyWindowThreadFn' (0x414) has exited with code 0 (0x0).

Then it shows that a bunch of DLLs are unloaded.  When I click the Break button, the PC is at the end of _CrtIsValidHeapPointer in dbgheap.c.  Does anyone have any ideas as to why my application is crashing when the thread exits?  Should I not be returning directly from within a threaded function?  Thanks.


来源: stackexchange

问:
Bash script to check running process
I wrote a bash-script to check if a process is running. It doesn't work since the ps command always returns exit code 1. When I run the ps command from the command-line, the $? is correctly set, but within the script it is always 1. Any idea?

```<code>#!/bin/bash
SERVICE=$1

ps -a | grep -v grep | grep $1 > /dev/null
result=$?
echo "exit code: ${result}"
if [ "${result}" -eq "0" ] ; then
    echo "`date`: $SERVICE service running, everything is fine"
else
    echo "`date`: $SERVICE is not running"
fi
</code>```

Bash version: GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu)

答:
A solution with service and awk that takes in a comma-delimited list of service names.

First it's probably a good bet you'll need root privileges to do what you want.  If you don't need to check then you can remove that part.

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

# First parameter is a comma-delimited string of service names i.e. service1,service2,service3
SERVICES=$1

ALL_SERVICES_STARTED=true

if [ $EUID -ne 0 ]; then
  if [ "$(id -u)" != "0" ]; then
    echo "root privileges are required" 1>&2
    exit 1
  fi
  exit 1
fi

for service in ${SERVICES//,/ }
do
    STATUS=$(service ${service} status | awk '{print $2}')

    if [ "${STATUS}" != "started" ]; then
        echo "${service} not started"
        ALL_SERVICES_STARTED=false
    fi
done

if ${ALL_SERVICES_STARTED} ; then
    echo "All services started"
    exit 0
else
    echo "Check Failed"
    exit 1
fi
</code>```

ContentLicense: CC BY-SA 4.0

Title: Bash script to check running process

Body:
I wrote a bash-script to check if a process is running. It doesn't work since the ps command always returns exit code 1. When I run the ps command from the command-line, the $? is correctly set, but within the script it is always 1. Any idea?

#!/bin/bash
SERVICE=$1

ps -a | grep -v grep | grep $1 > /dev/null
result=$?
echo "exit code: ${result}"
if [ "${result}" -eq "0" ] ; then
    echo "`date`: $SERVICE service running, everything is fine"
else
    echo "`date`: $SERVICE is not running"
fi

Bash version: GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu)

Body:
A solution with service and awk that takes in a comma-delimited list of service names.

First it's probably a good bet you'll need root privileges to do what you want.  If you don't need to check then you can remove that part.

#!/usr/bin/env bash

# First parameter is a comma-delimited string of service names i.e. service1,service2,service3
SERVICES=$1

ALL_SERVICES_STARTED=true

if [ $EUID -ne 0 ]; then
  if [ "$(id -u)" != "0" ]; then
    echo "root privileges are required" 1>&2
    exit 1
  fi
  exit 1
fi

for service in ${SERVICES//,/ }
do
    STATUS=$(service ${service} status | awk '{print $2}')

    if [ "${STATUS}" != "started" ]; then
        echo "${service} not started"
        ALL_SERVICES_STARTED=false
    fi
done

if ${ALL_SERVICES_STARTED} ; then
    echo "All services started"
    exit 0
else
    echo "Check Failed"
    exit 1
fi

ContentLicense: CC BY-SA 3.0


问:
How to sum two columns using sub query in a grouped data of joined tables
I've a query :

```<code>SELECT COUNT(*) as Avalied
FROM PY_LeaveTransactionMasterTAB as lm
JOIN PY_LeaveTransactionSubsidaryTAB as ls
ON lm.LV_TransMasterId = ls.LV_TransMasterId
WHERE lm.SystemCode = 'faheem123' AND lm.EmployeeCode = '0014' AND lm.Status ='Approved'
Group by lm.Status
</code>```

The Above query returns:

```<code>Availed
-------
   3
</code>```

and another query :

```<code>SELECT PY_Leave + CY_Leave as Openning
FROM PY_LeaveOpeningTAB
WHERE SystemCode = 'faheem123' and EmployeeCode = '0014'
</code>```

this query returns :

```<code>Openning
--------
   25
   23
   30
</code>```

I want to combine the above two queries to get the below result :

```<code>Openning   Availed
--------   --------
   25         3
   23         0
   30         0
</code>```

How do I achieve the above result? Thanks :)

答:
Assuming Availed "belongs" to the first row</p>

```<code>Select A.Opening
      ,Availed = case when A.RN=1 then B.Availed else 0 end)
 From (
        SELECT PY_Leave + CY_Leave as Openning
              ,RN = Row_Number() over (Order by (Select NULL))
         FROM PY_LeaveOpeningTAB
         WHERE SystemCode = 'faheem123' and EmployeeCode = '0014'
      ) A
 Cross Join (
                SELECT COUNT(*) as Avalied
                FROM PY_LeaveTransactionMasterTAB as lm
                JOIN PY_LeaveTransactionSubsidaryTAB as ls
                ON lm.LV_TransMasterId = ls.LV_TransMasterId
                WHERE lm.SystemCode = 'faheem123' AND lm.EmployeeCode = '0014' AND lm.Status ='Approved'
                Group by lm.Status
            ) B
</code>```

Body:
I've a query :

SELECT COUNT(*) as Avalied
FROM PY_LeaveTransactionMasterTAB as lm
JOIN PY_LeaveTransactionSubsidaryTAB as ls
ON lm.LV_TransMasterId = ls.LV_TransMasterId
WHERE lm.SystemCode = 'faheem123' AND lm.EmployeeCode = '0014' AND lm.Status ='Approved'
Group by lm.Status

The Above query returns:

Availed
-------
   3

and another query :

SELECT PY_Leave + CY_Leave as Openning
FROM PY_LeaveOpeningTAB
WHERE SystemCode = 'faheem123' and EmployeeCode = '0014'

this query returns :

Openning
--------
   25
   23
   30

I want to combine the above two queries to get the below result :

Openning   Availed
--------   --------
   25         3
   23         0
   30         0

How do I achieve the above result? Thanks :)

Body:
Assuming Availed "belongs" to the first row

Select A.Opening
      ,Availed = case when A.RN=1 then B.Availed else 0 end)
 From (
        SELECT PY_Leave + CY_Leave as Openning
              ,RN = Row_Number() over (Order by (Select NULL))
         FROM PY_LeaveOpeningTAB
         WHERE SystemCode = 'faheem123' and EmployeeCode = '0014'
      ) A
 Cross Join (
                SELECT COUNT(*) as Avalied
                FROM PY_LeaveTransactionMasterTAB as lm
                JOIN PY_LeaveTransactionSubsidaryTAB as ls
                ON lm.LV_TransMasterId = ls.LV_TransMasterId
                WHERE lm.SystemCode = 'faheem123' AND lm.EmployeeCode = '0014' AND lm.Status ='Approved'
                Group by lm.Status
            ) B


问:
What is UWP analog for Application.StartupPath?
This is my first experience with UWP and currently I porting my WinForms C# app to UWP, so I can use it on my phone.
My app using two files that I store near with it's exe: the PNG and text file. I accessed these with use of Application.StartupPath + "\\my.png" and etc. How I can do the same in UWP?

答:
You can do this by

```<code>BitmapImage bitmapImage = new BitmapImage(new Uri(this.BaseUri, "/Assets/image.jpg"));
</code>```

Assets is a folder name in your UWP project.

For more info https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh965322.aspx

Body:
You can do this by

BitmapImage bitmapImage = new BitmapImage(new Uri(this.BaseUri, "/Assets/image.jpg"));

Assets is a folder name in your UWP project.

For more info https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh965322.aspx


问:
Is this factorial function from a C tutorial wrong?
I have a little programming experience in Python, and for the sake of curiosity I started to learn C, at least the very basics. In a tutorial, I found an example function for calculating a factorial, which is this:

```<code>int factorial(int x)
{
    int i;
    for(i=1; i < x; i++)
    {
        x *= i;
    }
    return x;
}
</code>```

I also added these lines in order to see the output:

```<code>#include <stdio.h>

int main()
{
    int val;
    val = factorial(5);
    printf("%d\n",val);
    return 0;
}
</code>```

Then I compiled the code with gcc factor.c -o factor.out, run and... ooops, the result is -1899959296, clearly there's something wrong.

After a couple of tries, using printf() to print both i and x, I figured out what went wrong (I think): since the condition of the for loop checks if the counter is less than x, and at each step x gets bigger and bigger, i is always less than x, so the loop keeps going on, presumably stopping when the value of x is too big (which should be related to int, I'm not very familiar yet with the various data types).

So, to "solve" the problem, I rewrote the function like this:

```<code>int factorial(int x)
{
    int counter = x;
    int number = x;
    int i;
    for (i=1; i < counter; i++)
    {
        number *= i;
    }
    return number;
}
</code>```

I compiled the program, run, and the value printed is 120, which is correct.

I searched a little bit for examples of factorial functions in C, and found many solutions much better than mine, taking into account negative numbers and formats like long and whatnot, but all of them, in a way or another, seem to rely on two "main" variables, much like my solution.

So, the final question: is the example proposed wrong, or am I missing something? This really bothers me, because if such a simple example is blatantly wrong, I should question the credibility of the rest.

答:
Yes, indeed. The original factorial function is wrong for exactly the reason you've identified. You can't use x as both the accumulator and loop limit.

In your version, one improvement I'd suggest is to get rid of counter. Since you're no longer modifying x,  you don't need to save off a copy of it.

```<code>int factorial(int x)
{
    int number = x;
    int i;
    for (i=1; i < x; i++)
    {
        number *= i;
    }
    return number;
}
</code>```

You could do this without additional variables if you reverse the loop.

```<code>int factorial(int x)
{
    int i;
    for (i = x - 1; i > 1; i--)
    {
        x *= i;
    }
    return x;
}
</code>```

I wouldn't write it this way, though. Modifying an input parameter is poor style.

Body:
I have a little programming experience in Python, and for the sake of curiosity I started to learn C, at least the very basics. In a tutorial, I found an example function for calculating a factorial, which is this:

int factorial(int x)
{
    int i;
    for(i=1; i < x; i++)
    {
        x *= i;
    }
    return x;
}

I also added these lines in order to see the output:

#include <stdio.h>

int main()
{
    int val;
    val = factorial(5);
    printf("%d\n",val);
    return 0;
}

Then I compiled the code with gcc factor.c -o factor.out, run and... ooops, the result is -1899959296, clearly there's something wrong.

After a couple of tries, using printf() to print both i and x, I figured out what went wrong (I think): since the condition of the for loop checks if the counter is less than x, and at each step x gets bigger and bigger, i is always less than x, so the loop keeps going on, presumably stopping when the value of x is too big (which should be related to int, I'm not very familiar yet with the various data types).

So, to "solve" the problem, I rewrote the function like this:

int factorial(int x)
{
    int counter = x;
    int number = x;
    int i;
    for (i=1; i < counter; i++)
    {
        number *= i;
    }
    return number;
}

I compiled the program, run, and the value printed is 120, which is correct.

I searched a little bit for examples of factorial functions in C, and found many solutions much better than mine, taking into account negative numbers and formats like long and whatnot, but all of them, in a way or another, seem to rely on two "main" variables, much like my solution.

So, the final question: is the example proposed wrong, or am I missing something? This really bothers me, because if such a simple example is blatantly wrong, I should question the credibility of the rest.

Body:
Yes, indeed. The original factorial function is wrong for exactly the reason you've identified. You can't use x as both the accumulator and loop limit.

In your version, one improvement I'd suggest is to get rid of counter. Since you're no longer modifying x,  you don't need to save off a copy of it.

int factorial(int x)
{
    int number = x;
    int i;
    for (i=1; i < x; i++)
    {
        number *= i;
    }
    return number;
}

You could do this without additional variables if you reverse the loop.

int factorial(int x)
{
    int i;
    for (i = x - 1; i > 1; i--)
    {
        x *= i;
    }
    return x;
}

I wouldn't write it this way, though. Modifying an input parameter is poor style.


问:
How to center this image in div
I've tried alot of solutions and maybe I just implemented them wrongly for my code but I need help as my yr 11 task is due in 1 more day! Someone save me aha.
I apologize for not having a fiddle example to use as I don't know how to set it up or whatever, also the site just wants me to add more details so I'm just gonna keep writing till it lets me post cause I'm tired af and can't think. Whoever helps me your a bloody legend, cheers from straya :)

.slideshow {
  display: none;
  padding: 10px 0 10px 0;
  margin-top: -50px;
  font-size: 25px;
  overflow-y: hidden;
}

.slide_selection {
  display: inline-block;
  padding: 20px 30px;
}

.slide_selection img {
  height: 40px;
  padding: 5px;
  border-radius: 250px;
  border: #00000099 2px solid;
  transition: all .3s ease-in-out, border .5s;
}

.slide_selection img:hover {
  background-color: #00000099;
}

.slide_icon {
  display: inline;
  float: left;
  padding: 0 30px 0 30px;
  transition: all .15s ease-in-out;
}

.slide_icon:hover {
  transform: scale(1.3);
}

figcaption {
  font-size: 10px;
  font-weight: bold;
}

.slide_content {
  background-color: #00000025;
  box-shadow: inset 0 15px 10px -15px black, inset 0 -13px 10px -15px black;
  margin: -10px 0 0 0;
  padding: 30px 0;
  display: inline-block;
}

.slide_content img {
  height: 95px;
}

.slide_image {
  width: 25%;
  height: 100%;
  float: left;
}

.slide_info {
  display: inline-block;
  float: right;
  width: 75%;
  text-align: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="slideshow">
  <div class="slide_selection">
    <div onclick="test(1);" class="slide_icon"> <img src="https://i.stack.imgur.com/iplpF.png" alt="" />
      <figcaption>WinRar</figcaption>
    </div>
    <div class="slide_icon"> <img src="https://i.stack.imgur.com/iplpF.png" alt="" />
      <figcaption>OllyDBG</figcaption>
    </div>
    <div class="slide_icon"> <img src="https://i.stack.imgur.com/iplpF.png" alt="" />
      <figcaption>NortonAV</figcaption>
    </div>
  </div>
  <div class="slide_content">
    <div class="slide_image">
      <img src="https://i.stack.imgur.com/iplpF.png" alt="" />
    </div>
    <div class="slide_info">
      <h4>Software Type: </h4>
      <h4>Release Date: </h4>
      <p>Winrar Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
        aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

    </div>

  </div>
</div></code>```

答:
i did nt understand your code but i think you need a div container you divise it as much as you need then you put your image in the middle of the page here is an simple example

```<code><div class="container">
<div class="row">
    <div class="igreen col-sm-5 col-md-5 col-lg-5">this is will be green area</div>
    <div class="col-sm-2 col-md-2 col-lg-2"></div>
    <div class="col-sm-5 col-md-5 col-lg-5">step1</div>
    <div class="col-sm-5 col-md-5 col-lg-5">step1</div>
    <div class="col-sm-2 col-md-2 col-lg-2"> <img src="my_image.png"></div>
    <div class="ired col-sm-5 col-md-5 col-lg-5">this is will be a red area</div>
    <div class="col-sm-5 col-md-5 col-lg-5">step1</div>
    <div class="iblue col-sm-2 col-md-2 col-lg-2">this is the blue </div>
    <div class="col-sm-5 col-md-5 col-lg-5">step1</div>

</div>
this is a container
</code>```

Title: How to center this image in div

Body:
I've tried alot of solutions and maybe I just implemented them wrongly for my code but I need help as my yr 11 task is due in 1 more day! Someone save me aha.
I apologize for not having a fiddle example to use as I don't know how to set it up or whatever, also the site just wants me to add more details so I'm just gonna keep writing till it lets me post cause I'm tired af and can't think. Whoever helps me your a bloody legend, cheers from straya :)

.slideshow {
  display: none;
  padding: 10px 0 10px 0;
  margin-top: -50px;
  font-size: 25px;
  overflow-y: hidden;
}

.slide_selection {
  display: inline-block;
  padding: 20px 30px;
}

.slide_selection img {
  height: 40px;
  padding: 5px;
  border-radius: 250px;
  border: #00000099 2px solid;
  transition: all .3s ease-in-out, border .5s;
}

.slide_selection img:hover {
  background-color: #00000099;
}

.slide_icon {
  display: inline;
  float: left;
  padding: 0 30px 0 30px;
  transition: all .15s ease-in-out;
}

.slide_icon:hover {
  transform: scale(1.3);
}

figcaption {
  font-size: 10px;
  font-weight: bold;
}

.slide_content {
  background-color: #00000025;
  box-shadow: inset 0 15px 10px -15px black, inset 0 -13px 10px -15px black;
  margin: -10px 0 0 0;
  padding: 30px 0;
  display: inline-block;
}

.slide_content img {
  height: 95px;
}

.slide_image {
  width: 25%;
  height: 100%;
  float: left;
}

.slide_info {
  display: inline-block;
  float: right;
  width: 75%;
  text-align: left;
}

WinRar

OllyDBG

NortonAV

Software Type:

Release Date:

Winrar Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
        aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Body:
i did nt understand your code but i think you need a div container you divise it as much as you need then you put your image in the middle of the page here is an simple example

<div class="container">
<div class="row">
    <div class="igreen col-sm-5 col-md-5 col-lg-5">this is will be green area</div>
    <div class="col-sm-2 col-md-2 col-lg-2"></div>
    <div class="col-sm-5 col-md-5 col-lg-5">step1</div>
    <div class="col-sm-5 col-md-5 col-lg-5">step1</div>
    <div class="col-sm-2 col-md-2 col-lg-2"> <img src="my_image.png"></div>
    <div class="ired col-sm-5 col-md-5 col-lg-5">this is will be a red area</div>
    <div class="col-sm-5 col-md-5 col-lg-5">step1</div>
    <div class="iblue col-sm-2 col-md-2 col-lg-2">this is the blue </div>
    <div class="col-sm-5 col-md-5 col-lg-5">step1</div>

</div>
this is a container


问:
Cannot insert NULL into column while value is not null
So im having this weird problem with trying to add an instance to the entities. Its a asp.net application using EF 6.0.

The exception:

SqlException: Cannot insert the value NULL into column 'OrderId',
  table 'BETA.MDF.dbo.Orders'; column
  does not allow nulls. INSERT fails. The statement has been terminated.

My code:

```<code>User user = (User)Session["CurrentUser"];
BetaEntities entities = new BetaEntities();

Beta.Order order = new Beta.Order();
order.OrderId = Guid.NewGuid().ToString();
order.OrderDate = DateTime.Now;
order.OrderedBy = user.UserId;
order.HandledBy = entities.Users.Where(x => x.Rank > 0).Select(i => i.UserId).FirstOrDefault();

entities.Orders.Add(order);

entities.SaveChanges();
</code>```

My table:

Also this is my order class, i already tried [Databasegenerated]

```<code>public partial class Order
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public string OrderId { get; set; }
    public System.DateTime OrderDate { get; set; }
    public int OrderedBy { get; set; }
    public int HandledBy { get; set; }
}
</code>```

Example entry:

Please tell me if you need more details.

EDIT:

I tried setting the database datatype of OrderID to UNIQUEIDENTIEFIER and updated the entity model so the database should generate the guid(and i removed  itself but i still get the same exception.

This is my new class:

```<code>public partial class Order
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public System.Guid OrderId { get; set; }
    public System.DateTime OrderDate { get; set; }
    public int OrderedBy { get; set; }
    public int HandledBy { get; set; }
}
</code>```

EDIT:

If i make OrderID NULLABALE and remove the primary key i get the following exception:

System.Data.Entity.Infrastructure.DbUpdateConcurrencyException: 'Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.'

But this can be resolved by adding a primary key :( so removing the PK and making it NULLABLE isnt working.

Also i need to assign to GUID myself for further purposes so letting the database assign the guid itself(with [DatabaseGenerated(DatabaseGeneratedOption.Identity)]) is also not an option.

答:
Your problem is that you set DatabaseGenerated attribute to the OrderId column.

```<code>[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string OrderId { get; set; }
</code>```

With this attribute EF will ignore value you set to OrderId and "try" generate unique value, but generating unique value will not work for string and OrderId will be NULL when INSERT query is generated.

If you are using EF "code first" then change type of OrderId to Guid and remove next line from code

```<code>order.OrderId = Guid.NewGuid().ToString();
</code>```

And leave DatabaseGenerated attribute as it is.

When using DatabaseGenerated attribute for column - means that value of this column will be generated by database.

After changing your structure of Order class, you need update database accordingly. If you using "code-first" approach then you need generate migration script and run it against your database. In "database-first" approach you need update database manually

Even you said removing DatabaseGenerated attribute doesn't help, it will be most simpler solution as suggested by Ivan Stoev in the comments.

Because you generating unique string by yourself using Guid.NewGuid().ToString().

Body:
So im having this weird problem with trying to add an instance to the entities. Its a asp.net application using EF 6.0.

The exception:

SqlException: Cannot insert the value NULL into column 'OrderId',
  table 'BETA.MDF.dbo.Orders'; column
  does not allow nulls. INSERT fails. The statement has been terminated.

My code:

User user = (User)Session["CurrentUser"];
BetaEntities entities = new BetaEntities();

Beta.Order order = new Beta.Order();
order.OrderId = Guid.NewGuid().ToString();
order.OrderDate = DateTime.Now;
order.OrderedBy = user.UserId;
order.HandledBy = entities.Users.Where(x => x.Rank > 0).Select(i => i.UserId).FirstOrDefault();

entities.Orders.Add(order);

entities.SaveChanges();

My table:

Also this is my order class, i already tried [Databasegenerated]

public partial class Order
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public string OrderId { get; set; }
    public System.DateTime OrderDate { get; set; }
    public int OrderedBy { get; set; }
    public int HandledBy { get; set; }
}

Example entry:

Please tell me if you need more details.

EDIT:

I tried setting the database datatype of OrderID to UNIQUEIDENTIEFIER and updated the entity model so the database should generate the guid(and i removed  itself but i still get the same exception.

This is my new class:

public partial class Order
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public System.Guid OrderId { get; set; }
    public System.DateTime OrderDate { get; set; }
    public int OrderedBy { get; set; }
    public int HandledBy { get; set; }
}

EDIT:

If i make OrderID NULLABALE and remove the primary key i get the following exception:

System.Data.Entity.Infrastructure.DbUpdateConcurrencyException: 'Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.'

But this can be resolved by adding a primary key :( so removing the PK and making it NULLABLE isnt working.

Also i need to assign to GUID myself for further purposes so letting the database assign the guid itself(with [DatabaseGenerated(DatabaseGeneratedOption.Identity)]) is also not an option.

Body:
Your problem is that you set DatabaseGenerated attribute to the OrderId column.

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string OrderId { get; set; }

With this attribute EF will ignore value you set to OrderId and "try" generate unique value, but generating unique value will not work for string and OrderId will be NULL when INSERT query is generated.

If you are using EF "code first" then change type of OrderId to Guid and remove next line from code

order.OrderId = Guid.NewGuid().ToString();

And leave DatabaseGenerated attribute as it is.

When using DatabaseGenerated attribute for column - means that value of this column will be generated by database.

After changing your structure of Order class, you need update database accordingly. If you using "code-first" approach then you need generate migration script and run it against your database. In "database-first" approach you need update database manually

Even you said removing DatabaseGenerated attribute doesn't help, it will be most simpler solution as suggested by Ivan Stoev in the comments.

Because you generating unique string by yourself using Guid.NewGuid().ToString().


问:
Target value shape in Lasagne
I am trying to train a Siamese Lasagne model in batches of 100.
The inputs are X1 (100x3x100x100) and X2 (same size) and Y(100x1) and my last layer is a Dense layer of one output dimension as I am expecting a value of 0 or 1 as a target value. However, it is throwing an error for unexpected dimension. Below are the code excerpts:

```<code>input1 = lasagne.layers.InputLayer(shape=(None,3, 100, 100), input_var=None)
conv1_a = lasagne.layers.Conv2DLayer(input1,
                                num_filters=24,
                                filter_size=(7, 7),
                                nonlinearity=lasagne.nonlinearities.rectify)

pool1_a = lasagne.layers.MaxPool2DLayer(conv1_a, pool_size=(3, 3), stride=2)
</code>```

Layer 2 is same as above.
Output Layer:

```<code>dense_b = lasagne.layers.DenseLayer(dense_a,
                                num_units=128,
                                nonlinearity=lasagne.nonlinearities.rectify)
dense_c = lasagne.layers.DenseLayer(dense_b,
                                num_units=1,
                                nonlinearity=lasagne.nonlinearities.softmax)

net_output = lasagne.layers.get_output(dense_c)
true_output = T.ivector('true_output')
</code>```

The training code is below:

```<code>loss_value = train(X1_train,X2_train,Y_train.astype(np.int32))
print loss_value
</code>```

ValueError: Input dimension mis-match. (input[0].shape[1] = 100,
  input[1].shape[1] = 1) Apply node that caused the error:
  Elemwise{Composite{((i0 * i1) + (i2 *
  log1p((-i3))))}}(InplaceDimShuffle{x,0}.0, LogSoftmax.0,
  Elemwise{sub,no_inplace}.0, SoftmaxWithBias.0) Toposort index: 113
  Inputs types: [TensorType(int32, row), TensorType(float32, matrix),
  TensorType(float64, row), TensorType(float32, matrix)] Inputs shapes:
  [(1, 100), (100, 1), (1, 100), (100, 1)] Inputs strides: [(400, 4),
  (4, 4), (800, 8), (4, 4)] Inputs values: ['not shown', 'not shown',
  'not shown', 'not shown'] Outputs clients:
  [[Sum{acc_dtype=float64}(Elemwise{Composite{((i0 * i1) + (i2 *
  log1p((-i3))))}}.0)]]

答:
Try using draw_net.py as follows:

```<code>import draw_net
dot = draw_net.get_pydot_graph(lasagne.layers.get_all_layers(your_last_layer),
verbose = True)

dot.write("test.pdf", format="pdf")
</code>```

to dump the Lasagne graph in pdf format (requires graphviz to be installed)

Title: Target value shape in Lasagne

Body:
I am trying to train a Siamese Lasagne model in batches of 100.
The inputs are X1 (100x3x100x100) and X2 (same size) and Y(100x1) and my last layer is a Dense layer of one output dimension as I am expecting a value of 0 or 1 as a target value. However, it is throwing an error for unexpected dimension. Below are the code excerpts:

input1 = lasagne.layers.InputLayer(shape=(None,3, 100, 100), input_var=None)
conv1_a = lasagne.layers.Conv2DLayer(input1,
                                num_filters=24,
                                filter_size=(7, 7),
                                nonlinearity=lasagne.nonlinearities.rectify)

pool1_a = lasagne.layers.MaxPool2DLayer(conv1_a, pool_size=(3, 3), stride=2)

Layer 2 is same as above.
Output Layer:

dense_b = lasagne.layers.DenseLayer(dense_a,
                                num_units=128,
                                nonlinearity=lasagne.nonlinearities.rectify)
dense_c = lasagne.layers.DenseLayer(dense_b,
                                num_units=1,
                                nonlinearity=lasagne.nonlinearities.softmax)

net_output = lasagne.layers.get_output(dense_c)
true_output = T.ivector('true_output')

The training code is below:

loss_value = train(X1_train,X2_train,Y_train.astype(np.int32))
print loss_value

ValueError: Input dimension mis-match. (input[0].shape[1] = 100,
  input[1].shape[1] = 1) Apply node that caused the error:
  Elemwise{Composite{((i0 * i1) + (i2 *
  log1p((-i3))))}}(InplaceDimShuffle{x,0}.0, LogSoftmax.0,
  Elemwise{sub,no_inplace}.0, SoftmaxWithBias.0) Toposort index: 113
  Inputs types: [TensorType(int32, row), TensorType(float32, matrix),
  TensorType(float64, row), TensorType(float32, matrix)] Inputs shapes:
  [(1, 100), (100, 1), (1, 100), (100, 1)] Inputs strides: [(400, 4),
  (4, 4), (800, 8), (4, 4)] Inputs values: ['not shown', 'not shown',
  'not shown', 'not shown'] Outputs clients:
  [[Sum{acc_dtype=float64}(Elemwise{Composite{((i0 * i1) + (i2 *
  log1p((-i3))))}}.0)]]

Body:
Try using draw_net.py as follows:

import draw_net
dot = draw_net.get_pydot_graph(lasagne.layers.get_all_layers(your_last_layer),
verbose = True)

dot.write("test.pdf", format="pdf")

to dump the Lasagne graph in pdf format (requires graphviz to be installed)


问:
Find how many times team has won and loss the matches?
Find how many times team has won and loss the matches ?

 Find how many times team has won and loss the matches ?
My Table Structure

TeamA | TeamB | Won
A     | D     | D
B     | A     | A
A     | D     | A

Result should be like below

TeamName | Won | Lost
A        | 2   | 1
B        | 0   | 1
D        | 1   | 1```

答:
You need to first fetch all teams by using union of teamA and teamB.

Once that is done then you can have count of winning teams by doing group by operation on won team.

If team won is null it means it lost and not null means if has won and count of that is nothing but no.of times that won the game.  Below is the query for the same

Select t.team, case when won is not null then won else 0 end as won,  case when won is null then 1 else 0 end as lost from (Select teamA aa team from table
Union
Select teamB from table) t left join
(Select won, count(won)  won from table group by won) m on t.team=m.won


问:
Xamarin: Resource.Designer.cs doesn't update when I make changes
I got a problem with my Resource.Designer.cs. I spent well over an hour on google trying to find a solution, but I can't find a fix for my problem.
When I add a button or a text field in the Main.axml editor thing, it doesn't update the Resource.Designer.cs file. So when I write "var label = FindViewById(Resource.Id.textView1);" it shows a red line under the "textView1" because there is nothing about it in the Resource.Designer.cs file.

Even worse:
When I open a blank file and name it as "App1" (the default it was) and add all the things to get the same as in this tutorial, it can't detect the Resource.Layout.Main, since it generates the names wrong.
Screenshot of MainActivity.cs: http://puu.sh/tqsNr/8ac98a5b08.png
Screenshot of Resource.Designer.cs: http://puu.sh/tqsOv/dd1de7328f.png
This is because the namespace in MainActivity is "App1", and it generates the namespace name in Resource.Designer as "application".

How can I fix this? I have very limited time because I have to use this for a school project.

答: To fix it, try adding a new .axml file to project. Worked for me (you can delete the file after it works).


问:
Authorize Attribute Not Working with Roles MVC C#
I'm modifying a system written in c# MVC at the moment.

I've just built in an extra bit of functionality in the Administrator area that allows the administrator create a user account that has limited administrator functionality. I've put the following over each of the controllers for the new functionality:

```<code>[Authorize(Roles = "Administrator")]
</code>```

However, if I log in using limited administrator account, and navigate to this page, it lets me through.

I'm stumped because I appear to be doing this the right way but I'm also fairly new to MVC, is there anything else I can check? I haven't changed anything in the web.config file so that should be ok.

I know there's limited information above, not looking for a ready-made solution, more advice on what I can check to correct the issue.

thanks

EDIT:

This is how the new role/account was created. Go easy too, this is a first ditch attempt, there's not much validation.

```<code>[Authorize(Roles = "Administrator")]
    [HttpPost]
    public ActionResult AddSalesManager(App.Web.Areas.Administrator.Models.SalesManager model, FormCollection formValues)
    {
        if (formValues["Cancel"] != null)
        {
            return RedirectToAction("Index");
        }

        if (!string.Equals(model.password, model.confirmpassword))
        {
            ModelState.AddModelError("password", "Password and Confirmation must match");
        }

        if (ModelState.IsValid)
        {
            using (ModelContainer ctn = new ModelContainer())
            {
                // First, create the user account inside the ASP.Net membership system.
                //

                Membership.ApplicationName = "App";
                Roles.ApplicationName = "App";

                if (!Roles.RoleExists("LimitedAdmin"))
                    Roles.CreateRole("LimitedAdmin");

               // MembershipCreateStatus createStatus = MembershipService.CreateUser(model.email, model.password, model.email);
                if (Membership.GetUser(model.email) == null)
                {
                    Membership.CreateUser(model.email, model.password);
                    Roles.AddUserToRole(model.email, "LimitedAdmin");
                }

            }
        }
        return RedirectToAction("Index");

    }
</code>```

答:
What do you expect from this code?

With this attribute you gain all users in the administrator role the right to execute this controller action no matter how limited the account is.

ContentLicense: CC BY-SA 2.5

Body:
I'm modifying a system written in c# MVC at the moment.

I've just built in an extra bit of functionality in the Administrator area that allows the administrator create a user account that has limited administrator functionality. I've put the following over each of the controllers for the new functionality:

[Authorize(Roles = "Administrator")]

However, if I log in using limited administrator account, and navigate to this page, it lets me through.

I'm stumped because I appear to be doing this the right way but I'm also fairly new to MVC, is there anything else I can check? I haven't changed anything in the web.config file so that should be ok.

I know there's limited information above, not looking for a ready-made solution, more advice on what I can check to correct the issue.

thanks

EDIT:

This is how the new role/account was created. Go easy too, this is a first ditch attempt, there's not much validation.

[Authorize(Roles = "Administrator")]
    [HttpPost]
    public ActionResult AddSalesManager(App.Web.Areas.Administrator.Models.SalesManager model, FormCollection formValues)
    {
        if (formValues["Cancel"] != null)
        {
            return RedirectToAction("Index");
        }

        if (!string.Equals(model.password, model.confirmpassword))
        {
            ModelState.AddModelError("password", "Password and Confirmation must match");
        }

        if (ModelState.IsValid)
        {
            using (ModelContainer ctn = new ModelContainer())
            {
                // First, create the user account inside the ASP.Net membership system.
                //

                Membership.ApplicationName = "App";
                Roles.ApplicationName = "App";

                if (!Roles.RoleExists("LimitedAdmin"))
                    Roles.CreateRole("LimitedAdmin");

               // MembershipCreateStatus createStatus = MembershipService.CreateUser(model.email, model.password, model.email);
                if (Membership.GetUser(model.email) == null)
                {
                    Membership.CreateUser(model.email, model.password);
                    Roles.AddUserToRole(model.email, "LimitedAdmin");
                }

            }
        }
        return RedirectToAction("Index");

    }


问:
Python Module To Detect Linux Distro Version
Is there an existing python module that can be used to detect which distro of Linux and which version of the distro is currently installed.

For example:

RedHat Enterprise 5

Fedora 11

Suse Enterprise 11

etc....

I can make my own module by parsing various files like /etc/redhat-release but I was wondering if a module already exists?

Cheers,
Ivan

答:
I've written a package called distro (now used by pip) which aims to replace distro.linux_distribution. It works on many distributions which might return weird or empty tuples when using platform.

https://github.com/nir0s/distro (distro, on pypi)

It provides a much more elaborate API to retrieve distribution related information.

```<code>$ python
Python 2.7.12 (default, Nov  7 2016, 11:55:55)
[GCC 6.2.1 20160830] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import distro
>>> distro.linux_distribution()
(u'Antergos Linux', '', u'ARCHCODE')
</code>```

By the way, platform.linux_distribution is to be removed in Python 3.7.

Body:
I've written a package called distro (now used by pip) which aims to replace distro.linux_distribution. It works on many distributions which might return weird or empty tuples when using platform.

https://github.com/nir0s/distro (distro, on pypi)

It provides a much more elaborate API to retrieve distribution related information.

$ python
Python 2.7.12 (default, Nov  7 2016, 11:55:55)
[GCC 6.2.1 20160830] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import distro
>>> distro.linux_distribution()
(u'Antergos Linux', '', u'ARCHCODE')

By the way, platform.linux_distribution is to be removed in Python 3.7.


问:
__react-router/v4__How to access history instance in BrowserRouter?
I want to write a redux-middleware to handle history pushState in a react-router v4 application.

The problem is that I cannot access correct instance of history in BrowserRouter easily as it was created within BrowserRouter via createHistory.

My question: Is there an easy way to pass history singleton to BrowserRouter component?

Anyway, this example doesn't work anymore.

https://github.com/ReactTraining/react-router/blob/7f6706dab4827afc1c26a58418f8ef8c8ab40125/website/examples/Redux.js

答:
I temporarily solved this issue which I assume happens with react-router v4.( I also have react-router-dom), like so:

Passing the history object from the component(selector) as argument to the action creator and then in the action creator definition calling history.push('/new-route')

```<code>export function register(user, history) {
// this history is the argument from the register call in the component
    return function (dispatch) {
         dispatch(initRequest()); // show spinner or something
         return Auth.register(user)
             .then(()=> {
                dispatch(registerSuccess());
                history.push('/new-route');

        }).catch((err)=> dispatch(setErrorMessage()))
    }
}
</code>```

also I have to point out that createHistory did not work for me, I had to do:

```<code>import createBrowserHistory from 'history/createBrowserHistory'
const history = createBrowserHistory();
</code>```

Body:
I temporarily solved this issue which I assume happens with react-router v4.( I also have react-router-dom), like so:

Passing the history object from the component(selector) as argument to the action creator and then in the action creator definition calling history.push('/new-route')

export function register(user, history) {
// this history is the argument from the register call in the component
    return function (dispatch) {
         dispatch(initRequest()); // show spinner or something
         return Auth.register(user)
             .then(()=> {
                dispatch(registerSuccess());
                history.push('/new-route');

        }).catch((err)=> dispatch(setErrorMessage()))
    }
}

also I have to point out that createHistory did not work for me, I had to do:

import createBrowserHistory from 'history/createBrowserHistory'
const history = createBrowserHistory();


问:
Print in angularjs
I wrote the below code to print the screen. It is working fine. And it is opening the pdf file also. But behind the pdf file one window is opening. that window will open when we press on pdf file. The problem with that pdf behind window is it is becoming editable. How to remove the behind window.</p>

```<code>angular.element('#hideLeftLinks').addClass("no-print");
var printContents = angular.element('#Print').html();
var popupWin = window.open('', '_blank', 'width=1000,height=1000');
popupWin.document.open();
popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="css/Copyofstyles.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
popupWin.document.close();
popupWin.innerHTML='';
angular.element('#hideLeftLinks').removeClass("no-print");
</code>```

答:
You should check this answer. I tested myself and it seems that the answer is the only one working answer for now. I removed onload="window.print()" and added  and it worked. No need for popupWin.document.close(); and probably popupWin.innerHTML=''; too. So, replace below three lines

```<code>popupWin.document.write('<html><head><link rel="stylesheet" type="text/css"
    href="css/Copyofstyles.css" /></head><body onload="window.print()">' + printContents +
    '</body></html>');
popupWin.document.close();
popupWin.innerHTML='';
</code>```

to

```<code>popupWin.document.write('<html><head><link rel="stylesheet" type="text/css"
    href="css/Copyofstyles.css" /></head><body>' + printContents +
    '<script>window.print(); setTimeout(window.close, 0);</script></body></html>');
</code>```

Title: Print in angularjs

Body:
I wrote the below code to print the screen. It is working fine. And it is opening the pdf file also. But behind the pdf file one window is opening. that window will open when we press on pdf file. The problem with that pdf behind window is it is becoming editable. How to remove the behind window.

angular.element('#hideLeftLinks').addClass("no-print");
var printContents = angular.element('#Print').html();
var popupWin = window.open('', '_blank', 'width=1000,height=1000');
popupWin.document.open();
popupWin.document.write('<link rel="stylesheet" type="text/css" href="css/Copyofstyles.css" />' + printContents + '');
popupWin.document.close();
popupWin.innerHTML='';
angular.element('#hideLeftLinks').removeClass("no-print");

Body:
You should check this answer. I tested myself and it seems that the answer is the only one working answer for now. I removed onload="window.print()" and added <script>window.print(); setTimeout(window.close, 0);</script> and it worked. No need for popupWin.document.close(); and probably popupWin.innerHTML=''; too. So, replace below three lines

popupWin.document.write('<html><head><link rel="stylesheet" type="text/css"
    href="css/Copyofstyles.css" /></head><body onload="window.print()">' + printContents +
    '</body></html>');
popupWin.document.close();
popupWin.innerHTML='';

to

popupWin.document.write('<html><head><link rel="stylesheet" type="text/css"
    href="css/Copyofstyles.css" /></head><body>' + printContents +
    '<script>window.print(); setTimeout(window.close, 0);</script></body></html>');


问:
Unable to upgrade r-base-core package to backports in Debian
I am trying to upgrade r-base-core from version 3.1.1-1 in Debian Jessie to version 3.3.2-1 in jessie-backports.  My setup:

```<code>$ apt-cache policy r-base-core
r-base-core:
  Installed: 3.1.1-1+deb8u1
  Candidate: 3.1.1-1+deb8u1
  Version table:
     3.3.3-1~jessiecran.0 0
        500 http://cran.cnr.berkeley.edu/bin/linux/debian/ jessie-cran3/ Packages
     3.3.2-1~bpo8+1 0
        100 http://ftp.debian.org/debian/ jessie-backports/main amd64 Packages
 *** 3.1.1-1+deb8u1 0
       1000 http://security.debian.org/ jessie/updates/main amd64 Packages
       1000 http://security.debian.org/ stable/updates/main amd64 Packages
        100 /var/lib/dpkg/status
     3.1.1-1+b2 0
        900 http://ftp.us.debian.org/debian/ jessie/main amd64 Packages
        900 http://mirrors.kernel.org/debian/ stable/main amd64 Packages
        900 http://ftp.us.debian.org/debian/ stable/main amd64 Packages
</code>```

When I execute sudo apt-get -t jessie-backports install r-base-core, I get:

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
r-base-core is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 205 not upgraded.
</code>```

Why doesn't it see the jessie-backportsversion as being newer?  How do I debug this?  Thanks for any help.

答:
The display shows the *** for the selected variant.  Below is the all-important score of a 1000 which is higher than the alternatives of 100 and 500, respectively, for the higher versions.

This is a feature called apt-pinning.  You need to adjust the ranking you give the different repos.  At equal or lower score, the upgrade to a higher version happens as you would expect.

Body:
I am trying to upgrade r-base-core from version 3.1.1-1 in Debian Jessie to version 3.3.2-1 in jessie-backports.  My setup:

$ apt-cache policy r-base-core
r-base-core:
  Installed: 3.1.1-1+deb8u1
  Candidate: 3.1.1-1+deb8u1
  Version table:
     3.3.3-1~jessiecran.0 0
        500 http://cran.cnr.berkeley.edu/bin/linux/debian/ jessie-cran3/ Packages
     3.3.2-1~bpo8+1 0
        100 http://ftp.debian.org/debian/ jessie-backports/main amd64 Packages
 *** 3.1.1-1+deb8u1 0
       1000 http://security.debian.org/ jessie/updates/main amd64 Packages
       1000 http://security.debian.org/ stable/updates/main amd64 Packages
        100 /var/lib/dpkg/status
     3.1.1-1+b2 0
        900 http://ftp.us.debian.org/debian/ jessie/main amd64 Packages
        900 http://mirrors.kernel.org/debian/ stable/main amd64 Packages
        900 http://ftp.us.debian.org/debian/ stable/main amd64 Packages

When I execute sudo apt-get -t jessie-backports install r-base-core, I get:

Reading package lists... Done
Building dependency tree
Reading state information... Done
r-base-core is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 205 not upgraded.

Why doesn't it see the jessie-backportsversion as being newer?  How do I debug this?  Thanks for any help.


问:
In-app purchase "Cannot connect to iTunes Store" Xcode 8.3
In iPhone I see this data

and then I get an error  "Cannot connect to iTunes Store".

Transaction Error: Optional("Cannot connect to iTunes Store")

The code where the error appears

```<code>private func fail(transaction: SKPaymentTransaction) {
        print("fail...")
        if let transactionError = transaction.error as? NSError {
            if transactionError.code != SKError.paymentCancelled.rawValue {
                print("Transaction Error: \(transaction.error?.localizedDescription)")
            }
        }
</code>```

Now I check:

iTunes Connect > Features > In-App Purchases - Approved

Use real device - Yes

Connecting to iTunes Sandbox - Yes

"Agreements, Tax, and Banking" of iTunes Connect - Ok

iOS Provisioning Profiles - Active (Type:iOS Distribution; Enabled Services: Game Center, In-App Purchase)

Sign out of iCloud on this device - Yes

Xcode > Capabilities > In-App Purchase - ON (Steps: Link StoreKit.framework - ok; Add the In-App Purchase feature to your App ID - ok)

delete Apple ID from Xcode and all profiles from /Users/****/Library/MobileDevice and re-uploaded everything

Use this tutorial

Previously everything worked fine (swift 3, Xcode Version 8.2.1)

答: Today iTunes Sandbox earned, without any changes without any updates. I think yesterday servers were not work. But why Apple can not be told about this so that developers will not do unnecessary work!!!</p>

Body:
In iPhone I see this data

and then I get an error  "Cannot connect to iTunes Store".

Transaction Error: Optional("Cannot connect to iTunes Store")

The code where the error appears

private func fail(transaction: SKPaymentTransaction) {
        print("fail...")
        if let transactionError = transaction.error as? NSError {
            if transactionError.code != SKError.paymentCancelled.rawValue {
                print("Transaction Error: \(transaction.error?.localizedDescription)")
            }
        }

Now I check:

iTunes Connect > Features > In-App Purchases - Approved

Use real device - Yes

Connecting to iTunes Sandbox - Yes

"Agreements, Tax, and Banking" of iTunes Connect - Ok

iOS Provisioning Profiles - Active (Type:iOS Distribution; Enabled Services: Game Center, In-App Purchase)

Sign out of iCloud on this device - Yes

Xcode > Capabilities > In-App Purchase - ON (Steps: Link StoreKit.framework - ok; Add the In-App Purchase feature to your App ID - ok)

delete Apple ID from Xcode and all profiles from /Users/****/Library/MobileDevice and re-uploaded everything

Use this tutorial

Previously everything worked fine (swift 3, Xcode Version 8.2.1)


问:
Looping over child selectors
greetings,
I have a div wrapped around a bunch of checkboxes on my form.

```<code><div id="checker">
  <input type="checkbox" name="dynamic" id="dynamic" value="dynamic" />
  <input type="checkbox" name="dynamic" id="dynamic" value="dynamic" />
  <input type="checkbox" name="dynamic" id="dynamic" value="dynamic" />
</div>
</code>```

... where "dynamic" (above) is coming from a database and I don't know the names or ids.  These would be created in a loop of php code - not shown.

Using JQuery, how do I access these checkboxes, so I can loop over them?  I'd like to do something like:

```<code>$('#checker').children('checkbox').each( function(){ .... });
</code>```

(I know that is wrong - it's just to show what I'm thinking).

Thoughts?  Thanks
JohnC

答:
```<code>$('#checker input:checkbox').each( function() { ... } );
</code>```

Title: Looping over child selectors

Body:
greetings,
I have a div wrapped around a bunch of checkboxes on my form.

  <input type="checkbox" name="dynamic" id="dynamic" value="dynamic" />
  <input type="checkbox" name="dynamic" id="dynamic" value="dynamic" />
  <input type="checkbox" name="dynamic" id="dynamic" value="dynamic" />

... where "dynamic" (above) is coming from a database and I don't know the names or ids.  These would be created in a loop of php code - not shown.

Using JQuery, how do I access these checkboxes, so I can loop over them?  I'd like to do something like:

$('#checker').children('checkbox').each( function(){ .... });

(I know that is wrong - it's just to show what I'm thinking).

Thoughts?  Thanks
JohnC


问:
Counting the position of a character after two or more spaces
I am trying to return a value equal to the position of the first letter coming after two or more spaces.

I have a tool that extract tables with variable column length into TXT docs. I need to get these tables into an Excel sheet without having to put fixed width to each column in each table (that is a lot of coding to be done). I am trying to find something more dynamic to do so based on the position of the first character after two or more spaces.

Bearing in mind that not all rows are fully populated but the first row would make a perfect candidate to get the width of the column.

To give an example, the lines of the text would look like this

John       Robert       Eric       Tom

10          11            143        43

21                       265        56

99          241                     76

All I got so far is to make it work with fixed width as per the code below

```<code>Sub exporttosheet()

Dim fPath As String
fPath = "C:\test.txt"

Const fsoForReading = 1
Const F_LEN_A As Integer = 10
Const F_LEN_B As Integer = 23
Const F_LEN_C As Integer = 7
Const F_LEN_D As Integer = 10

Dim objFSO As Object, objTextStream As Object, txt, f1, f2, f3, f4
Dim start As Integer
Dim fLen As Integer
Dim rw As Long

Set objFSO = CreateObject("scripting.filesystemobject")
Set objTextStream = objFSO.OpenTextFile(fPath, fsoForReading)
rw = 1

Do Until objTextStream.AtEndOfStream
    txt = objTextStream.Readline

    f1 = Trim(Left(txt, F_LEN_A))
    start = F_LEN_A + 1
    f2 = Trim(Mid(txt, start, F_LEN_B))
    start = start + F_LEN_B + 1
    f3 = Trim(Mid(txt, start, F_LEN_C))
    start = start + F_LEN_C + 1
    f4 = Trim(Mid(txt, start, F_LEN_D))

    With ThisWorkbook.Sheets("data").Cells(rw, 1).Resize(1, 4)
        .NumberFormat = "@" 'format cells as text
        .Value = Array(f1, f2, f3, f4)
    End With
    rw = rw + 1
Loop

objTextStream.Close
End Sub
</code>```

答:
You may try this function below:

```<code>Public Function InterpretLine(strLine As String) As Variant
    Dim rgxCell As RegExp: Set rgxCell = New RegExp
    rgxCell.Pattern = "([^ ]+([ ]?[^ ]+)*)"
    rgxCell.Global = True
    Dim mtcResult As MatchCollection: Set mtcResult = rgxCell.Execute(strLine)
    Dim strResult() As String: ReDim strResult(0 To mtcResult.Count - 1)
    Dim i As Long: For i = 0 To mtcResult.Count - 1
        strResult(i) = mtcResult.Item(i)
    Next i
    InterpretLine = strResult
End Function
</code>```

It takes a line as a string value and returns an array of strings (each element is a cell from the line). My assumption is that none of the cells contais 2 consecutive space characters and that between cells there is always at least two space characters. (Here, space character means only the one which is input through the long key on the keyboard, tabs linefeeds, etc. are not included.)

To use Regex in VBA, you need the following Reference (in the VBA Editor choose Tools > References), and check the following option:

Body:
I am trying to return a value equal to the position of the first letter coming after two or more spaces.

I have a tool that extract tables with variable column length into TXT docs. I need to get these tables into an Excel sheet without having to put fixed width to each column in each table (that is a lot of coding to be done). I am trying to find something more dynamic to do so based on the position of the first character after two or more spaces.

Bearing in mind that not all rows are fully populated but the first row would make a perfect candidate to get the width of the column.

To give an example, the lines of the text would look like this

John       Robert       Eric       Tom

10          11            143        43

21                       265        56

99          241                     76

All I got so far is to make it work with fixed width as per the code below

Sub exporttosheet()

Dim fPath As String
fPath = "C:\test.txt"

Const fsoForReading = 1
Const F_LEN_A As Integer = 10
Const F_LEN_B As Integer = 23
Const F_LEN_C As Integer = 7
Const F_LEN_D As Integer = 10

Dim objFSO As Object, objTextStream As Object, txt, f1, f2, f3, f4
Dim start As Integer
Dim fLen As Integer
Dim rw As Long

Set objFSO = CreateObject("scripting.filesystemobject")
Set objTextStream = objFSO.OpenTextFile(fPath, fsoForReading)
rw = 1

Do Until objTextStream.AtEndOfStream
    txt = objTextStream.Readline

    f1 = Trim(Left(txt, F_LEN_A))
    start = F_LEN_A + 1
    f2 = Trim(Mid(txt, start, F_LEN_B))
    start = start + F_LEN_B + 1
    f3 = Trim(Mid(txt, start, F_LEN_C))
    start = start + F_LEN_C + 1
    f4 = Trim(Mid(txt, start, F_LEN_D))

    With ThisWorkbook.Sheets("data").Cells(rw, 1).Resize(1, 4)
        .NumberFormat = "@" 'format cells as text
        .Value = Array(f1, f2, f3, f4)
    End With
    rw = rw + 1
Loop

objTextStream.Close
End Sub

Body:
You may try this function below:

Public Function InterpretLine(strLine As String) As Variant
    Dim rgxCell As RegExp: Set rgxCell = New RegExp
    rgxCell.Pattern = "([^ ]+([ ]?[^ ]+)*)"
    rgxCell.Global = True
    Dim mtcResult As MatchCollection: Set mtcResult = rgxCell.Execute(strLine)
    Dim strResult() As String: ReDim strResult(0 To mtcResult.Count - 1)
    Dim i As Long: For i = 0 To mtcResult.Count - 1
        strResult(i) = mtcResult.Item(i)
    Next i
    InterpretLine = strResult
End Function

It takes a line as a string value and returns an array of strings (each element is a cell from the line). My assumption is that none of the cells contais 2 consecutive space characters and that between cells there is always at least two space characters. (Here, space character means only the one which is input through the long key on the keyboard, tabs linefeeds, etc. are not included.)

To use Regex in VBA, you need the following Reference (in the VBA Editor choose Tools > References), and check the following option:


问:
instance Of Operator in java
```<code>class A {}

class B {}

public class Demo {

    public static void main(String[] args) {

        A a = new A();
        System.out.println(a instanceof B);
    }

}
</code>```

This code is giving compile time error.
How can I use instanceof to give false instead of compile time error when object is not an instance of class specified.

答:
If class A and B are not related through inheritance, then compiler will throw an error when you try to perform a instanceof B

In your case, A is NOT a subclass of B, so you can't do an instanceof check like a instanceof B

But, if you change your classes like below:

```<code>class A {}

class B extends A {}

public static void main(String[] args) {
   B b=new B();
   System.out.println(b instanceof A);
}
</code>```

Now b instanceof A will return true because B IS-A (type of) A

You can read the Java doc here on the same subject:

The instanceof operator compares an object to a specified type. You
  can use it to test if an object is an instance of a class, an instance
  of a subclass, or an instance of a class that implements a particular
  interface.

Title: instance Of Operator in java

Body:
class A {}

class B {}

public class Demo {

    public static void main(String[] args) {

        A a = new A();
        System.out.println(a instanceof B);
    }

}

This code is giving compile time error.
How can I use instanceof to give false instead of compile time error when object is not an instance of class specified.

Body:
If class A and B are not related through inheritance, then compiler will throw an error when you try to perform a instanceof B

In your case, A is NOT a subclass of B, so you can't do an instanceof check like a instanceof B

But, if you change your classes like below:

class A {}

class B extends A {}

public static void main(String[] args) {
   B b=new B();
   System.out.println(b instanceof A);
}

Now b instanceof A will return true because B IS-A (type of) A

You can read the Java doc here on the same subject:

The instanceof operator compares an object to a specified type. You
  can use it to test if an object is an instance of a class, an instance
  of a subclass, or an instance of a class that implements a particular
  interface.


问:
Scroll Bug in Elastic gird jquery plugin
I'm using the elastic grid plugin to display my gallery.
I discoverd a bug in the plugin and I'm wondering how to fix it.

To recreate the bug:

1) click an image to reveal expanded details.

2) clicking on an image in a row below the current slide out causes the plugin to wrongly calulate the scroll. Clicking above the slide out seems to work fine.

Has anyone discoverd a solution to this bug? I've attached reference images

Thanks for your time. Cheers

答:
I was facing the same problem. Sometimes the page would just scroll itself to the top.

I realized I was using a function(on document.ready()) which was acting upon the List-Categories before it was completely loaded.

See if you're doing something similar..
Let the Plugin Completely Load


问:
Concat in MySQL with condition
I have three columns in my table - company_name, first_name, last_name. In the result of a SELECT, I'd like to have only one column: name, which should contain content of company_name if it's not NULL or concatenation of first_name +' '+  last_name, if the company_name is not set.

Any advice? Thanks!

答:
```<code>SELECT IFNULL(company_name,CONCAT(first_name,' ',last_name)) as NAME
</code>```

OwnerDisplayName: Milan Novota

Title: Concat in MySQL with condition

OwnerDisplayName: Ivan


Title: Looping over child selectors

Body: $('#checker input:type="checkbox"').each(...);


问:
Excess thin line under div with background image
I have div with next styles:

```<code>.top-pattern {
  width: 1024px;
  height: 92px;
  background-image: url("https://s21.postimg.org/p0amqt8wn/pattern-top-big.png");
  background-repeat: repeat-x;
  background-size: contain;
}
</code>```

It is pretty simple and works great. But at some devices (mac and mobile) there is weird line appeared under the div. What is this? How to remove it?

Example: https://jsfiddle.net/wx92fb61/

Screenshot: https://gyazo.com/3020d6720d27fcbd0315a55fce0fb016

P.S. I checked my image hundred times: there is NO line in the image.

答:
See, if you can override this CSS class and remove box-shadow.
I think this is what is getting you that border.</p>

```<code>.image-box-component .image-viewer {
     box-shadow: 0 0 0px rgba(0,0,0,0) !important;
}
</code>```

Body:
I have div with next styles:

.top-pattern {
  width: 1024px;
  height: 92px;
  background-image: url("https://s21.postimg.org/p0amqt8wn/pattern-top-big.png");
  background-repeat: repeat-x;
  background-size: contain;
}

It is pretty simple and works great. But at some devices (mac and mobile) there is weird line appeared under the div. What is this? How to remove it?

Example: https://jsfiddle.net/wx92fb61/

Screenshot: https://gyazo.com/3020d6720d27fcbd0315a55fce0fb016

P.S. I checked my image hundred times: there is NO line in the image.

Body:
See, if you can override this CSS class and remove box-shadow.
I think this is what is getting you that border.

.image-box-component .image-viewer {
     box-shadow: 0 0 0px rgba(0,0,0,0) !important;
}


问:
Object is null after being initialized in a method
I'm new to programming and I have a problem in my code.
I start by initializing the Maze object to null because I don't know which will be the choice of the user. It is initialized in the method createMaze() but when I call printMaze it is null.</p>

```<code>import java.util.Scanner;

public class Main {
    public static final String EXITGAME = "EXIT";
    public static final String PRINTBOARD = "PRINT";
    public static final String CREATEMAZE = "UPLOAD";

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Maze maze = null;

        menu(maze,in);
    }

    private static void menu(Maze maze, Scanner in){
        String option = in.nextLine();
        while(option.toUpperCase() != EXITGAME){
            switch(option.toUpperCase()){
                case PRINTBOARD: printMaze(maze); break;
                case CREATEMAZE: createMaze(in,maze); break;
            }
            System.out.println();
            option = in.nextLine();
        }
    }

    private static void printMaze(Maze maze){
        if(maze != null){
            int maxX = maze.getxSize();
            int maxY = maze.getySize();

            for(int x = 0; x < maxX; x++){
                for(int y = 0; y < maxY; y++){
                    System.out.print(maze.getMazeRepresentation(x, y));
                }
                System.out.println();
            }
        }
        else
            System.out.println("Maze is undefined");
    }

    private static void createMaze(Scanner in, Maze maze){
        if(maze == null || !maze.getGameStatus()){
            int x = in.nextInt();
            int y = in.nextInt();
            in.nextLine();
            char rawMaze[][] = new char[x][y];

            maze = new MazeClass(x,y);

            for(int i = 0; i < x; i++){
                createMazeLine(in,i,y, rawMaze);
            }
            maze.createMaze(rawMaze);
        }
        else
            System.out.println("Maze already defined.");
    }

    private static void createMazeLine(Scanner in, int lines, int y, char[][] rawMaze){
        String line = in.nextLine();

        for(int i = 0; i < y; i++){
            rawMaze[lines][i] = line.charAt(i);
        }
    }
}
</code>```

答:
in Java when you pass parameter to the method (i.e. Maze maze createMaze(Scanner in, Maze maze) it is a value of reference to the maze.
In other words in your case:

there is a null value.

there is a reference to that null called null

in call to the method value of that reference passed (let say address) as pramemter

in method call there is a parameter variable which holds value of that reference

Java does not have "parameters by reference" or pointers conception.

So, when inside the method createMaze you do maze = new MazeClass(x,y);

you assign new object maze reference to the reference parameter variable.

But your initial null value and reference to it outside of method stay untouched and object you created inside method destroyed after method done.

In short, all you need is:

```<code>private static void menu(Maze maze, Scanner in){
    String option = in.nextLine();
    while(option.toUpperCase() != EXITGAME){
        switch(option.toUpperCase()){
            case PRINTBOARD: printMaze(maze); break;
            case CREATEMAZE: maze = createMaze(in,maze); break;
        }
        System.out.println();
        option = in.nextLine();
    }
}

private static Maze createMaze(Scanner in, Maze maze){
    if(maze == null || !maze.getGameStatus()){
        ... yuor code ...
        maze.createMaze(rawMaze);
    }
    else
        System.out.println("Maze already defined.");

    return maze;
}
</code>```

Of course code can be written in more clear style, but main point is

new value assignment to the method parameter inside the method does not replace value of variable passed as parameter in the caller

Body:
I'm new to programming and I have a problem in my code.
I start by initializing the Maze object to null because I don't know which will be the choice of the user. It is initialized in the method createMaze() but when I call printMaze it is null.

import java.util.Scanner;

public class Main {
    public static final String EXITGAME = "EXIT";
    public static final String PRINTBOARD = "PRINT";
    public static final String CREATEMAZE = "UPLOAD";

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Maze maze = null;

        menu(maze,in);
    }

    private static void menu(Maze maze, Scanner in){
        String option = in.nextLine();
        while(option.toUpperCase() != EXITGAME){
            switch(option.toUpperCase()){
                case PRINTBOARD: printMaze(maze); break;
                case CREATEMAZE: createMaze(in,maze); break;
            }
            System.out.println();
            option = in.nextLine();
        }
    }

    private static void printMaze(Maze maze){
        if(maze != null){
            int maxX = maze.getxSize();
            int maxY = maze.getySize();

            for(int x = 0; x < maxX; x++){
                for(int y = 0; y < maxY; y++){
                    System.out.print(maze.getMazeRepresentation(x, y));
                }
                System.out.println();
            }
        }
        else
            System.out.println("Maze is undefined");
    }

    private static void createMaze(Scanner in, Maze maze){
        if(maze == null || !maze.getGameStatus()){
            int x = in.nextInt();
            int y = in.nextInt();
            in.nextLine();
            char rawMaze[][] = new char[x][y];

            maze = new MazeClass(x,y);

            for(int i = 0; i < x; i++){
                createMazeLine(in,i,y, rawMaze);
            }
            maze.createMaze(rawMaze);
        }
        else
            System.out.println("Maze already defined.");
    }

    private static void createMazeLine(Scanner in, int lines, int y, char[][] rawMaze){
        String line = in.nextLine();

        for(int i = 0; i < y; i++){
            rawMaze[lines][i] = line.charAt(i);
        }
    }
}

Body:
in Java when you pass parameter to the method (i.e. Maze maze createMaze(Scanner in, Maze maze) it is a value of reference to the maze.
In other words in your case:

there is a null value.

there is a reference to that null called null

in call to the method value of that reference passed (let say address) as pramemter

in method call there is a parameter variable which holds value of that reference

Java does not have "parameters by reference" or pointers conception.

So, when inside the method createMaze you do maze = new MazeClass(x,y);

you assign new object maze reference to the reference parameter variable.

But your initial null value and reference to it outside of method stay untouched and object you created inside method destroyed after method done.

In short, all you need is:

private static void menu(Maze maze, Scanner in){
    String option = in.nextLine();
    while(option.toUpperCase() != EXITGAME){
        switch(option.toUpperCase()){
            case PRINTBOARD: printMaze(maze); break;
            case CREATEMAZE: maze = createMaze(in,maze); break;
        }
        System.out.println();
        option = in.nextLine();
    }
}

private static Maze createMaze(Scanner in, Maze maze){
    if(maze == null || !maze.getGameStatus()){
        ... yuor code ...
        maze.createMaze(rawMaze);
    }
    else
        System.out.println("Maze already defined.");

    return maze;
}

Of course code can be written in more clear style, but main point is

new value assignment to the method parameter inside the method does not replace value of variable passed as parameter in the caller


问:
Accessing command line (cmd) from RStudio
In my work under R I need to make the call to another software (ANSYS)
For that I am looking for a command under R which allows access to the command line windows (cmd).
For example under matlab the character (!) Allows to do it
thank you</p>

答:
The only portable functions are system() and system2(). All relevant information is as usual in the behind help("system").  R will then execute whatever command you give it provided it is in the $PATH.

In case you wanted to also work interactively, you can use a more recent daily build of RStudio, you will get a completely full-feature terminal tab as well.  So just upgrade to a daily build.

OwnerDisplayName: Hamid Hamdani


问:
Getting "TypeError: float() argument must be a string or a number" with pandas plot()
I am going thru simple pandas tutorial. And I am trying to plot DataFrame indexed by dtype='datetime64[ns]', however, when I try to plot, I assume the matplotlib attempts to convert the date to float, which raises an exception.

```<code>>>> df.index
DatetimeIndex(['2012-01-01', '2012-01-02', '2012-01-03', '2012-01-04',
           '2012-01-05', '2012-01-06', '2012-01-07', '2012-01-08',
           '2012-01-09', '2012-01-10',
           ...
           '2012-12-22', '2012-12-23', '2012-12-24', '2012-12-25',
           '2012-12-26', '2012-12-27', '2012-12-28', '2012-12-29',
           '2012-12-30', '2012-12-31'],
          dtype='datetime64[ns]', name=u'Date', length=366, freq=None)

>>> df.plot()
Traceback (most recent call last):
  ...
  File "/usr/local/lib/python2.7/dist-packages/matplotlib/lines.py", line 676, in recache
    x = np.asarray(xconv, np.float_)
  File "/usr/local/lib/python2.7/dist-packages/numpy/core/numeric.py", line 531, in asarray
    return array(a, dtype, copy=False, order=order)
TypeError: float() argument must be a string or a number
</code>```

What am I doing wrong?

note: I am following very simple tutorial here: http://nbviewer.jupyter.org/github/jvns/pandas-cookbook/blob/v0.1/cookbook/Chapter%201%20-%20Reading%20from%20a%20CSV.ipynb

答:
The tutorial is plotting the numbers in colmn 2, not the date in column 1:

Date

2012-01-01         35

2012-01-02         83

2012-01-03        135

....

Thus your plot is missing something, check your input again ...

Body:
I am going thru simple pandas tutorial. And I am trying to plot DataFrame indexed by dtype='datetime64[ns]', however, when I try to plot, I assume the matplotlib attempts to convert the date to float, which raises an exception.

>>> df.index
DatetimeIndex(['2012-01-01', '2012-01-02', '2012-01-03', '2012-01-04',
           '2012-01-05', '2012-01-06', '2012-01-07', '2012-01-08',
           '2012-01-09', '2012-01-10',
           ...
           '2012-12-22', '2012-12-23', '2012-12-24', '2012-12-25',
           '2012-12-26', '2012-12-27', '2012-12-28', '2012-12-29',
           '2012-12-30', '2012-12-31'],
          dtype='datetime64[ns]', name=u'Date', length=366, freq=None)

>>> df.plot()
Traceback (most recent call last):
  ...
  File "/usr/local/lib/python2.7/dist-packages/matplotlib/lines.py", line 676, in recache
    x = np.asarray(xconv, np.float_)
  File "/usr/local/lib/python2.7/dist-packages/numpy/core/numeric.py", line 531, in asarray
    return array(a, dtype, copy=False, order=order)
TypeError: float() argument must be a string or a number

What am I doing wrong?

note: I am following very simple tutorial here: http://nbviewer.jupyter.org/github/jvns/pandas-cookbook/blob/v0.1/cookbook/Chapter%201%20-%20Reading%20from%20a%20CSV.ipynb


问:
Connection timeout on query on large table
I have a problem with a script timing out while fetching data form a query on large table.

The table have 9,521,457 rows.

The query I'm trying to preform is:

```<code>SELECT *
FROM `dialhistory`
WHERE `customerId` IN (22606536, 22707251, 41598836);
</code>```

This query runs without problems on HeidiSQL and take about 171 seconds and returns 434 rows.

But when I run my C# script dose it timeout after 161 rows.

```<code>16:54:55: Row 1
...
16:54:55: Row 161
16:55:32: Error -> Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
</code>```

Here is the code

```<code>public MySqlDatabase(string server, string database, string username, string password)
{
    ConnectionString = "SERVER=" + server + ";DATABASE=" + database + ";UID=" + username + ";PASSWORD=" + password + ";";

}

public IQueryable<DailHistory> GetHistory(IList<int> customerIds)
{
    IList<DailHistory> list = new List<DailHistory>();
    var connection = new MySqlConnection(ConnectionString);
    connection.Open();
    var command = connection.CreateCommand();
    command.CommandText = "SELECT * FROM `dialhistory` WHERE `customerId` in ("+string.Join(",", customerIds.ToArray())+")";
    var reader = command.ExecuteReader();
    int i = 1;
    while (reader.Read())
    {
        Console.WriteLine(DateTime.Now.ToLongTimeString() + ": Row " + i);
        i++;
        try
        {
            var d = new DailHistory();
            d.CustomerId = int.Parse((string) reader["customerId"]);
            d.Agent = ParseNullAbleString(reader["agent"].ToString());
            d.CallBackReason = ParseNullAbleString(reader["callBackReason"].ToString());
            d.CallState = ParseCallSate(reader["callState"].ToString());
            d.ContactResponse = ParseNullAbleString(reader["contactResponse"].ToString());
            d.DailTime = new DailTime(reader["dialStart"].ToString(), reader["dialEnd"].ToString());
            d.HistoryIndex = int.Parse(reader["historyIndex"].ToString());
            d.Note = ParseNullAbleString(reader["note"].ToString());
            d.OldDialNo = ParseNullAbleInt(reader["oldDialNo"].ToString());
            d.ProjectJob = ParseNullAbleString(reader["projectJob"].ToString());
            list.Add(d);
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
    reader.Close();
    return list.AsQueryable();
}
</code>```

答:
```<code>command.CommandTimeout = int.MaxValue;
</code>```

If you know more exactly which number to insert, do that. If you set it to int.MaxValue, you are removing a security barrier.

Body:
I have a problem with a script timing out while fetching data form a query on large table.

The table have 9,521,457 rows.

The query I'm trying to preform is:

SELECT *
FROM `dialhistory`
WHERE `customerId` IN (22606536, 22707251, 41598836);

This query runs without problems on HeidiSQL and take about 171 seconds and returns 434 rows.

But when I run my C# script dose it timeout after 161 rows.

16:54:55: Row 1
...
16:54:55: Row 161
16:55:32: Error -> Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.

Here is the code

public MySqlDatabase(string server, string database, string username, string password)
{
    ConnectionString = "SERVER=" + server + ";DATABASE=" + database + ";UID=" + username + ";PASSWORD=" + password + ";";

}

public IQueryable<DailHistory> GetHistory(IList<int> customerIds)
{
    IList<DailHistory> list = new List<DailHistory>();
    var connection = new MySqlConnection(ConnectionString);
    connection.Open();
    var command = connection.CreateCommand();
    command.CommandText = "SELECT * FROM `dialhistory` WHERE `customerId` in ("+string.Join(",", customerIds.ToArray())+")";
    var reader = command.ExecuteReader();
    int i = 1;
    while (reader.Read())
    {
        Console.WriteLine(DateTime.Now.ToLongTimeString() + ": Row " + i);
        i++;
        try
        {
            var d = new DailHistory();
            d.CustomerId = int.Parse((string) reader["customerId"]);
            d.Agent = ParseNullAbleString(reader["agent"].ToString());
            d.CallBackReason = ParseNullAbleString(reader["callBackReason"].ToString());
            d.CallState = ParseCallSate(reader["callState"].ToString());
            d.ContactResponse = ParseNullAbleString(reader["contactResponse"].ToString());
            d.DailTime = new DailTime(reader["dialStart"].ToString(), reader["dialEnd"].ToString());
            d.HistoryIndex = int.Parse(reader["historyIndex"].ToString());
            d.Note = ParseNullAbleString(reader["note"].ToString());
            d.OldDialNo = ParseNullAbleInt(reader["oldDialNo"].ToString());
            d.ProjectJob = ParseNullAbleString(reader["projectJob"].ToString());
            list.Add(d);
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
    reader.Close();
    return list.AsQueryable();
}

Body:
command.CommandTimeout = int.MaxValue;

If you know more exactly which number to insert, do that. If you set it to int.MaxValue, you are removing a security barrier.


问:
Using CXF with Spring Boot Actuator
I am working on a web service host application in which using cxf with spring boot. when I register cxf servlet with following code web service side works and I can see published wsdls. </p>

<p>However after setting cxf servlet Spring boot actuator and rest endpoints not working and returning 404. How can I solve this issue ? </p>

```<code>@Bean
public ServletRegistrationBean cxfServlet() {
    return new ServletRegistrationBean(new CXFServlet(), "/soap-api/*");
}
</code>```

答:
I looks like there is a clash between servlets.

You can check it in your logs. There should be:

```<code>2017-04-01 15:34:04,029 [restartedMain] INFO  o.s.b.w.s.ServletRegistrationBean - Mapping servlet: 'CXFServlet' to [/soap-api/*]

2017-04-01 15:34:04,031 [restartedMain] INFO  o.s.b.w.s.ServletRegistrationBean - Mapping servlet: 'dispatcherServlet' to [/]
</code>```

There should be exactly two servlets and the path should be different.

If there is one missing the enpoints won't work.

dispatcherServlet is spring default one to handle actuator metrics

Title: Using CXF with Spring Boot Actuator

Body:
I am working on a web service host application in which using cxf with spring boot. when I register cxf servlet with following code web service side works and I can see published wsdls.

However after setting cxf servlet Spring boot actuator and rest endpoints not working and returning 404. How can I solve this issue ?

@Bean
public ServletRegistrationBean cxfServlet() {
    return new ServletRegistrationBean(new CXFServlet(), "/soap-api/*");
}

Body:
I looks like there is a clash between servlets.

You can check it in your logs. There should be:

2017-04-01 15:34:04,029 [restartedMain] INFO  o.s.b.w.s.ServletRegistrationBean - Mapping servlet: 'CXFServlet' to [/soap-api/*]

2017-04-01 15:34:04,031 [restartedMain] INFO  o.s.b.w.s.ServletRegistrationBean - Mapping servlet: 'dispatcherServlet' to [/]

There should be exactly two servlets and the path should be different.

If there is one missing the enpoints won't work.

dispatcherServlet is spring default one to handle actuator metrics


问:
BigQuery/SQL: Sum over intervals indicated by a secondary table
Suppose I have two tables: intervals contains index intervals (its columns are i_min and i_max) and values contains indexed values (with columns i and x). Here's an example:

```<code> values:        intervals:
+---+---+   +-------+-------+
| i | x |   | i_min | i_max |
+-------+   +---------------+
| 1 | 1 |   |   1   |   4   |
| 2 | 0 |   |   6   |   6   |
| 3 | 4 |   |   6   |   6   |
| 4 | 9 |   |   6   |   6   |
| 6 | 7 |   |   7   |   9   |
| 7 | 2 |   |  12   |  17   |
| 8 | 2 |   +-------+-------+
| 9 | 2 |
+---+---+
</code>```

I want to sum the values of x for each interval:

```<code>       result:
+-------+-------+-----+
| i_min | i_max | sum |
+---------------------+
|   1   |   4   |  13 | // 1+0+4+9
|   6   |   6   |   7 |
|   6   |   6   |   7 |
|   6   |   6   |   7 |
|   7   |   9   |   6 | // 2+2+2
|  12   |  17   |   0 |
+-------+-------+-----+
</code>```

In some SQL engines, this could be done using:

```<code>SELECT
  i_min,
  i_max,
  (SELECT SUM(x)
   FROM values
   WHERE i BETWEEN intervals.i_min AND intervals.i_max) AS sum_x
FROM
  intervals
</code>```

except that type of query is not allowed by BigQuery ("Subselect not allowed in SELECT clause." or "LEFT OUTER JOIN cannot be used without a condition that is an equality of fields from both sides of the join." depending on the syntax used).

There must be a way to do this with window functions, but I can't figure out how — all examples I've seen have the partition as part of the table. Is there an option that doesn't use CROSS JOIN? If not, what's the most efficient way to do this CROSS JOIN?

Some notes on my data:

Both tables contain many (10⁸-10⁹) rows.

There might be repetitions in intervals, not in i.

But two intervals in intervals are either the same, either entirely disjoint (no overlaps).

The union of all intervals is typically close to the set of all values of i (so it forms a partition of this space).

Intervals might be large (say, i_max-i_min < 10⁶).

答:
Try below - BigQuery Standard SQL  </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
SELECT
  i_min, i_max, SUM(x) AS  sum_x
FROM (
  SELECT i_min, i_max, ROW_NUMBER() OVER() AS line FROM `project.dataset.intervals`
) AS intervals
JOIN (SELECT i, x FROM `project.dataset.values` UNION ALL SELECT NULL, 0) AS values
ON values.i BETWEEN intervals.i_min AND intervals.i_max OR values.i IS NULL
GROUP BY i_min, i_max, line
-- ORDER BY i_min
</code>```

<p>you can play/test with dummy data as below   </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
WITH intervals AS (
  SELECT  1 AS i_min, 4 AS i_max UNION ALL
  SELECT  6, 6 UNION ALL
  SELECT  6, 6 UNION ALL
  SELECT  6, 6 UNION ALL
  SELECT  7, 9 UNION ALL
  SELECT 12, 17
),
values AS (
  SELECT 1 AS i, 1 AS x UNION ALL
  SELECT 2, 0 UNION ALL
  SELECT 3, 4 UNION ALL
  SELECT 4, 9 UNION ALL
  SELECT 6, 7 UNION ALL
  SELECT 7, 2 UNION ALL
  SELECT 8, 2 UNION ALL
  SELECT 9, 2
)
SELECT
  i_min, i_max, SUM(x) AS  sum_x
FROM (SELECT i_min, i_max, ROW_NUMBER() OVER() AS line FROM intervals) AS intervals
JOIN (SELECT i, x FROM values UNION ALL SELECT NULL, 0) AS values
ON values.i BETWEEN intervals.i_min AND intervals.i_max OR values.i IS NULL
GROUP BY i_min, i_max, line
-- ORDER BY i_min
</code>```

Body:
Suppose I have two tables: intervals contains index intervals (its columns are i_min and i_max) and values contains indexed values (with columns i and x). Here's an example:

 values:        intervals:
+---+---+   +-------+-------+
| i | x |   | i_min | i_max |
+-------+   +---------------+
| 1 | 1 |   |   1   |   4   |
| 2 | 0 |   |   6   |   6   |
| 3 | 4 |   |   6   |   6   |
| 4 | 9 |   |   6   |   6   |
| 6 | 7 |   |   7   |   9   |
| 7 | 2 |   |  12   |  17   |
| 8 | 2 |   +-------+-------+
| 9 | 2 |
+---+---+

I want to sum the values of x for each interval:

       result:
+-------+-------+-----+
| i_min | i_max | sum |
+---------------------+
|   1   |   4   |  13 | // 1+0+4+9
|   6   |   6   |   7 |
|   6   |   6   |   7 |
|   6   |   6   |   7 |
|   7   |   9   |   6 | // 2+2+2
|  12   |  17   |   0 |
+-------+-------+-----+

In some SQL engines, this could be done using:

SELECT
  i_min,
  i_max,
  (SELECT SUM(x)
   FROM values
   WHERE i BETWEEN intervals.i_min AND intervals.i_max) AS sum_x
FROM
  intervals

except that type of query is not allowed by BigQuery ("Subselect not allowed in SELECT clause." or "LEFT OUTER JOIN cannot be used without a condition that is an equality of fields from both sides of the join." depending on the syntax used).

There must be a way to do this with window functions, but I can't figure out how — all examples I've seen have the partition as part of the table. Is there an option that doesn't use CROSS JOIN? If not, what's the most efficient way to do this CROSS JOIN?

Some notes on my data:

Both tables contain many (10⁸-10⁹) rows.

There might be repetitions in intervals, not in i.

But two intervals in intervals are either the same, either entirely disjoint (no overlaps).

The union of all intervals is typically close to the set of all values of i (so it forms a partition of this space).

Intervals might be large (say, i_max-i_min < 10⁶).

Body:
Try below - BigQuery Standard SQL

#standardSQL
SELECT
  i_min, i_max, SUM(x) AS  sum_x
FROM (
  SELECT i_min, i_max, ROW_NUMBER() OVER() AS line FROM `project.dataset.intervals`
) AS intervals
JOIN (SELECT i, x FROM `project.dataset.values` UNION ALL SELECT NULL, 0) AS values
ON values.i BETWEEN intervals.i_min AND intervals.i_max OR values.i IS NULL
GROUP BY i_min, i_max, line
-- ORDER BY i_min

you can play/test with dummy data as below

#standardSQL
WITH intervals AS (
  SELECT  1 AS i_min, 4 AS i_max UNION ALL
  SELECT  6, 6 UNION ALL
  SELECT  6, 6 UNION ALL
  SELECT  6, 6 UNION ALL
  SELECT  7, 9 UNION ALL
  SELECT 12, 17
),
values AS (
  SELECT 1 AS i, 1 AS x UNION ALL
  SELECT 2, 0 UNION ALL
  SELECT 3, 4 UNION ALL
  SELECT 4, 9 UNION ALL
  SELECT 6, 7 UNION ALL
  SELECT 7, 2 UNION ALL
  SELECT 8, 2 UNION ALL
  SELECT 9, 2
)
SELECT
  i_min, i_max, SUM(x) AS  sum_x
FROM (SELECT i_min, i_max, ROW_NUMBER() OVER() AS line FROM intervals) AS intervals
JOIN (SELECT i, x FROM values UNION ALL SELECT NULL, 0) AS values
ON values.i BETWEEN intervals.i_min AND intervals.i_max OR values.i IS NULL
GROUP BY i_min, i_max, line
-- ORDER BY i_min