问:
HTML Table, vertical scroll of a table body prevents horizontal scrolling of a wrapper div
I was trying to build a simple fixed-width html table, with a scrollable body. On mobiles, I wanted it to preserve the width and to overflow with scrolling.

Here's the bin http://output.jsbin.com/hefuzeleza (open it on mobile phone or tablet, in a browser simulation it works fine).

Anyway the code I have looks like this:

```<code>div.wrapper // width: 1060px; overflow-x: auto
  table
    thead
    tbody // height: 300px; overflow-y: auto;
</code>```

My intent is pretty staightforward, the table should be scrollable in both axes. It works on desktop just like that. But on mobile it doesn't allow the horizontall scroll by dragging on the table body (where overflow-x is set).

I'm assuming the problem is that I cannot move the body horizontally, because the vertical scroll exist and the "touch" mobile event doesn't propagates any further (can't reach the wrapper with X scroll).

I've tried putting z-indexes and changing overflow-y/x to unset on elements. No result so far, I wonder if there's any other workarounds.

Thanks in advance.

答:
Add the following css line to your div that needs horizontal scroll:

```<code>-webkit-overflow-scrolling: touch;
</code>```

I tested on Android and it works. On iOS it's not working. The above setting should do the trick.

Body:
I was trying to build a simple fixed-width html table, with a scrollable body. On mobiles, I wanted it to preserve the width and to overflow with scrolling.

Here's the bin http://output.jsbin.com/hefuzeleza (open it on mobile phone or tablet, in a browser simulation it works fine).

Anyway the code I have looks like this:

div.wrapper // width: 1060px; overflow-x: auto
  table
    thead
    tbody // height: 300px; overflow-y: auto;

My intent is pretty staightforward, the table should be scrollable in both axes. It works on desktop just like that. But on mobile it doesn't allow the horizontall scroll by dragging on the table body (where overflow-x is set).

I'm assuming the problem is that I cannot move the body horizontally, because the vertical scroll exist and the "touch" mobile event doesn't propagates any further (can't reach the wrapper with X scroll).

I've tried putting z-indexes and changing overflow-y/x to unset on elements. No result so far, I wonder if there's any other workarounds.

Thanks in advance.

Body:
Add the following css line to your div that needs horizontal scroll:

-webkit-overflow-scrolling: touch;

I tested on Android and it works. On iOS it's not working. The above setting should do the trick.


来源: stackexchange

问:
Logging output running django tests under Pycharm
When running/debugging individual tests using django.test.TestCase under PyCharm logging.logger messages are not shown. I've tried setting logging.basicConfig(level=logging.DEBUG) as suggested by How can I see log messages when unit testing in PyCharm? but that didn't help either. I suspect it might be django's TestCase setup interferring.

Is there some other way in test setup or runner configuration that I can turn on debug logging for the test run?

The logging I have set up in my settings.py right now is:

```<code>LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'verbose'
        },
        'file': {
            'level': 'DEBUG',
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': '/var/log/em/mcqueen-dev.log',
            'when': 'midnight',
            'formatter': 'verbose',
        },
    },
    'formatters': {
        'verbose': {
            'format': '%(asctime)s.%(msecs).03d - %(process)d - %(thread)d - %(levelname)8s - %(filename)s:%(lineno)d - %(funcName)s - %(message)s'
        },
        'simple': {
            'format': '%(asctime)s - %(levelname)s %(message)s'
        },
    },
    'loggers': {
        'mcqueen_api': {
            'handlers': ['console', 'file'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG')
        },
        'mcqueen_app': {
            'handlers': ['console', 'file'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG')
        },
        'mcqueen_base': {
            'handlers': ['console', 'file'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG')
        },
    },
}
</code>```

答:
When I want to see logs while working on tests for Django project in PyCharm I'm putting this snippet of code in the file with test:

```<code>import logging
logger = logging.getLogger(__name__)
logging.disable(logging.NOTSET)
logger.setLevel(logging.DEBUG)
</code>```

While running Django tests level for disabling logs is set high (to 50), lowering it (as in line #3 in code above) will cause that logs will be displayed (or saved to file - depending on log handler that is in use).

ContentLicense: CC BY-SA 3.0

Body:
When running/debugging individual tests using django.test.TestCase under PyCharm logging.logger messages are not shown. I've tried setting logging.basicConfig(level=logging.DEBUG) as suggested by How can I see log messages when unit testing in PyCharm? but that didn't help either. I suspect it might be django's TestCase setup interferring.

Is there some other way in test setup or runner configuration that I can turn on debug logging for the test run?

The logging I have set up in my settings.py right now is:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'verbose'
        },
        'file': {
            'level': 'DEBUG',
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': '/var/log/em/mcqueen-dev.log',
            'when': 'midnight',
            'formatter': 'verbose',
        },
    },
    'formatters': {
        'verbose': {
            'format': '%(asctime)s.%(msecs).03d - %(process)d - %(thread)d - %(levelname)8s - %(filename)s:%(lineno)d - %(funcName)s - %(message)s'
        },
        'simple': {
            'format': '%(asctime)s - %(levelname)s %(message)s'
        },
    },
    'loggers': {
        'mcqueen_api': {
            'handlers': ['console', 'file'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG')
        },
        'mcqueen_app': {
            'handlers': ['console', 'file'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG')
        },
        'mcqueen_base': {
            'handlers': ['console', 'file'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG')
        },
    },
}

Body:
When I want to see logs while working on tests for Django project in PyCharm I'm putting this snippet of code in the file with test:

import logging
logger = logging.getLogger(__name__)
logging.disable(logging.NOTSET)
logger.setLevel(logging.DEBUG)

While running Django tests level for disabling logs is set high (to 50), lowering it (as in line #3 in code above) will cause that logs will be displayed (or saved to file - depending on log handler that is in use).


问:
Clarification for public key while signing initial transaction
I need clarification from API doc reference,
If I am signing transaction based on legal identity key then it works fine.

If I am signing transaction by generating fresh public key and send it to acceptor then it throws exception - The Initiator of CollectSignatureFlow must have signed the transaction

Here as per below doc, we can use public key of legal identity Or can generate public key for signing transaction

答:
It sounds like your issue is as follows:

When adding the required signers to the commands, you're using your standard identity

When signing the transaction, you're using a fresh public key, which doesn't correspond to the identity listed in the commands

The counterparty can't match your signature with the fresh public key to your standard identity listed as a required signer, and therefore throws a SignaturesMissing exception

Instead of creating a fresh public key manually, you should be use the SwapIdentitiesFlow: https://docs.corda.net/api-identity.html#swapidentitiesflow.


问:
Change input text value in before submitting form
I'm trying to change the value of my input text field before submitting the form using jQuery like this:

```<code><form actions="http://test.com/" method="GET">
 <input name="test" id="autocompleteform" type="text"/>
</form>
<script>
$('#form-customer-attr-new').submit(function(e) {
    var value = $("#autocompleteform").val();
    value = value.substr(0, value.indexOf(' '));
    if (!isNan(value) && !empty(value)) {
        $("#autocompleteform").val(value);
        alert($("#autocompleteform").val());
        return true;
    } else {
        alert("Invalid Postcode");
        return false;
    }
});
</script>
</code>```

when i alert the value of the input file, it's showing the new value, but when the form submitten, the paramether in url still showing the old value of the input, for example:

```<code> old_input_value = "1234 justice spoiler message";
 new_input_value = "1234";
 the_url_after_form_submit_now = "http://test.com?test=1234+justice+spoiler+message";
 the_url_after_form_submit_should_be ="http://test.com?test=1234";
</code>```

答:
Submit API for jQuery

The handler will execute as a response to the $('#form-customer-attr-new').submit() (it's a callback function practically), so you will need to move the code from that function to before you do the actual submit.

So move the code right before the jQuery submit() call.

Also, i see that your id is not added to the HTML, please do that as the call will not work otherwise.

Body:
I'm trying to change the value of my input text field before submitting the form using jQuery like this:

<form actions="http://test.com/" method="GET">
 <input name="test" id="autocompleteform" type="text"/>
</form>

when i alert the value of the input file, it's showing the new value, but when the form submitten, the paramether in url still showing the old value of the input, for example:

 old_input_value = "1234 justice spoiler message";
 new_input_value = "1234";
 the_url_after_form_submit_now = "http://test.com?test=1234+justice+spoiler+message";
 the_url_after_form_submit_should_be ="http://test.com?test=1234";


问:
Undefined reference to vtable. Trying to compile a Qt project
I'm using Code::Blocks 8.02 and the mingw 5.1.6 compiler. I'm getting this error when I compile my Qt project:

C:\Documents and Settings\The
  Fuzz\Desktop\GUI\App_interface.cpp|33|undefined
  reference to `vtable for AddressBook'

File AddressBook.h:

```<code> #ifndef ADDRESSBOOK_H
 #define ADDRESSBOOK_H

 #include <QWidget>

 class QLabel;
 class QLineEdit;
 class QTextEdit;

 class AddressBook : public QWidget
 {
     Q_OBJECT

 public:
     AddressBook(QWidget *parent = 0);

 private:
     QLineEdit *nameLine;
     QTextEdit *addressText;
 };

 #endif
</code>```

File AddressBook.cpp:

```<code>#include <QtGui>
#include "addressbook.h"

AddressBook::AddressBook(QWidget *parent)
     : QWidget(parent)
{
    QLabel *nameLabel = new QLabel(tr("Name:"));
    nameLine = new QLineEdit;

    QLabel *addressLabel = new QLabel(tr("Address:"));
    addressText = new QTextEdit;

    QGridLayout *mainLayout = new QGridLayout;
    mainLayout->addWidget(nameLabel, 0, 0);
    mainLayout->addWidget(nameLine, 0, 1);
    mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop);
    mainLayout->addWidget(addressText, 1, 1);

    setLayout(mainLayout);
    setWindowTitle(tr("Simple Address Book"));
}
</code>```

答:
For CMake projects, set CMAKE_AUTOMOC to ON, this fixed my problem.</p>

```<code>#Find includes in corresponding build directories
set(CMAKE_INCLUDE_CURRENT_DIR ON)

# Instruct CMake to run moc automatically when needed.
set(CMAKE_AUTOMOC ON)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm using Code::Blocks 8.02 and the mingw 5.1.6 compiler. I'm getting this error when I compile my Qt project:

C:\Documents and Settings\The
  Fuzz\Desktop\GUI\App_interface.cpp|33|undefined
  reference to `vtable for AddressBook'

File AddressBook.h:

 #ifndef ADDRESSBOOK_H
 #define ADDRESSBOOK_H

 #include <QWidget>

 class QLabel;
 class QLineEdit;
 class QTextEdit;

 class AddressBook : public QWidget
 {
     Q_OBJECT

 public:
     AddressBook(QWidget *parent = 0);

 private:
     QLineEdit *nameLine;
     QTextEdit *addressText;
 };

 #endif

File AddressBook.cpp:

#include <QtGui>
#include "addressbook.h"

AddressBook::AddressBook(QWidget *parent)
     : QWidget(parent)
{
    QLabel *nameLabel = new QLabel(tr("Name:"));
    nameLine = new QLineEdit;

    QLabel *addressLabel = new QLabel(tr("Address:"));
    addressText = new QTextEdit;

    QGridLayout *mainLayout = new QGridLayout;
    mainLayout->addWidget(nameLabel, 0, 0);
    mainLayout->addWidget(nameLine, 0, 1);
    mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop);
    mainLayout->addWidget(addressText, 1, 1);

    setLayout(mainLayout);
    setWindowTitle(tr("Simple Address Book"));
}

Body:
For CMake projects, set CMAKE_AUTOMOC to ON, this fixed my problem.

#Find includes in corresponding build directories
set(CMAKE_INCLUDE_CURRENT_DIR ON)

# Instruct CMake to run moc automatically when needed.
set(CMAKE_AUTOMOC ON)


问:
JQuery, show an element based on 2 attribute conditions
I was wondering if anyone knew of a way of selecting a DIV based on 2 of its attributes meeting a certain criteria using JQuery?  Say for example I have a variable called 'time', now if data-in and data-out (below) are 'seconds', how would you show the relevant DIV based on the 'time' variable.  Assume all the DIVs below are hidden by CSS to start with.

For example if 'time'=15 it would show slide1 because it's between data-in (10) and data-out (20), and if 'time'=73 it would show slide4 (between data-in 70 and data-out 80).

Here is the code (very basic),

```<code><div id="slide1" data-in="10" data-out="20" name="slide1"></div>
<div id="slide2" data-in="30" data-out="40" name="slide2"></div>
<div id="slide3" data-in="50" data-out="60" name="slide3"></div>
<div id="slide4" data-in="70" data-out="80" name="slide4"></div>
<div id="slide5" data-in="90" data-out="100" name="slide5"></div>
</code>```

Thanks in advance.

答:
You need to find a way to iterate over those elements.  You can add a class, you can use a "starts-with" selector ('[id^=slide]'), or you can use a double attribute selector like this:</p>

```<code>var time = 15;
jQuery('[data-in][data-out]').each(function(index, range){
    var $this = $(this),
        dataIn  = $this.attr('data-in'),
        dataOut = $this.attr('data-out');

    if(dataIn < time && time < dataOut) {
        $this.show();
    }
});
</code>```

Body:
I was wondering if anyone knew of a way of selecting a DIV based on 2 of its attributes meeting a certain criteria using JQuery?  Say for example I have a variable called 'time', now if data-in and data-out (below) are 'seconds', how would you show the relevant DIV based on the 'time' variable.  Assume all the DIVs below are hidden by CSS to start with.

For example if 'time'=15 it would show slide1 because it's between data-in (10) and data-out (20), and if 'time'=73 it would show slide4 (between data-in 70 and data-out 80).

Here is the code (very basic),

Thanks in advance.

Body:
You need to find a way to iterate over those elements.  You can add a class, you can use a "starts-with" selector ('[id^=slide]'), or you can use a double attribute selector like this:

var time = 15;
jQuery('[data-in][data-out]').each(function(index, range){
    var $this = $(this),
        dataIn  = $this.attr('data-in'),
        dataOut = $this.attr('data-out');

    if(dataIn < time && time < dataOut) {
        $this.show();
    }
});


问:
Get all EoL Windows Computer in AD With Powershell
I have to create a script to get all EoL Windows computers in our AD.

This is my Code right now:

```<code>$getad = Get-ADComputer -Filter {
OperatingSystem -like "Windows 10*"
-or
OperatingSystem -like "*Windows Vista*"
-or
OperatingSystem -like "*Windows XP*"
-or
OperatingSystem -like "*95*"
-or
OperatingSystem -like "*94*"
-or
OperatingSystem -like "*Windows 8*"
-or
OperatingSystem -like "*Windows 8.1*"
-or
OperatingSystem -like "*2000 Professional*"
-or
OperatingSystem -like "*2000 Server*"
-or
OperatingSystem -like "*2003*"
-or
OperatingSystem -like "*Windows NT*"
-or
OperatingSystem -like "*Windows 7*"
-and
#Windows8
OperatingSystemVersion -notlike "*6.3.9600*"
-and
#Windows7 SP1
OperatingSystemVersion -notlike "*6.1.7601*"
-and
#Windows10
OperatingSystemVersion -notlike "*16299*"
-and
#Windows10
OperatingSystemVersion -notlike "*14393*"
-and
#Windows10
OperatingSystemVersion -notlike "*15063*"
} -Properties ('Name', 'operatingsystem', 'DistinguishedName',
'description', 'lastlogondate', 'OperatingsystemVersion')
$selectobj = $getad | Select-Object Name, Operatingsystem,
DistinguishedName, Description, Lastlogondate, OperatingSystemVersion
$selectobj
</code>```

The problem: The part with -notlike is not applied. I get computers with the versions I do not want to see.

I need all EoL Computers in one variable so i can work with them.

答:
I added ( and ) and now it works.

```<code> $getad = Get-ADComputer -Filter {(operatingsystem -like "*Windows 10*" -and OperatingSystemVersion -notlike "*16299*" -and OperatingSystemVersion -notlike "*14393*" -and OperatingSystemVersion -notlike "*15063*") -or (operatingsystem -like "*Windows Vista*") -or (operatingsystem -like "*Windows XP*") -or  (operatingsystem -like "*95*") -or (operatingsystem -like "*94*") -or ( operatingsystem -like "*Windows 8*" -and OperatingSystemVersion -notlike "*9600*") -or (operatingsystem -like "*2000 Professional*") -or (operatingsystem -like "*2000 Server*") -or (operatingsystem -like "*2003*") -or (operatingsystem -like "*Windows NT*") -or ( operatingsystem -like "*Windows 7*" -and OperatingSystemVersion -notlike "*7601*")} -Properties ('Name', 'operatingsystem', 'DistinguishedName', 'description', 'lastlogondate', 'OperatingsystemVersion', 'Created', 'Enabled', 'SamAccountName')

 $selectobj = $getad | Select-Object Name, Operatingsystem, DistinguishedName, Description, Lastlogondate, OperatingSystemVersion, Created, Enabled, SamAccountName
</code>```

It works but it isn't nice at all because of its lenght.
Is there any other shorter way?

Body:
I have to create a script to get all EoL Windows computers in our AD.

This is my Code right now:

$getad = Get-ADComputer -Filter {
OperatingSystem -like "Windows 10*"
-or
OperatingSystem -like "*Windows Vista*"
-or
OperatingSystem -like "*Windows XP*"
-or
OperatingSystem -like "*95*"
-or
OperatingSystem -like "*94*"
-or
OperatingSystem -like "*Windows 8*"
-or
OperatingSystem -like "*Windows 8.1*"
-or
OperatingSystem -like "*2000 Professional*"
-or
OperatingSystem -like "*2000 Server*"
-or
OperatingSystem -like "*2003*"
-or
OperatingSystem -like "*Windows NT*"
-or
OperatingSystem -like "*Windows 7*"
-and
#Windows8
OperatingSystemVersion -notlike "*6.3.9600*"
-and
#Windows7 SP1
OperatingSystemVersion -notlike "*6.1.7601*"
-and
#Windows10
OperatingSystemVersion -notlike "*16299*"
-and
#Windows10
OperatingSystemVersion -notlike "*14393*"
-and
#Windows10
OperatingSystemVersion -notlike "*15063*"
} -Properties ('Name', 'operatingsystem', 'DistinguishedName',
'description', 'lastlogondate', 'OperatingsystemVersion')
$selectobj = $getad | Select-Object Name, Operatingsystem,
DistinguishedName, Description, Lastlogondate, OperatingSystemVersion
$selectobj

The problem: The part with -notlike is not applied. I get computers with the versions I do not want to see.

I need all EoL Computers in one variable so i can work with them.

Body:
I added ( and ) and now it works.

 $getad = Get-ADComputer -Filter {(operatingsystem -like "*Windows 10*" -and OperatingSystemVersion -notlike "*16299*" -and OperatingSystemVersion -notlike "*14393*" -and OperatingSystemVersion -notlike "*15063*") -or (operatingsystem -like "*Windows Vista*") -or (operatingsystem -like "*Windows XP*") -or  (operatingsystem -like "*95*") -or (operatingsystem -like "*94*") -or ( operatingsystem -like "*Windows 8*" -and OperatingSystemVersion -notlike "*9600*") -or (operatingsystem -like "*2000 Professional*") -or (operatingsystem -like "*2000 Server*") -or (operatingsystem -like "*2003*") -or (operatingsystem -like "*Windows NT*") -or ( operatingsystem -like "*Windows 7*" -and OperatingSystemVersion -notlike "*7601*")} -Properties ('Name', 'operatingsystem', 'DistinguishedName', 'description', 'lastlogondate', 'OperatingsystemVersion', 'Created', 'Enabled', 'SamAccountName')

 $selectobj = $getad | Select-Object Name, Operatingsystem, DistinguishedName, Description, Lastlogondate, OperatingSystemVersion, Created, Enabled, SamAccountName

It works but it isn't nice at all because of its lenght.
Is there any other shorter way?


问:
Previous value in loop in Numba
I'm looping through an array out of order using an index array (or list), but for one of my calculations, I need the value of the previous point in the array (or list). I need to do this using the noPython mode for performance reasons.

For example:

```<code>ordered_pts = [0, 1, 6, 2, 3, 7, 4, 5, 8, 9, 10, 11]
start = [True, False, False, False, False, False, False, True, False, False, False]

@jit(nogil=True, nopython=True)
def loop_in_order(ordered_pts, start):
    for pt in ordered_pts:
        if start[pt]:
            prev_pt = None
        else:
            prev_pt = ordered_points[ordered_points.index(pt) - 1]
        print pt, prev_pt
</code>```

While this function works when nonjitted, I get a cannot convert native?int64 to Python object error.

Is there an efficient way of getting the previous item in the list while still using noPython mode in numba? Or should I just feed my numba function a list of previous indices in addition to my current ones?

In addition, I'd prefer to keep my data types as arrays if possible. (I know the .index function is for lists, rather than arrays)

答:
index trigg quadratic complexity, where a quasi linear Numpy solution exists :

```<code>def numpy_loop_in_order(ordered_pts,start):
    prev_pt=np.roll(ordered_pts,1)               # roll indices
    prev_pt[np.argsort(ordered_pts)[np.where(start)]] =-1  # see below
    return prev_pt
#[-1,  0,  1,  6,  2, -1,  7,  4,  5,  8,  9, 10]
</code>```

I added a element to start an replace None by -1 because Numpy arrays must be homogeneous. np.argsort find the index of all values in O( n ln(n) ) , np.where determines which values will be set.

Furthermore Numba only accelerate code on np.arrays, not lists. And generally useful only if Numpy tools can't solve the problem. but you can slightly improve your code here since ordered_points as the same elements as range(len(ordered_points)):

```<code>@jit(nogil=True, nopython=True)
def loop_in_order(ordered_pts, start):
    reverse_index = np.empty_like(ordered_pts)
    prev_pt = np.empty_like(ordered_pts)
    prev = -1
    for i,pt in enumerate(ordered_pts):
        reverse_index[pt] = i
        prev_pt[i] = prev
        prev = pt
    for pt,i in enumerate(reverse_index):
        if start[pt]:
            prev_pt[i] = -1
    return prev_pt
</code>```

Tests with 1000 points:

```<code>op=np.arange(1000)
np.random.shuffle(op)
ordered_pts=list(op)
start=np.random.randint(0,2,1000,dtype=bool)

In [614]: %timeit loop_in_order(ordered_pts,start)
9.52 ms ± 279 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [615]: %timeit numpy_loop_in_order(op,start)
43.6 µs ± 2.2 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [616]: %timeit numba_loop_in_order(op,start)
4.73 µs ± 179 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code>```

The main improvement is due to the abandonment of index.

Title: Previous value in loop in Numba

Body:
I'm looping through an array out of order using an index array (or list), but for one of my calculations, I need the value of the previous point in the array (or list). I need to do this using the noPython mode for performance reasons.

For example:

ordered_pts = [0, 1, 6, 2, 3, 7, 4, 5, 8, 9, 10, 11]
start = [True, False, False, False, False, False, False, True, False, False, False]

@jit(nogil=True, nopython=True)
def loop_in_order(ordered_pts, start):
    for pt in ordered_pts:
        if start[pt]:
            prev_pt = None
        else:
            prev_pt = ordered_points[ordered_points.index(pt) - 1]
        print pt, prev_pt

While this function works when nonjitted, I get a cannot convert native?int64 to Python object error.

Is there an efficient way of getting the previous item in the list while still using noPython mode in numba? Or should I just feed my numba function a list of previous indices in addition to my current ones?

In addition, I'd prefer to keep my data types as arrays if possible. (I know the .index function is for lists, rather than arrays)

Body:
index trigg quadratic complexity, where a quasi linear Numpy solution exists :

def numpy_loop_in_order(ordered_pts,start):
    prev_pt=np.roll(ordered_pts,1)               # roll indices
    prev_pt[np.argsort(ordered_pts)[np.where(start)]] =-1  # see below
    return prev_pt
#[-1,  0,  1,  6,  2, -1,  7,  4,  5,  8,  9, 10]

I added a element to start an replace None by -1 because Numpy arrays must be homogeneous. np.argsort find the index of all values in O( n ln(n) ) , np.where determines which values will be set.

Furthermore Numba only accelerate code on np.arrays, not lists. And generally useful only if Numpy tools can't solve the problem. but you can slightly improve your code here since ordered_points as the same elements as range(len(ordered_points)):

@jit(nogil=True, nopython=True)
def loop_in_order(ordered_pts, start):
    reverse_index = np.empty_like(ordered_pts)
    prev_pt = np.empty_like(ordered_pts)
    prev = -1
    for i,pt in enumerate(ordered_pts):
        reverse_index[pt] = i
        prev_pt[i] = prev
        prev = pt
    for pt,i in enumerate(reverse_index):
        if start[pt]:
            prev_pt[i] = -1
    return prev_pt

Tests with 1000 points:

op=np.arange(1000)
np.random.shuffle(op)
ordered_pts=list(op)
start=np.random.randint(0,2,1000,dtype=bool)

In [614]: %timeit loop_in_order(ordered_pts,start)
9.52 ms ± 279 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [615]: %timeit numpy_loop_in_order(op,start)
43.6 µs ± 2.2 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [616]: %timeit numba_loop_in_order(op,start)
4.73 µs ± 179 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

The main improvement is due to the abandonment of index.


问:
Sort a dictionary by a custom order
This refers to

Sort a list by a custom order

I will go for a similar example... I have a dictionary containing users

```<code>public class UserInfo
{
    public string Name { get; set; }

    public string Location { get; set; }
}
</code>```

the data:

```<code>private Dictionary<string, UserInfo> users = new Dictionary<string, UserInfo>(); // id + user
</code>```

and a list of possible locations

```<code>        private string[] locations = {
            "europe",
            "america",
            "asia",
            "africa"
        };
</code>```

how can I order this dictionary by these locations?

There should be the output

// ... all europeans

// ... all americans

// ... all asians

// ... all africans

when calling

```<code>    Dictionary<string, UserInfo> sortedUsers = ; // Sorting the dict "users" by locations

    foreach (KeyValuePair<string, UserInfo> info in sortedUsers)
    {
        Console.WriteLine("L: " + info.Value.Location + " N: " + info.Value.Name);
    }
</code>```

答:
A dictionary isn't an ordered collection, but it seems you want it's Values to be ordered:

```<code>var orderedUsersByLocation = users.Values.OrderBy(ui => ui.Location);
</code>```

If you want a List<UserInfo> use ToList:

```<code>List<UserInfo> result = orderedUsersByLocation.ToList();
</code>```

Maybe i didn't get the meaning of the string[] of possible locations, do you mean this array specifies the order and those locations are the possible locations in the UserInfo.Location?

```<code>private string[] locations = {
        "europe",
        "america",
        "asia",
        "africa"
    };

var orderedUsersByLocation = users.Values
    .OrderBy(ui => Array.IndexOf(locations, ui.Location));
</code>```

If it's possible that a location is not contained in that array Array.IndexOf returns -1, so those entries will be first. If that's possible and you want them to be listed last:

```<code>var orderedUsersByLocation = users.Values
    .Select(ui => new { UserInfo = ui, Index = Array.IndexOf(locations, ui.Location)})
    .OrderBy(x => x.Index == - 1 ? int.MaxValue : x.Index)
    .Select(x => x.UserInfo);
</code>```

Title: Sort a dictionary by a custom order

Body:
This refers to

Sort a list by a custom order

I will go for a similar example... I have a dictionary containing users

public class UserInfo
{
    public string Name { get; set; }

    public string Location { get; set; }
}

the data:

private Dictionary<string, UserInfo> users = new Dictionary<string, UserInfo>(); // id + user

and a list of possible locations

        private string[] locations = {
            "europe",
            "america",
            "asia",
            "africa"
        };

how can I order this dictionary by these locations?

There should be the output

// ... all europeans

// ... all americans

// ... all asians

// ... all africans

when calling

    Dictionary<string, UserInfo> sortedUsers = ; // Sorting the dict "users" by locations

    foreach (KeyValuePair<string, UserInfo> info in sortedUsers)
    {
        Console.WriteLine("L: " + info.Value.Location + " N: " + info.Value.Name);
    }

Body:
A dictionary isn't an ordered collection, but it seems you want it's Values to be ordered:

var orderedUsersByLocation = users.Values.OrderBy(ui => ui.Location);

If you want a List<UserInfo> use ToList:

List<UserInfo> result = orderedUsersByLocation.ToList();

Maybe i didn't get the meaning of the string[] of possible locations, do you mean this array specifies the order and those locations are the possible locations in the UserInfo.Location?

private string[] locations = {
        "europe",
        "america",
        "asia",
        "africa"
    };

var orderedUsersByLocation = users.Values
    .OrderBy(ui => Array.IndexOf(locations, ui.Location));

If it's possible that a location is not contained in that array Array.IndexOf returns -1, so those entries will be first. If that's possible and you want them to be listed last:

var orderedUsersByLocation = users.Values
    .Select(ui => new { UserInfo = ui, Index = Array.IndexOf(locations, ui.Location)})
    .OrderBy(x => x.Index == - 1 ? int.MaxValue : x.Index)
    .Select(x => x.UserInfo);


问:
How to enable php intl
I'm on Ubuntu 17.10
PHP Version: 7.1

I already tried this:

```<code>sudo apt-get install php7.1-intl
sudo service apache2 restart
</code>```

But when I var_dump extension_loaded('intl') it returns false. How can I enable this mod?

答:
on the console enter:

```<code>sudo phpenmod intl
</code>```

and the restart the apache webserver:

```<code>sudo service apache2 restart
</code>```

Title: How to enable php intl

Body:
I'm on Ubuntu 17.10
PHP Version: 7.1

I already tried this:

sudo apt-get install php7.1-intl
sudo service apache2 restart

But when I var_dump extension_loaded('intl') it returns false. How can I enable this mod?

Body:
on the console enter:

sudo phpenmod intl

and the restart the apache webserver:

sudo service apache2 restart


答:
You don't sort a dictionary, you get its values as a list and sort the values based on your criteria, which incidentally would be easiest to do if the criteria were a dictionary:</p>

```<code>Dictionary<string,int> locations = new Dictionary<string,int>();
locations["europe"] = 0;
locations["america"] = 1;
locations["asia"] = 2;
locations["africa"] = 3;

//formatted to fit in SO without scrolling
var sortedUsers =
  users.Values.OrderBy(
    u => locations.ContainsKey(u.Location) ? locations[u.Location] : 999999
  );

foreach (UserInfo info in sortedUsers)
{
    Console.WriteLine("L: " + info.Value.Location + " N: " + info.Value.Name);
}
</code>```

Title: Sort a dictionary by a custom order

Body:
You don't sort a dictionary, you get its values as a list and sort the values based on your criteria, which incidentally would be easiest to do if the criteria were a dictionary:

Dictionary<string,int> locations = new Dictionary<string,int>();
locations["europe"] = 0;
locations["america"] = 1;
locations["asia"] = 2;
locations["africa"] = 3;

//formatted to fit in SO without scrolling
var sortedUsers =
  users.Values.OrderBy(
    u => locations.ContainsKey(u.Location) ? locations[u.Location] : 999999
  );

foreach (UserInfo info in sortedUsers)
{
    Console.WriteLine("L: " + info.Value.Location + " N: " + info.Value.Name);
}


问:
C# Nullable Equality Operations, Why does null <= null resolve as false?
Why is it that in .NET

```<code>null >= null
</code>```

resolves as false, but

```<code>null == null
</code>```

resolves as true?

In other words, why isn't null >= null equivalent to null > null || null == null?

Does anyone have the official answer?

答:
They seem to be mixing paradigms from C and SQL.

In the context of nullable variables, null == null should really yield false since equality makes no sense if neither value is known, however doing that for C# as a whole would cause issues when comparing references.

Body:
Why is it that in .NET

null >= null

resolves as false, but

null == null

resolves as true?

In other words, why isn't null >= null equivalent to null > null || null == null?

Does anyone have the official answer?


问:
how to produce a 48-bit number on a 32-bit system
The task is to send out to the network the little-endian bytes that represent the number of miliseconds since the UNIX epoch --- using a 32-bit system.

The number 1510747673476 represents the current date, 2017 november 15th.  In a 32-bit system, the system can't think of this number.  It also doesn't have a source of miliseconds since the UNIX epoch.  But it does have a source of the number of seconds.  It is acceptable that we produce 48-bit numbers whose miliseconds are always zero.

Say y = 1510747673 is the number of seconds since the UNIX epoch of the current date.  Is there a way to format 1510747673 * 10^3 instead?  Meaning I'd get the bytes for the number 1510747673 and somehow discover which other two bytes I need to compose the little endian bytes of 1510747673 * 10^3?  That's the question.

Feel free to ask a better question.  The objective is to deliver the 6 bytes of the current date in miliseconds.  The receiving end expects it in little-endian and with a 48-bit size.

答:
You have the number of seconds y, which fits into a 32-bit datatype.  You want to format y + 10^3 in little-endian.  So you need the two little-endian bytes that represent 10^3.  These are 0xe8 and 0x03.

So take your library that formats 32-bit integers and get the 4 bytes that represents y.  These will be the 4 most significant bytes of your 48-bit integer.  Call them b3, b4, b5, b6.  The desired little-endian answer is 0xe8, 0x03, b3, b4, b5, b6.


问:
There is insufficient space in the filegroup to complete the emptyfile operation
I am in the process of migrating one of the databases that has multiple filegroups into Azure Sql Server. Azure does not seem to support multiple file groups yet according to DMA(Data Migration Assistant).

Now I would like to merge filegroups back into single file.

By searching on internet I found out the following commands to shrink the filegroup to empty the filegroup. Which I believe just merge the content into Primary filegroup and then the filegroup can be removed.

```<code>DBCC SHRINKFILE ('ndfFile', EMPTYFILE);
GO
ALTER DATABASE myDb REMOVE file ndfFile
GO
</code>```

When I run this I get the following error message:

Msg 2556, Level 16, State 1, Line 2

There is insufficient space in the filegroup to complete the emptyfile operation.

I have checked the Primary file group file and auto growth is enabled

I have taken a full backup and removed the database and restored the database again but again no success.

I have also tried to create a new database with a single file and tried to use import/export to copy the data into new database. However import/export wizard does only create tables but not referential integrity constraint nor primary key etc.

When I create the objects by using Generate Scripts feature to create all objects then I cannot copy the data even the "Insert Identity" option is selected.

Question 1: Is there any way that I can restore  MyDb.bak backup file into a single file (and log file)?

Question 2: Is there any way to merge filegroups into single file?

答:
You need to move existing data from the other filegroup(s) to the primary filegroup using WITH(DROP_EXISTING=ON) as explained in this article.

After that you can remove the filegroup with an ALTER DATABASE statement.

```<code>ALTER DATABASE [DB1] REMOVE FILEGROUP [fg_Secondary]
</code>```

At the end you will be able to migrate your database to Azure SQL Database.

Body:
I am in the process of migrating one of the databases that has multiple filegroups into Azure Sql Server. Azure does not seem to support multiple file groups yet according to DMA(Data Migration Assistant).

Now I would like to merge filegroups back into single file.

By searching on internet I found out the following commands to shrink the filegroup to empty the filegroup. Which I believe just merge the content into Primary filegroup and then the filegroup can be removed.

DBCC SHRINKFILE ('ndfFile', EMPTYFILE);
GO
ALTER DATABASE myDb REMOVE file ndfFile
GO

When I run this I get the following error message:

Msg 2556, Level 16, State 1, Line 2

There is insufficient space in the filegroup to complete the emptyfile operation.

I have checked the Primary file group file and auto growth is enabled

I have taken a full backup and removed the database and restored the database again but again no success.

I have also tried to create a new database with a single file and tried to use import/export to copy the data into new database. However import/export wizard does only create tables but not referential integrity constraint nor primary key etc.

When I create the objects by using Generate Scripts feature to create all objects then I cannot copy the data even the "Insert Identity" option is selected.

Question 1: Is there any way that I can restore  MyDb.bak backup file into a single file (and log file)?

Question 2: Is there any way to merge filegroups into single file?

Body:
You need to move existing data from the other filegroup(s) to the primary filegroup using WITH(DROP_EXISTING=ON) as explained in this article.

After that you can remove the filegroup with an ALTER DATABASE statement.

ALTER DATABASE [DB1] REMOVE FILEGROUP [fg_Secondary]

At the end you will be able to migrate your database to Azure SQL Database.


问:
Mock setup returning null when the method is called using await
I'm trying to unit test an action in an MVC controller but the mocked object is returning null.

I have a ClientProxy interface

```<code>public interface IClientProxy
{
    Task<T> Get<T>(string uri);
}
</code>```

With the following concrete implementation

```<code>public async Task<T> Get<T>(string uri)
{
    using (HttpClient httpClient = new HttpClient())
    {
        ConfigureClient(httpClient);
        var response = await httpClient.GetAsync(uri);
        response.EnsureSuccessStatusCode();
        return await Task.Run(() => GetResultFromResponse<T>(response));
    }
}
</code>```

This is my action

```<code>public async Task<ActionResult> Index()
{
    var categories = await _proxy.Get<PagedResults<Category>>("/category/get");
    return View("index", null, JsonConvert.SerializeObject(categories));
}
</code>```

And this is the unit test class

```<code>public class CategoryControllerTests
{
    private readonly CategoryController _controller;
    private readonly Mock<IClientProxy> _mockProxy;

    public CategoryControllerTests()
    {
        _mockProxy = new Mock<IClientProxy>();
        _controller = new CategoryController(_mockProxy.Object);
    }

    [Fact]
    public async Task IndexPageRenders()
    {
        // Arrange
        var fakeResult = new PagedResults<Category>
        {
            Paging = new Paging
            {
                Page = 1,
                PageSize = 10,
                TotalRecords = 2
            },
            Results = new List<Category>
            {
                new Category { CategoryId = 1, Name = "Category One" },
                new Category { CategoryId = 2, Name = "Category Two" }
            }
        };

        var result = JsonConvert.SerializeObject(fakeResult);

        _mockProxy.Setup(p => p.Get<PagedResults<Category>>(It.IsAny<string>())).ReturnsAsync(fakeResult);

        // Act
        var action = await _controller.Index() as ViewResult;

        // Assert
        _mockProxy.Verify(p => p.Get<PagedResults<Category>>(It.IsAny<string>()), Times.Exactly(1));
    }
}
</code>```

Currently the mocked object setup for the get method is not getting hit, and categories are null (the Verify is failing, implying that the mocked method is never called). However, if I remove the await keyword from the action then the categories are returned. I'd rather not remove the await just to pass the test as it's there for a good reason, so any help would be appreciated.

Thanks in advance.

答:
Currently the mocked object setup for the get method is not getting hit, and categories are null (the Verify is failing, implying that the mocked method is never called).

That would mean that the mocked object was not passed as a dependency to the controller being tested and as such is not being invoked when the test is being exercised.

Here is a Minimal, Complete, and Verifiable example that demonstrates how one would setup and exercise a test in such a scenario.

The follow were used

```<code>public class MyModel {
    public int MyIntProperty { get; set; }
    public string MyStringProperty { get; set; }
}

public interface IClientProxy {
    Task<T> Get<T>(string uri);
}

public class MyController : Controller {
    IClientProxy _proxy;

    public MyController(IClientProxy _proxy) {
        this._proxy = _proxy;
    }

    public async Task<ActionResult> Index() {
        var categories = await _proxy.Get<MyModel>("/category/get");
        return View(categories);
    }
}
</code>```

And following test was used with MSTest, Moq and Fluent Assertions where is flowed to completion and passed.

```<code>[TestClass]
public class MyController_Should {
    [TestMethod]
    public async Task _Render_Index_Page() {
        // Arrange
        var fakeResult = new MyModel {
            MyIntProperty = 0,
            MyStringProperty = "Hello World."
        };

        var _mockProxy = new Mock<IClientProxy>();
        _mockProxy
            .Setup(_ => _.Get<MyModel>(It.IsAny<string>()))
            .ReturnsAsync(fakeResult);

        var _controller = new MyController(_mockProxy.Object);

        // Act
        var action = await _controller.Index() as ViewResult;

        // Assert
        _mockProxy.Verify(_ => _.Get<MyModel>(It.IsAny<string>()), Times.Exactly(1));

        action.Should().NotBeNull();

        var model = action.Model;
        model.Should().NotBeNull()
            .And.BeOfType<MyModel>()
            .And.Be(fakeResult);
    }
}
</code>```

I would suggest reviewing this example and then comparing it to how you designed your test to see if you can identify what may be causing your problem.

Body:
I'm trying to unit test an action in an MVC controller but the mocked object is returning null.

I have a ClientProxy interface

public interface IClientProxy
{
    Task<T> Get<T>(string uri);
}

With the following concrete implementation

public async Task<T> Get<T>(string uri)
{
    using (HttpClient httpClient = new HttpClient())
    {
        ConfigureClient(httpClient);
        var response = await httpClient.GetAsync(uri);
        response.EnsureSuccessStatusCode();
        return await Task.Run(() => GetResultFromResponse<T>(response));
    }
}

This is my action

public async Task<ActionResult> Index()
{
    var categories = await _proxy.Get<PagedResults<Category>>("/category/get");
    return View("index", null, JsonConvert.SerializeObject(categories));
}

And this is the unit test class

public class CategoryControllerTests
{
    private readonly CategoryController _controller;
    private readonly Mock<IClientProxy> _mockProxy;

    public CategoryControllerTests()
    {
        _mockProxy = new Mock<IClientProxy>();
        _controller = new CategoryController(_mockProxy.Object);
    }

    [Fact]
    public async Task IndexPageRenders()
    {
        // Arrange
        var fakeResult = new PagedResults<Category>
        {
            Paging = new Paging
            {
                Page = 1,
                PageSize = 10,
                TotalRecords = 2
            },
            Results = new List<Category>
            {
                new Category { CategoryId = 1, Name = "Category One" },
                new Category { CategoryId = 2, Name = "Category Two" }
            }
        };

        var result = JsonConvert.SerializeObject(fakeResult);

        _mockProxy.Setup(p => p.Get<PagedResults<Category>>(It.IsAny<string>())).ReturnsAsync(fakeResult);

        // Act
        var action = await _controller.Index() as ViewResult;

        // Assert
        _mockProxy.Verify(p => p.Get<PagedResults<Category>>(It.IsAny<string>()), Times.Exactly(1));
    }
}

Currently the mocked object setup for the get method is not getting hit, and categories are null (the Verify is failing, implying that the mocked method is never called). However, if I remove the await keyword from the action then the categories are returned. I'd rather not remove the await just to pass the test as it's there for a good reason, so any help would be appreciated.

Thanks in advance.

Body:
Currently the mocked object setup for the get method is not getting hit, and categories are null (the Verify is failing, implying that the mocked method is never called).

That would mean that the mocked object was not passed as a dependency to the controller being tested and as such is not being invoked when the test is being exercised.

Here is a Minimal, Complete, and Verifiable example that demonstrates how one would setup and exercise a test in such a scenario.

The follow were used

public class MyModel {
    public int MyIntProperty { get; set; }
    public string MyStringProperty { get; set; }
}

public interface IClientProxy {
    Task<T> Get<T>(string uri);
}

public class MyController : Controller {
    IClientProxy _proxy;

    public MyController(IClientProxy _proxy) {
        this._proxy = _proxy;
    }

    public async Task<ActionResult> Index() {
        var categories = await _proxy.Get<MyModel>("/category/get");
        return View(categories);
    }
}

And following test was used with MSTest, Moq and Fluent Assertions where is flowed to completion and passed.

[TestClass]
public class MyController_Should {
    [TestMethod]
    public async Task _Render_Index_Page() {
        // Arrange
        var fakeResult = new MyModel {
            MyIntProperty = 0,
            MyStringProperty = "Hello World."
        };

        var _mockProxy = new Mock<IClientProxy>();
        _mockProxy
            .Setup(_ => _.Get<MyModel>(It.IsAny<string>()))
            .ReturnsAsync(fakeResult);

        var _controller = new MyController(_mockProxy.Object);

        // Act
        var action = await _controller.Index() as ViewResult;

        // Assert
        _mockProxy.Verify(_ => _.Get<MyModel>(It.IsAny<string>()), Times.Exactly(1));

        action.Should().NotBeNull();

        var model = action.Model;
        model.Should().NotBeNull()
            .And.BeOfType<MyModel>()
            .And.Be(fakeResult);
    }
}

I would suggest reviewing this example and then comparing it to how you designed your test to see if you can identify what may be causing your problem.


问:
NLTK SklearnClassifier wrapper data
I was trying to to make a sklearn classifier within the nltk.SklearnClassifier wrapper and came across this question that if we don't train the classifier at once (which all of the tutorials out there do) and train it one data at a time, will it delete destroy the previous training done to the classifier . I hope I made myself clear but if not here is some code to explain.

```<code>from nltk.classify.scikitlearn import SklearnClassifier
from sklearn.naive_bayes import MultinomialNB

class classifier(object):
    def __init__(self,c):
        self.c = c

    def train(self,featuresets):
        self.c.train(featuresets)

    def classify(self,feature):
        self.c.classify(feature)

clf = classifier(SklearnClassifier(MultinomialNB()))
while True:
    #some lengthy operation
    clf.train(featuresets)
    #some lengthy operation again
    clf.classify(feature)
</code>```

I hope you now understood what I am trying to say. So when the clf gets trained  in the loop then does all the previous training gets useless or not and if it does get useless what are the other ways to achieve the same? thanks in advance.

答:
Everything depends on classifier you're using. Not all sci-kit classifiers are able to learn multiple times.

If you want to train it multiple times set warm_start = True when initializing your classifier object.

MultinomialNB doesn't have possibility to be trained multiple times. i.e. http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html is able to do this.

Nevertheless firstly it's good to think whether you really need to train it multiple times. Incremental learning is used usually when your data overcaps your viable memory.

```<code>warm_start : bool, default: False

When set to True, reuse the solution of the previous call to fit as initialization,
otherwise, just erase the previous solution. Useless for liblinear solver.
</code>```

Title: NLTK SklearnClassifier wrapper data

Body:
I was trying to to make a sklearn classifier within the nltk.SklearnClassifier wrapper and came across this question that if we don't train the classifier at once (which all of the tutorials out there do) and train it one data at a time, will it delete destroy the previous training done to the classifier . I hope I made myself clear but if not here is some code to explain.

from nltk.classify.scikitlearn import SklearnClassifier
from sklearn.naive_bayes import MultinomialNB

class classifier(object):
    def __init__(self,c):
        self.c = c

    def train(self,featuresets):
        self.c.train(featuresets)

    def classify(self,feature):
        self.c.classify(feature)

clf = classifier(SklearnClassifier(MultinomialNB()))
while True:
    #some lengthy operation
    clf.train(featuresets)
    #some lengthy operation again
    clf.classify(feature)

I hope you now understood what I am trying to say. So when the clf gets trained  in the loop then does all the previous training gets useless or not and if it does get useless what are the other ways to achieve the same? thanks in advance.

Body:
Everything depends on classifier you're using. Not all sci-kit classifiers are able to learn multiple times.

If you want to train it multiple times set warm_start = True when initializing your classifier object.

MultinomialNB doesn't have possibility to be trained multiple times. i.e. http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html is able to do this.

Nevertheless firstly it's good to think whether you really need to train it multiple times. Incremental learning is used usually when your data overcaps your viable memory.

warm_start : bool, default: False

When set to True, reuse the solution of the previous call to fit as initialization,
otherwise, just erase the previous solution. Useless for liblinear solver.


问:
Generating 'customers also bought' from table
I've got a 'cart' table as follows:

```<code>+----+---------+-----------+----------+----------+
| id | orderID | productID | quantity |  status  |
+----+---------+-----------+----------+----------+
|  1 |    3443 |       333 |        2 | complete |
|  2 |    3443 |       202 |        4 | complete |
+----+---------+-----------+----------+----------+
</code>```

And so foreach order, a new row gets added for each item in the cart.

So I want to get an 'customers also bought' from this table.  I'm using MySQL.

How can I do this? This is what I came up with at first:

```<code>SELECT * FROM `cart` WHERE `status` = 'complete' AND `productID` = '333' ORDER BY `ts` DESC
</code>```

But of course this only shows me the the rows with that productID in.  What I really want is the other products of orders that contain that productID.

How can I go about doing this?

答:
There are already two correct answers.  I'm just trying to give you an idea about the order (or the importance) of productID you show.
You could for example use a query like this, using the number of times a certain productID was bought (other than 'ts'):</p>

```<code>SELECT `productID`, COUNT(*) AS RC
FROM `cart`
WHERE `orderID` IN (SELECT `orderID` FROM `cart` WHERE `productid`=333 AND `status` = 'complete' )
AND `productID` <> '333'
GROUP BY  `productID`
ORDER BY RC DESC
</code>```

Body:
I've got a 'cart' table as follows:

+----+---------+-----------+----------+----------+
| id | orderID | productID | quantity |  status  |
+----+---------+-----------+----------+----------+
|  1 |    3443 |       333 |        2 | complete |
|  2 |    3443 |       202 |        4 | complete |
+----+---------+-----------+----------+----------+

And so foreach order, a new row gets added for each item in the cart.

So I want to get an 'customers also bought' from this table.  I'm using MySQL.

How can I do this? This is what I came up with at first:

SELECT * FROM `cart` WHERE `status` = 'complete' AND `productID` = '333' ORDER BY `ts` DESC

But of course this only shows me the the rows with that productID in.  What I really want is the other products of orders that contain that productID.

How can I go about doing this?

Body:
There are already two correct answers.  I'm just trying to give you an idea about the order (or the importance) of productID you show.
You could for example use a query like this, using the number of times a certain productID was bought (other than 'ts'):

SELECT `productID`, COUNT(*) AS RC
FROM `cart`
WHERE `orderID` IN (SELECT `orderID` FROM `cart` WHERE `productid`=333 AND `status` = 'complete' )
AND `productID` <> '333'
GROUP BY  `productID`
ORDER BY RC DESC


问:
Split string into conditional statements
I haven't been able to find an answer to this anywhere, so here it goes:
I have a pandas dataframe df like this:

```<code>   X  Y name
0  3  1  foo
1  5  2   fa
2  1  3  hoo
3  2  4   ha
</code>```

I can easily find information in df by making conditions (for example df['X' >=3]), which is great. However, I want to make a more generic solution, where I can create a long condition in string form (e.g. '(X >= 3) & (name == foo)'), which could be split into an actual condition, that can be used in a pandas dataframe.
Can anyone suggest a smart solution (if something like this is possible) or redirect me to a similar discussion on the discussion board, where this topic has been debated?

答:
It seems you need query for filtering:

```<code>df = df.query("X >= 3 & name == 'foo'")
</code>```

Body:
I haven't been able to find an answer to this anywhere, so here it goes:
I have a pandas dataframe df like this:

   X  Y name
0  3  1  foo
1  5  2   fa
2  1  3  hoo
3  2  4   ha

I can easily find information in df by making conditions (for example df['X' >=3]), which is great. However, I want to make a more generic solution, where I can create a long condition in string form (e.g. '(X >= 3) & (name == foo)'), which could be split into an actual condition, that can be used in a pandas dataframe.
Can anyone suggest a smart solution (if something like this is possible) or redirect me to a similar discussion on the discussion board, where this topic has been debated?

Body:
It seems you need query for filtering:

df = df.query("X >= 3 & name == 'foo'")


问:
How to get circle hover effect
How can I achieve rounded hover effect like in the attached image (at the right bottom pic)

Here is the fiddle link

Here is the relevant css:

```<code>.box_details {
  float:left;
  width:200px;
  height:200px;
  margin-right:35px;
  background-color:#fff;

  border-radius:3px;
  box-shadow: 0px 6px 19px 16px rgba(239,242,245,1);
}

.box_details:hover {
background-color:#f4f6f8;
color:#939bc5;
}
</code>```

答:
You can make a circle that has a bigger width than its parent element and center it. Check the code snippet for a demonstration of this.

.box_details {
  float: left;
  width: 200px;
  height: 200px;
  margin-right: 35px;
  background-color: #fff;
  display: block;
  position: relative;
  border-radius: 3px;
  box-shadow: 0px 6px 19px 16px rgba(239, 242, 245, 1);
  overflow: hidden;
}

.box_details:hover .circle {
  margin-top: 140px;
  transition-duration: 0.4s;
}

p {
  text-align: center;
}

.circle {
  position: absolute;
  width: 200%;
  height: 100px;
  left: 0;
  right: 0;
  margin: 0 auto;
  background: lightgrey;
  border-radius: 50%;
  margin-left: -50%;
  margin-top: 250px;
  transition-duration: 0.4s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box_details">
  <div class="circle">
    <p>Hi!</p>
  </div>
</div></code>```

Title: How to get circle hover effect

Body:
How can I achieve rounded hover effect like in the attached image (at the right bottom pic)

Here is the fiddle link

Here is the relevant css:

.box_details {
  float:left;
  width:200px;
  height:200px;
  margin-right:35px;
  background-color:#fff;

  border-radius:3px;
  box-shadow: 0px 6px 19px 16px rgba(239,242,245,1);
}

.box_details:hover {
background-color:#f4f6f8;
color:#939bc5;
}

Body:
You can make a circle that has a bigger width than its parent element and center it. Check the code snippet for a demonstration of this.

.box_details {
  float: left;
  width: 200px;
  height: 200px;
  margin-right: 35px;
  background-color: #fff;
  display: block;
  position: relative;
  border-radius: 3px;
  box-shadow: 0px 6px 19px 16px rgba(239, 242, 245, 1);
  overflow: hidden;
}

.box_details:hover .circle {
  margin-top: 140px;
  transition-duration: 0.4s;
}

p {
  text-align: center;
}

.circle {
  position: absolute;
  width: 200%;
  height: 100px;
  left: 0;
  right: 0;
  margin: 0 auto;
  background: lightgrey;
  border-radius: 50%;
  margin-left: -50%;
  margin-top: 250px;
  transition-duration: 0.4s;
}

<div class="box_details">
  <div class="circle">
    <p>Hi!</p>
  </div>
</div>


问:
instantiate an NSArray with integers value
I have a PickerView and I want to initialize it with integer values. For example PickerView with all integers lower than 10.

Thank you

答:
```<code>NSInteger min = 1;
NSInteger max = 10;
NSInteger step = 1;

NSMutableArray<NSNumber *> *options = [NSMutableArray new];

for (NSInteger index = 0; index < ceilf(((float)max)/step); index++)
{
    options[index] = @((index + min) * step);
}

NSLog(@"%@",options);
</code>```

An alternate approach:

```<code>NSInteger from = 1;
NSInteger size = 10;
NSInteger step = 1;

NSMutableArray<NSNumber *> *options = [NSMutableArray new];

for (NSInteger index = 0; index < size; index++)
{
    options[index] = @((index + from) * step);
}

NSLog(@"%@",options);
</code>```

Both of the above print the following:

(
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    10
)

Body:
NSInteger min = 1;
NSInteger max = 10;
NSInteger step = 1;

NSMutableArray<NSNumber *> *options = [NSMutableArray new];

for (NSInteger index = 0; index < ceilf(((float)max)/step); index++)
{
    options[index] = @((index + min) * step);
}

NSLog(@"%@",options);

An alternate approach:

NSInteger from = 1;
NSInteger size = 10;
NSInteger step = 1;

NSMutableArray<NSNumber *> *options = [NSMutableArray new];

for (NSInteger index = 0; index < size; index++)
{
    options[index] = @((index + from) * step);
}

NSLog(@"%@",options);

Both of the above print the following:

(
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    10
)


问:
PHP Securely include files + handle invalid parameters
I'm having a little problem. I want to securely include files based on the $_GET Parameter from a subdirectory + handle if the parameter is not valid.

```<code> <?php
if(isset($_GET['p']) && $_GET['p'] == 'fahrzeuge'){
        include 'includes/cars.php';
    }
  if(isset($_GET['p']) && $_GET['p'] == 'impressum'){
        include 'includes/impressum.php';
    }
    if(isset($_GET['p']) && $_GET['p'] == 'home'){
            include 'includes/home.php';
        }
      if(isset($_GET['p']) && $_GET['p'] == 'anfahrt'){
            include 'includes/anfahrt.php';
        }
        if(isset($_GET['p']) && $_GET['p'] == 'about'){
                include 'includes/about.php';
            }

?>
</code>```

This is my Code. Sorry I know it is a noob way of solving this. How can I improve it? Any Suggestions/Help would be highly appreciated

答:
Set an array of legit pages. Check once if $_GET['p'] is set and if so assign its value (after escaping it) to a variable $p.

Then check if the requested page ($p) is defined in your pages array, if so - include it.

```<code>$pages = array('about','contact','home');

$p = 'home'; //Default page
if(isset($_GET['p'])) {
  $p = $_GET['p']; //no need to escape as we compare it to predefined values as @Yoshi suggested
}

if(in_array($p, $pages)){
  include 'includes/'.$p.'.php';
} else {
   include 'includes/home.php';
}
</code>```

Body:
I'm having a little problem. I want to securely include files based on the $_GET Parameter from a subdirectory + handle if the parameter is not valid.

 <?php
if(isset($_GET['p']) && $_GET['p'] == 'fahrzeuge'){
        include 'includes/cars.php';
    }
  if(isset($_GET['p']) && $_GET['p'] == 'impressum'){
        include 'includes/impressum.php';
    }
    if(isset($_GET['p']) && $_GET['p'] == 'home'){
            include 'includes/home.php';
        }
      if(isset($_GET['p']) && $_GET['p'] == 'anfahrt'){
            include 'includes/anfahrt.php';
        }
        if(isset($_GET['p']) && $_GET['p'] == 'about'){
                include 'includes/about.php';
            }

?>

This is my Code. Sorry I know it is a noob way of solving this. How can I improve it? Any Suggestions/Help would be highly appreciated

Body:
Set an array of legit pages. Check once if $_GET['p'] is set and if so assign its value (after escaping it) to a variable $p.

Then check if the requested page ($p) is defined in your pages array, if so - include it.

$pages = array('about','contact','home');

$p = 'home'; //Default page
if(isset($_GET['p'])) {
  $p = $_GET['p']; //no need to escape as we compare it to predefined values as @Yoshi suggested
}

if(in_array($p, $pages)){
  include 'includes/'.$p.'.php';
} else {
   include 'includes/home.php';
}


问:
HTTP request failed! HTTP/1.1 400 Bad Request
I am trying to create a issue in Jira .

I am able to make a GET request with a proper response, but the problem arises when i make a POST request.Here is the code.

```<code><?php

$userName ='xxxxxxxxxxxxxxxx';
$password ='xxxxxxxxxxxx';

$data = ['fields' => ['projects'=>['key'=>'ABC'],'summary'=>'abc','description'=>'abc','issuetype'=>['name'=>'Task']]];

$data = http_build_query($data);
$context =
     array("http"=>
        array(
            "method" => "POST",
                "header" => "Authorization: Basic " . base64_encode($userName.':'.$password) . "\r\n".
                'Accept: application/json'."\r\n".
                "Content-Length: ".strlen($data)."\r\n".
                    'Content-Type: application/json'."\r\n",
            'content' => $data,
            'verify_peer'=>false,
            'verify_peer_name'=>false,
            )
            );
$context = stream_context_create($context);
$result = file_get_contents("https://xxxxx.atlassian.net/rest/api/2/issue/", false, $context);
echo "The result is ", $result;
</code>```

?>

I get the following error:

```<code>Warning:file_get_contents(https://xxxxx.atlassian.net/rest/api/2/issue/):
failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in
/var/www/html/test/new.php on line 27
</code>```

Could any one help me out? Thanks

P.S

I dont want to use curl as an alternative to http-streams as google app engine does not support curl.

答:
Could you have a typo in your code?

```<code>$data=array('fields' => array ('project' => array ('key' => 'WOIS',),'summary' => 'ABC','description' => 'ABC','issuetype' => array ('name' => 'Task',),),);
</code>```

vs

```<code>$data = ['fields' => ['projects'=>['key'=>'WOIS'],'summary'=>'adfsdf','description'=>'adfefsa','issuetype'=>['name'=>'Task']]];
</code>```

the first line says project while the second line says projects

Body:
I am trying to create a issue in Jira .

I am able to make a GET request with a proper response, but the problem arises when i make a POST request.Here is the code.

<?php

$userName ='xxxxxxxxxxxxxxxx';
$password ='xxxxxxxxxxxx';

$data = ['fields' => ['projects'=>['key'=>'ABC'],'summary'=>'abc','description'=>'abc','issuetype'=>['name'=>'Task']]];

$data = http_build_query($data);
$context =
     array("http"=>
        array(
            "method" => "POST",
                "header" => "Authorization: Basic " . base64_encode($userName.':'.$password) . "\r\n".
                'Accept: application/json'."\r\n".
                "Content-Length: ".strlen($data)."\r\n".
                    'Content-Type: application/json'."\r\n",
            'content' => $data,
            'verify_peer'=>false,
            'verify_peer_name'=>false,
            )
            );
$context = stream_context_create($context);
$result = file_get_contents("https://xxxxx.atlassian.net/rest/api/2/issue/", false, $context);
echo "The result is ", $result;

?>

I get the following error:

Warning:file_get_contents(https://xxxxx.atlassian.net/rest/api/2/issue/):
failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in
/var/www/html/test/new.php on line 27

Could any one help me out? Thanks

P.S

I dont want to use curl as an alternative to http-streams as google app engine does not support curl.

Body:
Could you have a typo in your code?

$data=array('fields' => array ('project' => array ('key' => 'WOIS',),'summary' => 'ABC','description' => 'ABC','issuetype' => array ('name' => 'Task',),),);

vs

$data = ['fields' => ['projects'=>['key'=>'WOIS'],'summary'=>'adfsdf','description'=>'adfefsa','issuetype'=>['name'=>'Task']]];

the first line says project while the second line says projects


问:
How to use Content-Type: Multipart/Related
I want to send a binary file to the user and have some HTML display on the browser.  I'm using a CGI-BIN script with apache2.  I found this example on page 4.  The link also shows details about the multipart/related content-type.  Here's what I tried so far:

```
Content-Type: Multipart/Related; boundary="boundary-content"; start=""; type=\"text/plain\""

--boundary-content
Content-Disposition: inline
Content Type:text/plain
Content-ID: <abc>

hi

--boundary-content
Content Type:application/octet-stream
Content-Disposition: attachment;filename=myfile
Content-ID: 2

...

--boundary-content
```

The whole thing after the first Content-Type line shows up as a single plaintext attachment.  How can I make the browser say hi and prompt to download myfile with contents of ...?

答: i do not think browsers understand multipart MIME responses</p>

Body:
I want to send a binary file to the user and have some HTML display on the browser.  I'm using a CGI-BIN script with apache2.  I found this example on page 4.  The link also shows details about the multipart/related content-type.  Here's what I tried so far:

Content-Type: Multipart/Related; boundary="boundary-content"; start=""; type=\"text/plain\""

--boundary-content
Content-Disposition: inline
Content Type:text/plain
Content-ID: <abc>

hi

--boundary-content
Content Type:application/octet-stream
Content-Disposition: attachment;filename=myfile
Content-ID: 2

...

--boundary-content

The whole thing after the first Content-Type line shows up as a single plaintext attachment.  How can I make the browser say hi and prompt to download myfile with contents of ...?


问:
What's the best way to check if a Firestore record exists if its path is known?
Given a given Firestore path what's the easiest and most elegant way to check if that record exists or not short of creating a document observable and subscribing to it?</p>

答:
Taking a look at this question it looks like .exists can still be used just like with the standard Firebase database. Additionally, you can find some more people talking about this issue on github here

The documentation states

NEW EXAMPLE

```<code>var docRef = db.collection("cities").doc("SF");

docRef.get().then((doc) => {
    if (doc.exists) {
        console.log("Document data:", doc.data());
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
}).catch((error) => {
    console.log("Error getting document:", error);
});
</code>```

OLD EXAMPLE

```<code>const cityRef = db.collection('cities').doc('SF');
const doc = await cityRef.get();

if (!doc.exists) {
    console.log('No such document!');
} else {
    console.log('Document data:', doc.data());
}
</code>```

Note: If there is no document at the location referenced by docRef, the resulting document will be empty and calling exists on it will return false.

OLD EXAMPLE 2

```<code>var cityRef = db.collection('cities').doc('SF');

var getDoc = cityRef.get()
    .then(doc => {
        if (!doc.exists) {
            console.log('No such document!');
        } else {
            console.log('Document data:', doc.data());
        }
    })
    .catch(err => {
        console.log('Error getting document', err);
    });
</code>```

Body:
Taking a look at this question it looks like .exists can still be used just like with the standard Firebase database. Additionally, you can find some more people talking about this issue on github here

The documentation states

NEW EXAMPLE

var docRef = db.collection("cities").doc("SF");

docRef.get().then((doc) => {
    if (doc.exists) {
        console.log("Document data:", doc.data());
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
}).catch((error) => {
    console.log("Error getting document:", error);
});

OLD EXAMPLE

const cityRef = db.collection('cities').doc('SF');
const doc = await cityRef.get();

if (!doc.exists) {
    console.log('No such document!');
} else {
    console.log('Document data:', doc.data());
}

Note: If there is no document at the location referenced by docRef, the resulting document will be empty and calling exists on it will return false.

OLD EXAMPLE 2

var cityRef = db.collection('cities').doc('SF');

var getDoc = cityRef.get()
    .then(doc => {
        if (!doc.exists) {
            console.log('No such document!');
        } else {
            console.log('Document data:', doc.data());
        }
    })
    .catch(err => {
        console.log('Error getting document', err);
    });

ContentLicense: CC BY-SA 4.0


问:
Pass parameter to gradle task
I have multiple tasks. I run a task from command line via : gradle tasks.gradle TaskA -Pparam1=value1 -Pparam2=value2

TaskA calls TaskB via : tasks.TaskB.execute().

How can I pass parameters to this task programatically?

答:
As in this comment, please do not call execute on task directly. Not only it may spoil the task dependency graph but this is also not the case that task action is always mapped to execute method.

To read the properties in the task, use:

```<code>project.findProperty("<PROPERTY_NAME>")
</code>```

It returns null if property is missing or value if it was passed.

Title: Pass parameter to gradle task

Body:
As in this comment, please do not call execute on task directly. Not only it may spoil the task dependency graph but this is also not the case that task action is always mapped to execute method.

To read the properties in the task, use:

project.findProperty("<PROPERTY_NAME>")

It returns null if property is missing or value if it was passed.


问:
filter two dropdown list with jQuery
I have two lists who looks like this.

```<code><select class="form-control" id="arrondissement" required="required" aria-invalid="false" name="arrondissement">
  <option value="1">1er arrondissement</option>
  <option value="2"><span>2ème arrondissement</span></option>
  <option value="3"><span>3ème arrondissement</span></option>
  <option value="4"><span>4ème arrondissement</span></option>
  <option value="5"><span>5ème arrondissement</span></option>
</select>

<select class="form-control classeNomIgh" id="nomIGH" required="required" aria-invalid="false" name="nomIGH">
  <!-- remplacer les valeurs "précodées" ('eiffel', 'montparnasse', 'tgi') par la liste des valeurs renvoyées par l'appel au WebService -->
  <option value="" label="---">---</option>
  <option data-arrondissement="1" value="IGH1">IGH1</option>
  <option data-arrondissement="2" value="IGH2">IGH2</option>
  <option data-arrondissement="3" value="IGH3">IGH3</option>
  <option data-arrondissement="4" value="IGH4">IGH4</option>
  <option data-arrondissement="5" value="IGH5">IGH5</option>
</select>
</code>```

How can i do so that when i select an 'arrondissement' in the first drowdown list, the second will display only those with data-arrondissement with the same value.

答:
This will help you using jquery change event

```<code>$( "#arrondissement" ).change(function() {

    var conceptName = $('#arrondissement').find(":selected").val();
    $("#nomIGH > option").each(function() {
        if(jQuery(this).attr('data-arrondissement') == conceptName){
          $("#nomIGH option[data-arrondissement='"+conceptName+"']").prop('selected', true);
        }
    });
});
</code>```

https://jsfiddle.net/7hgw8h69/

Title: filter two dropdown list with jQuery

Body:
I have two lists who looks like this.

<select class="form-control" id="arrondissement" required="required" aria-invalid="false" name="arrondissement">
  <option value="1">1er arrondissement</option>
  <option value="2">2ème arrondissement</option>
  <option value="3">3ème arrondissement</option>
  <option value="4">4ème arrondissement</option>
  <option value="5">5ème arrondissement</option>
</select>

<select class="form-control classeNomIgh" id="nomIGH" required="required" aria-invalid="false" name="nomIGH">

  <option value="" label="---">---</option>
  <option data-arrondissement="1" value="IGH1">IGH1</option>
  <option data-arrondissement="2" value="IGH2">IGH2</option>
  <option data-arrondissement="3" value="IGH3">IGH3</option>
  <option data-arrondissement="4" value="IGH4">IGH4</option>
  <option data-arrondissement="5" value="IGH5">IGH5</option>
</select>

How can i do so that when i select an 'arrondissement' in the first drowdown list, the second will display only those with data-arrondissement with the same value.

Body:
This will help you using jquery change event

$( "#arrondissement" ).change(function() {

    var conceptName = $('#arrondissement').find(":selected").val();
    $("#nomIGH > option").each(function() {
        if(jQuery(this).attr('data-arrondissement') == conceptName){
          $("#nomIGH option[data-arrondissement='"+conceptName+"']").prop('selected', true);
        }
    });
});

https://jsfiddle.net/7hgw8h69/


问:
Change input text value in before submitting form
I'm trying to change the value of my input text field before submitting the form using jQuery like this:

```<code><form actions="http://test.com/" method="GET">
 <input name="test" id="autocompleteform" type="text"/>
</form>
<script>
$('#form-customer-attr-new').submit(function(e) {
    var value = $("#autocompleteform").val();
    value = value.substr(0, value.indexOf(' '));
    if (!isNan(value) && !empty(value)) {
        $("#autocompleteform").val(value);
        alert($("#autocompleteform").val());
        return true;
    } else {
        alert("Invalid Postcode");
        return false;
    }
});
</script>
</code>```

when i alert the value of the input file, it's showing the new value, but when the form submitten, the paramether in url still showing the old value of the input, for example:

```<code> old_input_value = "1234 justice spoiler message";
 new_input_value = "1234";
 the_url_after_form_submit_now = "http://test.com?test=1234+justice+spoiler+message";
 the_url_after_form_submit_should_be ="http://test.com?test=1234";
</code>```

答:
Couple of things:

id of form was not set, add id="form-customer-attr-new" to form tag

isNan should be isNaN

!empty should be !!

Now it should work. full working example:

```<code><!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no,
initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <script
            src="https://code.jquery.com/jquery-3.2.1.min.js"
            integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
            crossorigin="anonymous"></script>
</head>
<body>
<form actions="http://test.com/" method="GET" id="form-customer-attr-new">
<input name="test" id="autocompleteform" type="text"/>
<input type="submit" />
</form>

<script>
    $('#form-customer-attr-new').submit(function(e) {
    var value = $("#autocompleteform").val();
    value = value.substr(0, value.indexOf(' '));

    if (!isNaN(value) && !!(value)) {
        $("#autocompleteform").val(value);
        alert($("#autocompleteform").val());
        return true;
    } else {
        alert("Invalid Postcode");
        return false;
    }
});

</script>
</body>
</code>```

Body:
I'm trying to change the value of my input text field before submitting the form using jQuery like this:

<form actions="http://test.com/" method="GET">
 <input name="test" id="autocompleteform" type="text"/>
</form>

when i alert the value of the input file, it's showing the new value, but when the form submitten, the paramether in url still showing the old value of the input, for example:

 old_input_value = "1234 justice spoiler message";
 new_input_value = "1234";
 the_url_after_form_submit_now = "http://test.com?test=1234+justice+spoiler+message";
 the_url_after_form_submit_should_be ="http://test.com?test=1234";

Body:
Couple of things:

id of form was not set, add id="form-customer-attr-new" to form tag

isNan should be isNaN

!empty should be !!

Now it should work. full working example:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no,
initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <script
            src="https://code.jquery.com/jquery-3.2.1.min.js"
            integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
            crossorigin="anonymous"></script>
</head>
<body>
<form actions="http://test.com/" method="GET" id="form-customer-attr-new">
<input name="test" id="autocompleteform" type="text"/>
<input type="submit" />
</form>

<script>
    $('#form-customer-attr-new').submit(function(e) {
    var value = $("#autocompleteform").val();
    value = value.substr(0, value.indexOf(' '));

    if (!isNaN(value) && !!(value)) {
        $("#autocompleteform").val(value);
        alert($("#autocompleteform").val());
        return true;
    } else {
        alert("Invalid Postcode");
        return false;
    }
});

</script>
</body>


问:
Working with decimals in Ruby on Rails 3
I'm trying to calculate the average net price of a product. I have, in my Product model :total_sold and :total_net_revenue. Doing straight division in the method seems to always result in 0. I resorted to using BigDecimal as I figured that was the problem ... but with my latest iteration of the code below, I'm still getting zero when the answer comes out to a decimal.

```<code>def avg_price
  BigDecimal(total_sold.to_s) / (BigDecimal(total_net_revenue.to_s) / 100)
end
</code>```

Net revenue is in cents, which is why I divide by 100. Can someone point out what I'm doing wrong or should do?

答:
First: You are dividing the wrong way.

100 items / $150 = .667 items per dollar

vs.

$150 / 100 items = $1.50 per item

Second: Like other languages, you need to force one of the numbers in the equation to be a decimal so that the result is cast as one as well. Since your revenue is a whole number, that meant all three values were whole numbers, which means you got a whole number as a result. To get a decimal, cast one of them as a floating-point number.

In other words, to get what you need, do this:

```<code>price_per_item = (total_net_revenue.to_f / 100) / total_sold
</code>```

Body:
I'm trying to calculate the average net price of a product. I have, in my Product model :total_sold and :total_net_revenue. Doing straight division in the method seems to always result in 0. I resorted to using BigDecimal as I figured that was the problem ... but with my latest iteration of the code below, I'm still getting zero when the answer comes out to a decimal.

def avg_price
  BigDecimal(total_sold.to_s) / (BigDecimal(total_net_revenue.to_s) / 100)
end

Net revenue is in cents, which is why I divide by 100. Can someone point out what I'm doing wrong or should do?

Body:
First: You are dividing the wrong way.

100 items / $150 = .667 items per dollar

vs.

$150 / 100 items = $1.50 per item

Second: Like other languages, you need to force one of the numbers in the equation to be a decimal so that the result is cast as one as well. Since your revenue is a whole number, that meant all three values were whole numbers, which means you got a whole number as a result. To get a decimal, cast one of them as a floating-point number.

In other words, to get what you need, do this:

price_per_item = (total_net_revenue.to_f / 100) / total_sold


问:
Send JavaScript in an HTTP post request
Let's say I have foo.html and there is a text-field where I submit text that is shown afterwards on the site. It is possible to write JavaScript in this text-field. For example  and  works.

What I want to do is to send a JavaScript as message per post request to foo.html. The form has a text-area and its name is "textfield". My JavaScript code which should send another script code looks as follows:

```<code>var r = new XMLHttpRequest();
var script_code = "<script>alert(1)<\/script>";
url = "foo.html";
r.open("POST", url, false);
var content = "textfield=".concat(script_code);
r.send(content);
</code>```

That works fine. But I am confused because:

```<code>var r = new XMLHttpRequest();
var script_code = "<script>alert(1);<\/script>";
url = "foo.html";
r.open("POST", url, false);
var content = "textfield=".concat(script_code);
r.send(content);
</code>```

or

```<code>var r = new XMLHttpRequest();
var script_code = "<script>alert(1);\n alert(2);<\/script>";
url = "foo.html";
r.open("POST", url, false);
var content = "textfield=".concat(script_code);
r.send(content);
</code>```

don't work. If I remove the semicolons it works again:

```<code>var r = new XMLHttpRequest();
var script_code = "<script>alert(1);\n alert(2);<\/script>";
script_code = script_code.replace(/;/g,"");
url = "foo.html";
r.open("POST", url, false);
var content = "textfield=".concat(script_code);
r.send(content);
</code>```

But I have a much larger script saved as a string that I want to send to foo.html but it doesn't work. It doesn't work as well if I remove all semicolons. That's why my questions is:
What does a "script as a string" has to look like so that this works?

EDIT:
@Keith Let's say I want to try the following:

```<code><script id=script_id>
//TODO: What do I have to write here to decode?
var r = new XMLHttpRequest();
alert(1);
alert(2);
var script_code = document.getElementById("script_id").innerHTML;
var sub_string_begin='<script>';
var sub_string_end="<\/script>";
script_code = sub_string_begin.concat(script_code, sub_string_end);

url = "foo.html";
r.open("POST", url, false);
var content = "textfield=".concat(script_code);
content = encodeURIComponent(content);
r.send(content);
</script>
</code>```

So I want to send the script itself. How do I decode it then?

答:
It all depends on how the post request is handled by 'foo.html'.

Very likely the post request is sanitised there.

Title: Send JavaScript in an HTTP post request

Body:
Let's say I have foo.html and there is a text-field where I submit text that is shown afterwards on the site. It is possible to write JavaScript in this text-field. For example  and  works.

What I want to do is to send a JavaScript as message per post request to foo.html. The form has a text-area and its name is "textfield". My JavaScript code which should send another script code looks as follows:

var r = new XMLHttpRequest();
var script_code = "

So I want to send the script itself. How do I decode it then?


问:
How to properly catch an error with react native
I am new with react native and I am trying catching an error in this way

```<code>Linking.openURL('test').catch(err =>
     alert('error' + err)
   );
</code>```

But If I try to log the error like this

```<code>Linking.openURL('test').catch(err =>
     alert('error' + err); // error in this line
     console.log(err);
   );
</code>```

I get a syntax error because of the comma.

答:
You're just missing the braces in the arrow function.

```<code>Linking.openURL('test').catch(err => {
   alert('error' + err); // error in this line
   console.log(err);
});
</code>```

You need braces if your arrow function has more than one sentence.

If you don't have braces, you should only have one sentence whose result will be automatically returned.

Body:
I am new with react native and I am trying catching an error in this way

Linking.openURL('test').catch(err =>
     alert('error' + err)
   );

But If I try to log the error like this

Linking.openURL('test').catch(err =>
     alert('error' + err); // error in this line
     console.log(err);
   );

I get a syntax error because of the comma.

Body:
You're just missing the braces in the arrow function.

Linking.openURL('test').catch(err => {
   alert('error' + err); // error in this line
   console.log(err);
});

You need braces if your arrow function has more than one sentence.

If you don't have braces, you should only have one sentence whose result will be automatically returned.


问:
Android Studio 3.0 laggy typing experience
I have an extremely disturbing laggy Android Studio editor. I read all proposed optimisation suggestions on the stack and did following things to speed it but nothing helped.

Increased the Heap Size in VM options with following options

Disabled all the plugins regarding git, svn etc.

Checked the followings in Compiler settings

Compiler independent modules

--offline in command line options

Configure on demand

My Device is an MBP from middle 2015 with 16 GB Ram and 512 GB SSD HD.The project is a Java Project which was ok on my other laptop.
Any other things I can do?

答:
I've experienced same problem.
It was buildTools version 25.0.2, but these worked that time.

Kill ADB once.

Version dependent lag.
Try another buildTools version.

Avoid re-trigger completion (ex. kill a letter with back space) while editing.
Code completion is a large part of lag.


问:
Why is that when float is specified to the clear div, its parent container's border does not recognize it?
example:

Html

```<code><div id = parent>
      <div class = "clearDiv"></div>
</div>
</code>```

css:

```<code>div.clearDiv
{
      width:      1000px;
      height:     1px;
      float:      left;
      clear:      both;
      visibility: hidden;
}
</code>```

with the float: left property specified, its parent div does not recognize it, the therefore the parent div #parent has a height that is pretty much zero, why?

答:
Set overflow:auto; CSS style to parent container element.

To parent container they don't provide dimensinal infomation. They just interact with their siblings (or other floated elements). Hence float. They can be anything, anywhere and of any size. Container doesn't really care because they're floating...

Body:
example:

Html

css:

div.clearDiv
{
      width:      1000px;
      height:     1px;
      float:      left;
      clear:      both;
      visibility: hidden;
}

with the float: left property specified, its parent div does not recognize it, the therefore the parent div #parent has a height that is pretty much zero, why?


问:
Page breaks for images in Python fpdf
I want to insert some lengthy images (each image can extend to 2 pages) using python fpdf. But the images don't continue to next page once a page break is triggered. How can I print the rest of the images into the next page starting from a given set_y value (header included)?</p>

答:
Although I believe there is a way with fpdf, I suggest you switch to pdfkit / wkhtmltopdf based solution.

I have many similar issues with reportlab, which is very like fpdf, then switched to wkhtmltopdf, feels much better.

With wkhtmltopdf, you could control layout with standard web stack, use CSS and javascript, use a favorite template engine, then convert HTML file to pdf, easier and much more powerful.

Title: Page breaks for images in Python fpdf


答:
Step 1: call a java script function while form submitted

```<code><form onsubmit="return test();">
</code>```

Step 2: inside test function set value in your text field.

```<code><script>
function test()
{
   document.getElementById("myTextFieldId").value = "12345";
   return true;
}
</script>
</code>```

Title: Change input text value in before submitting form

Body:
Step 1: call a java script function while form submitted

<form onsubmit="return test();">

Step 2: inside test function set value in your text field.

<script>
function test()
{
   document.getElementById("myTextFieldId").value = "12345";
   return true;
}
</script>


问:
require_without and require_unless for same field
I have 3 field 'account_name','billable_option' and 'billable_option_yes'

'billable_option' is required if 'billable_option_yes' is not filled and 'billable_option_yes' is required if 'billable_option' is not filled

and I want to check both field is not required if 'account_name' value is 0

I want to combine the validation required_unless:account_name,0

```<code>$this->validate($request,[
   'billable_option' => 'required_without:billable_option_yes',
   'billable_option_yes' =>'required_without:billable_option',
],$messages);
</code>```

答:
I think you can check first the value of account_name and based on that value you can validate further,
Here laravel provides required_unless validation to check for this field is required if that is null,

```<code>if($request->account_name != "0"){
  $this->validate($request,[
   'billable_option' => 'required_unless:billable_option_yes,null',
   'billable_option_yes' =>'required_unless:billable_option,null',
  ],$messages);
}
</code>```

or you can do like this,

```<code>$this->validate($request,[
   'billable_option' => 'required_if:account_name,==,0|required_unless:billable_option_yes,null',
   'billable_option_yes' =>'required_if:account_name,==,0|required_unless:billable_option,null',
  ],$messages);
</code>```

Hope it helps you.

Body:
I have 3 field 'account_name','billable_option' and 'billable_option_yes'

'billable_option' is required if 'billable_option_yes' is not filled and 'billable_option_yes' is required if 'billable_option' is not filled

and I want to check both field is not required if 'account_name' value is 0

I want to combine the validation required_unless:account_name,0

$this->validate($request,[
   'billable_option' => 'required_without:billable_option_yes',
   'billable_option_yes' =>'required_without:billable_option',
],$messages);

Body:
I think you can check first the value of account_name and based on that value you can validate further,
Here laravel provides required_unless validation to check for this field is required if that is null,

if($request->account_name != "0"){
  $this->validate($request,[
   'billable_option' => 'required_unless:billable_option_yes,null',
   'billable_option_yes' =>'required_unless:billable_option,null',
  ],$messages);
}

or you can do like this,

$this->validate($request,[
   'billable_option' => 'required_if:account_name,==,0|required_unless:billable_option_yes,null',
   'billable_option_yes' =>'required_if:account_name,==,0|required_unless:billable_option,null',
  ],$messages);

Hope it helps you.


问:
List of Guids not Model Binding Asp.Net Core
i'm sending an array of Guids to an ASP.NET Core Web app using aurelia-fetch-client, however on the server side the model binder doesn't pick it up and the list of notificationIds is null. However when i make the request through Swagger, or CURL it binds just fine.

I changed the signature of my controller method to accept a list of strings just in case there was something wrong with the GUID formatting, but same issue.

JS

```<code>var body = {notificationIds :  this.notifications.map(x => x.notificationId) };
    console.log("Dismissing All notifications");

    await this.httpClient.fetch('http://localhost:5000/api/notifications/clear',
        {
            method: 'POST',
            body: json(body),
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`,
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'X-Requested-With': 'Fetch'
            },
            mode: 'cors'
        }).then(response => {
            if(response.status == 204){
               //Success! Remove Notifications from VM
            }
            else{

                console.log(response.status)
            }
        })
</code>```

Controller Method

```<code>// POST: api/Notifications
        [HttpPost]
        [Route("clear")]
        [ProducesResponseType((int)HttpStatusCode.NoContent)]
        [ProducesResponseType((int)HttpStatusCode.BadRequest)]
        public async Task<IActionResult> Post([FromBody]List<string> notificationIds)
        {
            if (notificationIds.IsNullOrEmpty())
            {
                return BadRequest("No notifications requested to be cleared");
            }

            var name = User.Claims.ElementAt(1);

            await _notificationRepository.Acknowledge(notificationIds, name.Value);

            return NoContent();
}
</code>```

Interesting thing is that Chrome (V62) shows nothing posted.

But Fiddler does

答:
The shape of the object you are passing from JavaScript isn't the same shape of an object you are telling the ASP.NET framework to expect.

There are two ways that you could fix this issue:

Option 1:
In your JavaScript, change your body to var body = this.notifications.map(x => x.notificationId);

Option 2:
Create an object in c# that reflects what you are passing from your JavaScript.

```<code>namespace Foo
{
  public class Bar
  {
    public List<string> NotificationIds { get; set; }
  }
}
</code>```

and then update your controller method to the following:

```<code>// POST: api/Notifications
[HttpPost]
[Route("clear")]
[ProducesResponseType((int)HttpStatusCode.NoContent)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> Post([FromBody]Bar bar)
{
  if (bar.NotificationIds.IsNullOrEmpty())
  {
    return BadRequest("No notifications requested to be cleared");
  }

  var name = User.Claims.ElementAt(1);
  await _notificationRepository.Acknowledge(bar.NotificationIds, name.Value);
  return NoContent();
}
</code>```

Body:
i'm sending an array of Guids to an ASP.NET Core Web app using aurelia-fetch-client, however on the server side the model binder doesn't pick it up and the list of notificationIds is null. However when i make the request through Swagger, or CURL it binds just fine.

I changed the signature of my controller method to accept a list of strings just in case there was something wrong with the GUID formatting, but same issue.

JS

var body = {notificationIds :  this.notifications.map(x => x.notificationId) };
    console.log("Dismissing All notifications");

    await this.httpClient.fetch('http://localhost:5000/api/notifications/clear',
        {
            method: 'POST',
            body: json(body),
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`,
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'X-Requested-With': 'Fetch'
            },
            mode: 'cors'
        }).then(response => {
            if(response.status == 204){
               //Success! Remove Notifications from VM
            }
            else{

                console.log(response.status)
            }
        })

Controller Method

// POST: api/Notifications
        [HttpPost]
        [Route("clear")]
        [ProducesResponseType((int)HttpStatusCode.NoContent)]
        [ProducesResponseType((int)HttpStatusCode.BadRequest)]
        public async Task<IActionResult> Post([FromBody]List<string> notificationIds)
        {
            if (notificationIds.IsNullOrEmpty())
            {
                return BadRequest("No notifications requested to be cleared");
            }

            var name = User.Claims.ElementAt(1);

            await _notificationRepository.Acknowledge(notificationIds, name.Value);

            return NoContent();
}

Interesting thing is that Chrome (V62) shows nothing posted.

But Fiddler does

Body:
The shape of the object you are passing from JavaScript isn't the same shape of an object you are telling the ASP.NET framework to expect.

There are two ways that you could fix this issue:

Option 1:
In your JavaScript, change your body to var body = this.notifications.map(x => x.notificationId);

Option 2:
Create an object in c# that reflects what you are passing from your JavaScript.

namespace Foo
{
  public class Bar
  {
    public List<string> NotificationIds { get; set; }
  }
}

and then update your controller method to the following:

// POST: api/Notifications
[HttpPost]
[Route("clear")]
[ProducesResponseType((int)HttpStatusCode.NoContent)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> Post([FromBody]Bar bar)
{
  if (bar.NotificationIds.IsNullOrEmpty())
  {
    return BadRequest("No notifications requested to be cleared");
  }

  var name = User.Claims.ElementAt(1);
  await _notificationRepository.Acknowledge(bar.NotificationIds, name.Value);
  return NoContent();
}