问:
pyqt5 How to connect shortcut to child widget
I have a QtableWidget populated with forms (imported form).  Each form is basically a Qgroupbox that contains a couple pushbuttons and a spinbox.  I chose to put these in the table so that the arrow keys can be used to navigate between groupboxes. But I want each pushbutton to be checkable via a keyboard shortcut AND the spinbox to be adjusted via some kind of keyboard shortcut as well (perhaps shift plus arrow).  I have the navigation mostly working but the shortcuts that I have assigned to the pushbuttons don't work.  It seems that I need a way to "pass" the shortcut from the groupbox that has focus to the target widget inside that groupbox.  The second issue of adjusting the spinboxes appears to be related but I'm even less clear about how to go about setting this up.

I have attached most of the code (generated with QTCtreator) for the form.  It's interesting to me that the shortcut code is in the retranslate method.

image of single form

image of grid of forms

```<code>class Ui_FormLoads(object):
    def setupUi(self, FormLoads):
        FormLoads.setObjectName("FormLoads")
        FormLoads.resize(88, 105)
        FormLoads.setFocusPolicy(QtCore.Qt.TabFocus)
        FormLoads.setWindowTitle("LoadChannel")
        self.gridLayout = QtWidgets.QGridLayout(FormLoads)
        self.gridLayout.setContentsMargins(8, 8, 8, 8)
        self.gridLayout.setSpacing(0)
        self.gridLayout.setObjectName("gridLayout")
        self.groupBox = QtWidgets.QGroupBox(FormLoads)
        font = QtGui.QFont()
        font.setPointSize(10)
        self.groupBox.setFont(font)
        self.groupBox.setObjectName("groupBox")
        self.gridLayout_2 = QtWidgets.QGridLayout(self.groupBox)
        self.gridLayout_2.setContentsMargins(8, 8, 8, 8)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.pushStop = QtWidgets.QPushButton(self.groupBox)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushStop.sizePolicy().hasHeightForWidth())
        self.pushStop.setSizePolicy(sizePolicy)
        self.pushStop.setMinimumSize(QtCore.QSize(30, 0))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.pushStop.setFont(font)
        self.pushStop.setText("Stop")
        self.pushStop.setCheckable(True)
        self.pushStop.setObjectName("pushStop")
        self.gridLayout_2.addWidget(self.pushStop, 1, 0, 1, 1)
        self.pushReload = QtWidgets.QPushButton(self.groupBox)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushReload.sizePolicy().hasHeightForWidth())
        self.pushReload.setSizePolicy(sizePolicy)
        self.pushReload.setMinimumSize(QtCore.QSize(30, 0))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.pushReload.setFont(font)
        self.pushReload.setText("Load")
        self.pushReload.setCheckable(True)
        self.pushReload.setObjectName("pushReload")
        self.gridLayout_2.addWidget(self.pushReload, 1, 1, 1, 1)
        self.spinBox = QtWidgets.QSpinBox(self.groupBox)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.spinBox.sizePolicy().hasHeightForWidth())
        self.spinBox.setSizePolicy(sizePolicy)
        self.spinBox.setMinimumSize(QtCore.QSize(51, 0))
        font = QtGui.QFont()
        font.setPointSize(13)
        self.spinBox.setFont(font)
        self.spinBox.setMinimum(-20)
        self.spinBox.setMaximum(12)
        self.spinBox.setObjectName("spinBox")
        self.gridLayout_2.addWidget(self.spinBox, 0, 0, 1, 2)
        self.gridLayout.addWidget(self.groupBox, 0, 0, 1, 1)

        self.retranslateUi(FormLoads)
        QtCore.QMetaObject.connectSlotsByName(FormLoads)

    def retranslateUi(self, FormLoads):
        _translate = QtCore.QCoreApplication.translate
        self.groupBox.setTitle(_translate("FormLoads", "GroupBox"))
        self.pushStop.setShortcut(_translate("FormLoads", "S"))
        self.pushReload.setShortcut(_translate("FormLoads", "L"))
</code>```

答:
Well, I figured out how to do this. [btw formLoad is the variable name I'm using for the forms when I iterate through to populate the table.  actionStop is the variable name I'm using for this particular shortcut.]

```<code>self.formLoad.actionStop = QtWidgets.QShortcut(QtGui.QKeySequence("S"), self.formLoad)
self.formLoad.actionStop.activated.connect(self.formLoad.ui.pushStop.click)
self.formLoad.actionStop.setContext(QtCore.Qt.WidgetWithChildrenShortcut)
</code>```

A) First was understanding the scope and focus.  I ended up setting the most senior widget (for the form) to strongfocus and everything else except the spinbox to nofocus.  The spinbox is set to wheelfocus which allows it to be wheeled or typed.  The focus settings can be set in QtCreator/Designer which means there is less that you have to add in your main py file.  Keeping focus off the buttons keeps the key command from shifting focus to an individual button which I suspect may be problematic on a Mac depending on if you have keyboard shortcuts set to "all" in system preferences.  Then, setting the context attribute to 'WidgetWithChildrenShortcut' allows the keycommand to filter down from the top widget to the pushbutton. [btw, There doesn't appear to be a way to define context using the shortcuts that you can set in QtCreator so I instead defined the shortcuts explicitly.] When I created the actionStop shortcut you can see that I assigned it to formLoad as it's parent.  This assigns the shortcut to the widget that is set for strongfocus.

```<code>self.formLoad.actionIncrement = QtWidgets.QShortcut(QtGui.QKeySequence("Alt+Up"), self.formLoad)
self.formLoad.actionIncrement.activated.connect(self.formLoad.ui.spinBox.stepUp)
self.formLoad.actionIncrement.setContext(QtCore.Qt.WidgetWithChildrenShortcut)
self.formLoad.actionDecrement = QtWidgets.QShortcut(QtGui.QKeySequence("Alt+Down"), self.formLoad)
self.formLoad.actionDecrement.activated.connect(self.formLoad.ui.spinBox.stepDown)
self.formLoad.actionDecrement.setContext(QtCore.Qt.WidgetWithChildrenShortcut)
</code>```

B)  Secondly I had to figure out which attributes (and their names) that can be "triggered" by a shortcut.  These aren't clearly documented on the main QT page for QPushButton or QSpinBox.  I found the "click" attribute in some example code online and I found the up and down button attributes in the QT documentation for the QAbstractSpinBox. 'stepUp' and 'stepDown' are equivalent to clicking the up or down buttons of the spinbox. In this case I used the Alt modifier key with the up and down arrows.  Somewhere in the Qt documentation is the list of key commands with their string titles ("Alt+Up" etc).

```<code>    self.formLoad.actionZero = QtWidgets.QShortcut(QtGui.QKeySequence("0"), self.formLoad)
    self.formLoad.actionZero.setContext(QtCore.Qt.WidgetWithChildrenShortcut)
    self.formLoad.actionZero.activated.connect(functools.partial(self.spinboxset, 0, self.formLoad.ui.spinBox))

@QtCore.pyqtSlot()
def spinboxset(self, key, spInBox):
    spInBox.setValue(key)
</code>```

C)  Lastly, I decided to implement some key commands that directly load a specific value into the spinbox.  This was trickier because you can't use the 'setValue' function directly from the activated.connect line.  I tried some variations on lambda but importing functools and using partial with a separate function is what worked.  The last element that is being passed by partial is the  spinbox that was a subwidget of the cell that was being populated. This way, the method knows which spinbox to apply the value to.  Without sending this, it will always apply the value to the last 'formLoad.spinBox' that had been defined with that name. The second element being passed (called key) is the value.  This allows the one method (spinboxset) to be used for multiple key commands.  For instance, another one can be set for "5".

```<code>self.formLoad.actionFive = QtWidgets.QShortcut(QtGui.QKeySequence("5"), self.formLoad)
self.formLoad.actionFive.setContext(QtCore.Qt.WidgetWithChildrenShortcut)
self.formLoad.actionFive.activated.connect(functools.partial(self.spinboxset, 5, self.formLoad.ui.spinBox))
</code>```

Now, if someone can show me how to copy and paste all the settings of a cell between cells I'll be set...

Body:
I have a QtableWidget populated with forms (imported form).  Each form is basically a Qgroupbox that contains a couple pushbuttons and a spinbox.  I chose to put these in the table so that the arrow keys can be used to navigate between groupboxes. But I want each pushbutton to be checkable via a keyboard shortcut AND the spinbox to be adjusted via some kind of keyboard shortcut as well (perhaps shift plus arrow).  I have the navigation mostly working but the shortcuts that I have assigned to the pushbuttons don't work.  It seems that I need a way to "pass" the shortcut from the groupbox that has focus to the target widget inside that groupbox.  The second issue of adjusting the spinboxes appears to be related but I'm even less clear about how to go about setting this up.

I have attached most of the code (generated with QTCtreator) for the form.  It's interesting to me that the shortcut code is in the retranslate method.

image of single form

image of grid of forms

class Ui_FormLoads(object):
    def setupUi(self, FormLoads):
        FormLoads.setObjectName("FormLoads")
        FormLoads.resize(88, 105)
        FormLoads.setFocusPolicy(QtCore.Qt.TabFocus)
        FormLoads.setWindowTitle("LoadChannel")
        self.gridLayout = QtWidgets.QGridLayout(FormLoads)
        self.gridLayout.setContentsMargins(8, 8, 8, 8)
        self.gridLayout.setSpacing(0)
        self.gridLayout.setObjectName("gridLayout")
        self.groupBox = QtWidgets.QGroupBox(FormLoads)
        font = QtGui.QFont()
        font.setPointSize(10)
        self.groupBox.setFont(font)
        self.groupBox.setObjectName("groupBox")
        self.gridLayout_2 = QtWidgets.QGridLayout(self.groupBox)
        self.gridLayout_2.setContentsMargins(8, 8, 8, 8)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.pushStop = QtWidgets.QPushButton(self.groupBox)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushStop.sizePolicy().hasHeightForWidth())
        self.pushStop.setSizePolicy(sizePolicy)
        self.pushStop.setMinimumSize(QtCore.QSize(30, 0))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.pushStop.setFont(font)
        self.pushStop.setText("Stop")
        self.pushStop.setCheckable(True)
        self.pushStop.setObjectName("pushStop")
        self.gridLayout_2.addWidget(self.pushStop, 1, 0, 1, 1)
        self.pushReload = QtWidgets.QPushButton(self.groupBox)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.pushReload.sizePolicy().hasHeightForWidth())
        self.pushReload.setSizePolicy(sizePolicy)
        self.pushReload.setMinimumSize(QtCore.QSize(30, 0))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.pushReload.setFont(font)
        self.pushReload.setText("Load")
        self.pushReload.setCheckable(True)
        self.pushReload.setObjectName("pushReload")
        self.gridLayout_2.addWidget(self.pushReload, 1, 1, 1, 1)
        self.spinBox = QtWidgets.QSpinBox(self.groupBox)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.spinBox.sizePolicy().hasHeightForWidth())
        self.spinBox.setSizePolicy(sizePolicy)
        self.spinBox.setMinimumSize(QtCore.QSize(51, 0))
        font = QtGui.QFont()
        font.setPointSize(13)
        self.spinBox.setFont(font)
        self.spinBox.setMinimum(-20)
        self.spinBox.setMaximum(12)
        self.spinBox.setObjectName("spinBox")
        self.gridLayout_2.addWidget(self.spinBox, 0, 0, 1, 2)
        self.gridLayout.addWidget(self.groupBox, 0, 0, 1, 1)

        self.retranslateUi(FormLoads)
        QtCore.QMetaObject.connectSlotsByName(FormLoads)

    def retranslateUi(self, FormLoads):
        _translate = QtCore.QCoreApplication.translate
        self.groupBox.setTitle(_translate("FormLoads", "GroupBox"))
        self.pushStop.setShortcut(_translate("FormLoads", "S"))
        self.pushReload.setShortcut(_translate("FormLoads", "L"))

Body:
Well, I figured out how to do this. [btw formLoad is the variable name I'm using for the forms when I iterate through to populate the table.  actionStop is the variable name I'm using for this particular shortcut.]

self.formLoad.actionStop = QtWidgets.QShortcut(QtGui.QKeySequence("S"), self.formLoad)
self.formLoad.actionStop.activated.connect(self.formLoad.ui.pushStop.click)
self.formLoad.actionStop.setContext(QtCore.Qt.WidgetWithChildrenShortcut)

A) First was understanding the scope and focus.  I ended up setting the most senior widget (for the form) to strongfocus and everything else except the spinbox to nofocus.  The spinbox is set to wheelfocus which allows it to be wheeled or typed.  The focus settings can be set in QtCreator/Designer which means there is less that you have to add in your main py file.  Keeping focus off the buttons keeps the key command from shifting focus to an individual button which I suspect may be problematic on a Mac depending on if you have keyboard shortcuts set to "all" in system preferences.  Then, setting the context attribute to 'WidgetWithChildrenShortcut' allows the keycommand to filter down from the top widget to the pushbutton. [btw, There doesn't appear to be a way to define context using the shortcuts that you can set in QtCreator so I instead defined the shortcuts explicitly.] When I created the actionStop shortcut you can see that I assigned it to formLoad as it's parent.  This assigns the shortcut to the widget that is set for strongfocus.

self.formLoad.actionIncrement = QtWidgets.QShortcut(QtGui.QKeySequence("Alt+Up"), self.formLoad)
self.formLoad.actionIncrement.activated.connect(self.formLoad.ui.spinBox.stepUp)
self.formLoad.actionIncrement.setContext(QtCore.Qt.WidgetWithChildrenShortcut)
self.formLoad.actionDecrement = QtWidgets.QShortcut(QtGui.QKeySequence("Alt+Down"), self.formLoad)
self.formLoad.actionDecrement.activated.connect(self.formLoad.ui.spinBox.stepDown)
self.formLoad.actionDecrement.setContext(QtCore.Qt.WidgetWithChildrenShortcut)

B)  Secondly I had to figure out which attributes (and their names) that can be "triggered" by a shortcut.  These aren't clearly documented on the main QT page for QPushButton or QSpinBox.  I found the "click" attribute in some example code online and I found the up and down button attributes in the QT documentation for the QAbstractSpinBox. 'stepUp' and 'stepDown' are equivalent to clicking the up or down buttons of the spinbox. In this case I used the Alt modifier key with the up and down arrows.  Somewhere in the Qt documentation is the list of key commands with their string titles ("Alt+Up" etc).

    self.formLoad.actionZero = QtWidgets.QShortcut(QtGui.QKeySequence("0"), self.formLoad)
    self.formLoad.actionZero.setContext(QtCore.Qt.WidgetWithChildrenShortcut)
    self.formLoad.actionZero.activated.connect(functools.partial(self.spinboxset, 0, self.formLoad.ui.spinBox))

@QtCore.pyqtSlot()
def spinboxset(self, key, spInBox):
    spInBox.setValue(key)

C)  Lastly, I decided to implement some key commands that directly load a specific value into the spinbox.  This was trickier because you can't use the 'setValue' function directly from the activated.connect line.  I tried some variations on lambda but importing functools and using partial with a separate function is what worked.  The last element that is being passed by partial is the  spinbox that was a subwidget of the cell that was being populated. This way, the method knows which spinbox to apply the value to.  Without sending this, it will always apply the value to the last 'formLoad.spinBox' that had been defined with that name. The second element being passed (called key) is the value.  This allows the one method (spinboxset) to be used for multiple key commands.  For instance, another one can be set for "5".

self.formLoad.actionFive = QtWidgets.QShortcut(QtGui.QKeySequence("5"), self.formLoad)
self.formLoad.actionFive.setContext(QtCore.Qt.WidgetWithChildrenShortcut)
self.formLoad.actionFive.activated.connect(functools.partial(self.spinboxset, 5, self.formLoad.ui.spinBox))

Now, if someone can show me how to copy and paste all the settings of a cell between cells I'll be set...


来源: stackexchange

问:
Can't prevent navigation gesture in latest Chrome version (59) on mac
Not being able to completely disable the two-finger swipe gesture to navigate through the browser history for a whole website is a constant annoyance to me. Up until this point, it was at least possible to prevent that behavior by calling preventDefault() on the mousewheel event.

This does not seem to be working anymore in Chrome 59.

Here is how to reproduce it:

Start the gesture somewhere on the page, then cancel it

From there on, preventDefault has no effect.

Does anyone have a solution to this?

Examples

Zenkit and Airtable both call preventDefault when you scroll inside their table view. It seems to be working at first, but as soon as the gesture was recognized and then canceled at least once (outside the table, where prevent default is not called), preventing the gesture doesn't work anymore (even inside the table). So from there on, scrolling to the left inside the table is almost impossible because it always triggers the gesture.

In Trello`s kanban view it only occurs if you're at the left or right edge of the scroller. But I guess that is because they use native scrolling while Zenkit and Airtable use css translation instead.

I tried creating an invisible scroll container on top of the content once the user starts scrolling and removing it afterwards. This reduces the problem significantly but doesn't work in all of the cases.

Example Code:
https://codepen.io/anon/pen/gRKaMX

There are 3 boxes in this pen.

The fist one scrolls natively using overflow: scroll. Here the gesture can only be triggered if scrollLeft is 0.

The second one has an event listener attached that calls preventDefault on every mousewheel event. This prevents the gesture at first but once you started it anywhere else on the page, it doesn't work anymore.

And lastly there is a third div that you can always start the gesture on.

StackOverflow wants me to inline the code as well, so here it is:

HTML:

```<code> Native Scrolling:
<div id="native-scrolling" class="box">
  <div></div>
 </div>

Prevent gesture by calling prevent default. Only works if you didn't start the gesture anywhere else, yet:
<div id="prevent-gesture" class="box"></div>

Just a normal div:
<div class="box"></div>
</code>```

JavaScript:

```<code>$('#prevent-gesture').on('mousewheel', function (event) {
  event.preventDefault();
});
</code>```

CSS:

```<code>.box {
  height: 100px;
  width: 200px;
  background: black;
}

#native-scrolling {
  overflow: scroll;
}

#native-scrolling > div {
  width: 200%;
  height: 10px;
}
</code>```

Thanks in advance,
Jesse

Edit: About the accepted answer

Restarting Chrome fixes this issue temporarily but it keeps coming back. I'm on Chrom 69 now and it still occurs.

答: Have you tried turning it off and on again?</p>

ContentLicense: CC BY-SA 4.0

Body:
Not being able to completely disable the two-finger swipe gesture to navigate through the browser history for a whole website is a constant annoyance to me. Up until this point, it was at least possible to prevent that behavior by calling preventDefault() on the mousewheel event.

This does not seem to be working anymore in Chrome 59.

Here is how to reproduce it:

Start the gesture somewhere on the page, then cancel it

From there on, preventDefault has no effect.

Does anyone have a solution to this?

Examples

Zenkit and Airtable both call preventDefault when you scroll inside their table view. It seems to be working at first, but as soon as the gesture was recognized and then canceled at least once (outside the table, where prevent default is not called), preventing the gesture doesn't work anymore (even inside the table). So from there on, scrolling to the left inside the table is almost impossible because it always triggers the gesture.

In Trello`s kanban view it only occurs if you're at the left or right edge of the scroller. But I guess that is because they use native scrolling while Zenkit and Airtable use css translation instead.

I tried creating an invisible scroll container on top of the content once the user starts scrolling and removing it afterwards. This reduces the problem significantly but doesn't work in all of the cases.

Example Code:
https://codepen.io/anon/pen/gRKaMX

There are 3 boxes in this pen.

The fist one scrolls natively using overflow: scroll. Here the gesture can only be triggered if scrollLeft is 0.

The second one has an event listener attached that calls preventDefault on every mousewheel event. This prevents the gesture at first but once you started it anywhere else on the page, it doesn't work anymore.

And lastly there is a third div that you can always start the gesture on.

StackOverflow wants me to inline the code as well, so here it is:

HTML:

 Native Scrolling:

Prevent gesture by calling prevent default. Only works if you didn't start the gesture anywhere else, yet:

Just a normal div:

JavaScript:

$('#prevent-gesture').on('mousewheel', function (event) {
  event.preventDefault();
});

CSS:

.box {
  height: 100px;
  width: 200px;
  background: black;
}

#native-scrolling {
  overflow: scroll;
}

#native-scrolling > div {
  width: 200%;
  height: 10px;
}

Thanks in advance,
Jesse

Edit: About the accepted answer

Restarting Chrome fixes this issue temporarily but it keeps coming back. I'm on Chrom 69 now and it still occurs.

ContentLicense: CC BY-SA 3.0


问:
incomplete retrieved string from mysqli DB, PHP statement
I am filling an edit form from a database, so i retrieve text from a database field and place it in an input text as follows:

```<code>    echo '<b> Topic: </b><input type = text size = 50 value = ' . $filler['LP_Topic'].'>'. $br;
</code>```

it works fine, but it only gets the first word of the topic, not the whole string!

if I just echo the result without an input it will work perfectly ! the problem happens when I add  input
regards

答:
Try adding quotes around the value. All html properties/attributes are supposed to be quoted.</p>

```<code>echo '<b> Topic: </b><input type="text" size="50" value="' . $filler['LP_Topic'].'">'. $br;
</code>```

Body:
I am filling an edit form from a database, so i retrieve text from a database field and place it in an input text as follows:

    echo ' Topic: <input type = text size = 50 value = ' . $filler['LP_Topic'].'>'. $br;

it works fine, but it only gets the first word of the topic, not the whole string!

if I just echo the result without an input it will work perfectly ! the problem happens when I add  input
regards

Body:
Try adding quotes around the value. All html properties/attributes are supposed to be quoted.

echo '<b> Topic: </b><input type="text" size="50" value="' . $filler['LP_Topic'].'">'. $br;


问:
Finding if an element is in an array using C (syntax issue)
I'm trying to write a function that checks if an element is an array in C. I have a function here, but it always returns 0, so any debugging help would be appreciated:</p>

```<code>#include <stdio.h>
int array[] = {1, 2, 3};
int *parray = &array;
int j;
int n = sizeof(array)/sizeof(array[0]);

int ifInList(int array[], int n){
    for (j = 0; j < n; j++){
        if (array[j] == n){
           return 1;
        }
    }
    return 0;
}

int main(){
    printf("The number is %d \n", ifInList(&array[n], 1));
    return 0;
}
</code>```

答:
You are searching incorrectly:

```<code>ifInList(&array[n], 1);

arr[0]    arr[1]            ....   a[n-1]    a[n]
<----Search only these many elements --->     ^~~~You are searching unreserved address.
</code>```

Accessing a[n] could result into bugs that are very difficult to debug. You are not supposed to do that at first place.

Correct code :

```<code>ifInList(array, sizeOfArray, valueToFind);  //searches in the complete array

for (j = 0; j < sizeOfArray; j++){  //Loop
      if (array[j] == valueToFind){
</code>```

Another important advice, try to avoid usage of global variables when they are not necessarily needed.

Body:
I'm trying to write a function that checks if an element is an array in C. I have a function here, but it always returns 0, so any debugging help would be appreciated:

#include <stdio.h>
int array[] = {1, 2, 3};
int *parray = &array;
int j;
int n = sizeof(array)/sizeof(array[0]);

int ifInList(int array[], int n){
    for (j = 0; j < n; j++){
        if (array[j] == n){
           return 1;
        }
    }
    return 0;
}

int main(){
    printf("The number is %d \n", ifInList(&array[n], 1));
    return 0;
}

Body:
You are searching incorrectly:

ifInList(&array[n], 1);

arr[0]    arr[1]            ....   a[n-1]    a[n]
<----Search only these many elements --->     ^~~~You are searching unreserved address.

Accessing a[n] could result into bugs that are very difficult to debug. You are not supposed to do that at first place.

Correct code :

ifInList(array, sizeOfArray, valueToFind);  //searches in the complete array

for (j = 0; j < sizeOfArray; j++){  //Loop
      if (array[j] == valueToFind){

Another important advice, try to avoid usage of global variables when they are not necessarily needed.


问:
Dynamically creating asp.net with c# pages
I am struggling with finding clear answers to dynamically creating the same page over and over.  The questions and samples I have found seem to be all over the board on this topic.  I have studied the life cycle and still seem to not have a clear answer as to where code should go.

I have a master page and a content page.  All the content in the content area needs to be dynamically created (text boxes, ddl's, page tabs, buttons/onclick etc.).

After a user fills in data and clicks a submit button, I need to read the values off the form and rebuild the page completely again (not add/remove controls to current content).

My question is then.
Where do I put my code to build the page?
Will this area allow me to use IsPostBack so I can rebuild content with Request.Form values?
Will my buttons _Click events work?
Are there any working samples out there you could direct me to?

Thank you very much for the feedback...

答:
Brian's advices are good and you should follow them.

This might not really answer your question but still I add it as an advice. I'm professionally creating ASP.net web applications at quite a large scale and from my experience I can say that too much "dynamics" is usually bad and should be avoided because it just introduces complexity. Normally you might want to expose UI parts into ASP.net UserControls or if you want to make them even more reusable (if that's a factor) then into ASP.net Server controls. Then you replace different of them dynamically rather than creating everything from scratch.

ContentLicense: CC BY-SA 2.5


问:
Partition in metastore but path doesn't exist in HDFS
We had an issue with our ingestion process that would result in partitions being added to a table in Hive, but the path in HDFS didn't actually exist.  We've fixed that issue, but we still have these bad partitions.    When querying these tables using Tez, we get FileNotFound exception, pointing to the location in HDFS that doesn't exist.  If we use MR instead of Tez, the query works (which is very confusing to me), but it's too slow.

Is there a way to list all the partitions that have this probem?  MSCK REPAIR seems to handle the opposite problem, where the data exists in HDFS but there is no partition in Hive.

EDIT:  More info.
Here's the output of the file not found exception:

java.io.FileNotFoundException: File hdfs://<server>/db/tables/2016/03/14/mytable does not exist.

If I run show partitions <db.mytable>, I'll get all the partitions, including one for dt=2016-03-14.

show table extended like '<db.mytable>' partition(dt='2016-03-14' returns the same location:
location:hdfs://server/db/tables/2016/03/14/mytable.

答:
It seem MSCK REPAIR TABLE does not drop partitions that point to missing directories, but it does list these partitions (see Partitions not in metastore:), so with a little scripting / manual work, you can drop them based on the given list.

```<code>hive> create table mytable (i int) partitioned by (p int);
OK
Time taken: 0.539 seconds

hive> !mkdir mytable/p=1;
hive> !mkdir mytable/p=2;
hive> !mkdir mytable/p=3;

hive> msck repair table mytable;
OK
Partitions not in metastore:    mytable:p=1 mytable:p=2 mytable:p=3
Repair: Added partition to metastore mytable:p=1
Repair: Added partition to metastore mytable:p=2
Repair: Added partition to metastore mytable:p=3
Time taken: 0.918 seconds, Fetched: 4 row(s)

hive> show partitions mytable;
OK
p=1
p=2
p=3
Time taken: 0.331 seconds, Fetched: 3 row(s)

hive> !rmdir mytable/p=1;
hive> !rmdir mytable/p=2;
hive> !rmdir mytable/p=3;

hive> msck repair table mytable;
OK
Partitions missing from filesystem: mytable:p=1 mytable:p=2 mytable:p=3
Time taken: 0.425 seconds, Fetched: 1 row(s)

hive> show partitions mytable;
OK
p=1
p=2
p=3
Time taken: 0.56 seconds, Fetched: 3 row(s)
</code>```

Body:
It seem MSCK REPAIR TABLE does not drop partitions that point to missing directories, but it does list these partitions (see Partitions not in metastore:), so with a little scripting / manual work, you can drop them based on the given list.

hive> create table mytable (i int) partitioned by (p int);
OK
Time taken: 0.539 seconds

hive> !mkdir mytable/p=1;
hive> !mkdir mytable/p=2;
hive> !mkdir mytable/p=3;

hive> msck repair table mytable;
OK
Partitions not in metastore:    mytable:p=1 mytable:p=2 mytable:p=3
Repair: Added partition to metastore mytable:p=1
Repair: Added partition to metastore mytable:p=2
Repair: Added partition to metastore mytable:p=3
Time taken: 0.918 seconds, Fetched: 4 row(s)

hive> show partitions mytable;
OK
p=1
p=2
p=3
Time taken: 0.331 seconds, Fetched: 3 row(s)

hive> !rmdir mytable/p=1;
hive> !rmdir mytable/p=2;
hive> !rmdir mytable/p=3;

hive> msck repair table mytable;
OK
Partitions missing from filesystem: mytable:p=1 mytable:p=2 mytable:p=3
Time taken: 0.425 seconds, Fetched: 1 row(s)

hive> show partitions mytable;
OK
p=1
p=2
p=3
Time taken: 0.56 seconds, Fetched: 3 row(s)


问:
How to mark Jenkins builds as SUCCESS only on specific error exit values (other than 0)?
When I run an Execute shell build step to execute a script and that script returns 0, Jenkins flags the build as SUCCESS, otherwise it flags it as FAILURE which is the expected default behaviour as 0 means no errors and any other value represents an error.

Is there a way to mark a build as SUCCESS only if the return value matches a specific value other than 0 (e.g. 1,2,3...)?

PS: in case you're wondering why I'm looking for that, this will allow me to perform unit testing of Jenkins itself as my scripts are written to return different exit values depending on various factors, thus allowing me to expect certain values depending on certain setup mistakes and making sure my whole Jenkins integration picks up on those.

答:
I do it like this:

```<code>set +e
./myscript.sh
rc="$?"
set -e
if [ "$rc" == "$EXPECTED_CODE_1" ]; then
    #...actions 1 (if required)
    exit 0
elif [ "$rc" == "$EXPECTED_CODE_2" ]; then
    #...actions 2 (if required)
    exit 0
else
    #...actions else (if required)
    exit "$rc"
fi
echo "End of script" #Should never happen, just to indicate there's nothing further
</code>```

Here +e is to avoid default Jenkins behavior to report FAILURE on any sneeze during your script execution. Then get back with -e.

So that you can handle your exit code as appropriate, else eventually FAIL with the returned code.

Body:
I do it like this:

set +e
./myscript.sh
rc="$?"
set -e
if [ "$rc" == "$EXPECTED_CODE_1" ]; then
    #...actions 1 (if required)
    exit 0
elif [ "$rc" == "$EXPECTED_CODE_2" ]; then
    #...actions 2 (if required)
    exit 0
else
    #...actions else (if required)
    exit "$rc"
fi
echo "End of script" #Should never happen, just to indicate there's nothing further

Here +e is to avoid default Jenkins behavior to report FAILURE on any sneeze during your script execution. Then get back with -e.

So that you can handle your exit code as appropriate, else eventually FAIL with the returned code.


问:
How should I structure dockerized RabbitMQ?
I am trying to migrate our monolithic PHP Symfony app to a somewhat more scalable solution with Docker. There is some communication between the app and RabbitMQ, and I use docker-compose to bring all the containers up, in this case the app and the RabbitMQ server.

There is a lot of discussions around the topic that one container should spawn only one process, and the Docker best practices is somewhat vague regarding this point:

While this mantra has good intentions, it is not necessarily true that
  there should be only one operating system process per container. In
  addition to the fact that containers can now be spawned with an init
  process, some programs might spawn additional processes of their own
  accord.

Does it make sense to create a separate Docker container for each RabbitMQ consumer? It kind of feels "right" and "clean" to not let rabbitmq server know of language/tools used to process the queue. I came up with (relevant parts of docker-compose.yml):

```<code>  app :
    # my php-fpm app container

  rabbitmq_server:
    container_name: sf.rabbitmq_server
    build: .docker/rabbitmq
    ports:
        - "15672:15672"
        - "5672:5672"
    networks:
      - app_network

  rabbitmq_consumer:
    container_name: sf.rabbit_consumer
    extends: app
    depends_on:
      - rabbitmq_server
    working_dir: /app
    command: "php bin/console rabbitmq:consumer test"
    networks:
      - app_network
</code>```

I could run several consumers in the rabbitmq_consumer container using nohup or some other way of running them in the background.

I guess my questions are:

Can I somehow automate the "adding a new consumer", so that I would not have to edit the "build script" of Docker (and others, like ansible) every time the new consumer is added from the code?

Does it make sense to separate RabbitMQ server from Consumers, or should I use the Rabbit server with consumers running in the background?

Or should they be placed in the background of the app container?

答:
I'll share my experience so think critically about it.

Consumers have to be run in a separate container from a web app. The consumer container runs a process manager like these. Its responsibility is to spawn some child consumer processor, reboot them if they exit, reload on SIGUSR1 signal, shut down them correctly on SIGTERM. If the main process exists the whole container exists as well. You may have a police for this case like always restart. Here's how the consume.php script look like:

```<code><?php

// bin/consume.php
use App\Infra\SymfonyDaemon;
use Symfony\Component\Process\ProcessBuilder;

require __DIR__.'/../vendor/autoload.php';

$workerBuilder = new ProcessBuilder(['bin/console', 'enqueue:consume', '--setup-broker', '-vvv']);
$workerBuilder->setPrefix('php');
$workerBuilder->setWorkingDirectory(realpath(__DIR__.'/..'));
$daemon = new SymfonyDaemon($workerBuilder);
$daemon->start(3);
</code>```

The container config looks like:

```<code>app_consumer:
    restart: 'always'
    entrypoint: "php bin/consume.php"
    depends_on:
      - 'rabbitmq_server'
</code>```

Can I somehow automate the "adding a new consumer", so that I would not have to edit the "build script" of Docker (and others, like ansible) every time the new consumer is added from the code?

Unfortunately, the RabbitMQ bundle queue managment leaves much to be desired. By default, you have to run a single command per queue. If you have 100 queues you need 100 processes, at least one per queue. There is a way to configure a multi-queue consumer but requires completely different setup. By the way, enqueue does it a lot better. you can run a single command to consume from all queues at once. The --queue command option allows doing more accurate adjustments.

Does it make sense to separate RabbitMQ server from Consumers, or should I use the Rabbit server with consumers running in the background?

RabbitMQ server should be run in a separate container. I would not suggest adding them to mixing them up in one container.

Or should they be placed in the background of the app container?

I'd suggest having at least two app containers. One runs a web server and serves HTTP request another one runs queue consumers.

Body:
I am trying to migrate our monolithic PHP Symfony app to a somewhat more scalable solution with Docker. There is some communication between the app and RabbitMQ, and I use docker-compose to bring all the containers up, in this case the app and the RabbitMQ server.

There is a lot of discussions around the topic that one container should spawn only one process, and the Docker best practices is somewhat vague regarding this point:

While this mantra has good intentions, it is not necessarily true that
  there should be only one operating system process per container. In
  addition to the fact that containers can now be spawned with an init
  process, some programs might spawn additional processes of their own
  accord.

Does it make sense to create a separate Docker container for each RabbitMQ consumer? It kind of feels "right" and "clean" to not let rabbitmq server know of language/tools used to process the queue. I came up with (relevant parts of docker-compose.yml):

  app :
    # my php-fpm app container

  rabbitmq_server:
    container_name: sf.rabbitmq_server
    build: .docker/rabbitmq
    ports:
        - "15672:15672"
        - "5672:5672"
    networks:
      - app_network

  rabbitmq_consumer:
    container_name: sf.rabbit_consumer
    extends: app
    depends_on:
      - rabbitmq_server
    working_dir: /app
    command: "php bin/console rabbitmq:consumer test"
    networks:
      - app_network

I could run several consumers in the rabbitmq_consumer container using nohup or some other way of running them in the background.

I guess my questions are:

Can I somehow automate the "adding a new consumer", so that I would not have to edit the "build script" of Docker (and others, like ansible) every time the new consumer is added from the code?

Does it make sense to separate RabbitMQ server from Consumers, or should I use the Rabbit server with consumers running in the background?

Or should they be placed in the background of the app container?

Body:
I'll share my experience so think critically about it.

Consumers have to be run in a separate container from a web app. The consumer container runs a process manager like these. Its responsibility is to spawn some child consumer processor, reboot them if they exit, reload on SIGUSR1 signal, shut down them correctly on SIGTERM. If the main process exists the whole container exists as well. You may have a police for this case like always restart. Here's how the consume.php script look like:

<?php

// bin/consume.php
use App\Infra\SymfonyDaemon;
use Symfony\Component\Process\ProcessBuilder;

require __DIR__.'/../vendor/autoload.php';

$workerBuilder = new ProcessBuilder(['bin/console', 'enqueue:consume', '--setup-broker', '-vvv']);
$workerBuilder->setPrefix('php');
$workerBuilder->setWorkingDirectory(realpath(__DIR__.'/..'));
$daemon = new SymfonyDaemon($workerBuilder);
$daemon->start(3);

The container config looks like:

app_consumer:
    restart: 'always'
    entrypoint: "php bin/consume.php"
    depends_on:
      - 'rabbitmq_server'

Can I somehow automate the "adding a new consumer", so that I would not have to edit the "build script" of Docker (and others, like ansible) every time the new consumer is added from the code?

Unfortunately, the RabbitMQ bundle queue managment leaves much to be desired. By default, you have to run a single command per queue. If you have 100 queues you need 100 processes, at least one per queue. There is a way to configure a multi-queue consumer but requires completely different setup. By the way, enqueue does it a lot better. you can run a single command to consume from all queues at once. The --queue command option allows doing more accurate adjustments.

Does it make sense to separate RabbitMQ server from Consumers, or should I use the Rabbit server with consumers running in the background?

RabbitMQ server should be run in a separate container. I would not suggest adding them to mixing them up in one container.

Or should they be placed in the background of the app container?

I'd suggest having at least two app containers. One runs a web server and serves HTTP request another one runs queue consumers.


问:
How to achieve filling a path object on a canvas?
I have a problem filling a path drawn on a canvas.
I read all those previous questions saying

```<code>Paint red = new Paint();
red.setColor(Color.RED);
red.setStyle(Paint.Style.FILL_AND_STROKE);
</code>```

should be the way it works. Then I drew my Path like

```<code>Path p = new Path();
p.moveTo(100,100); //point1
p.lineTo(200,200);
p.moveTo(200,200); //point2
p.lineTo(100,200);
p.moveTo(100,200); //point3
p.lineTo(100,100);
p.close();
</code>```

Which should be a closed path in my opinion.
After canvas.drawPath(p, red);
the triangle/path is drawn but not filled although style is FILL_AND_STROKE.
What am I getting wrong?

答:
There is no path to fill because your path consists of multiple lines, but no coherent polygon. See moveTo documentation, which reads:

Set the beginning of the next contour to the point (x,y).

So by calling moveTo you are only drawing lines.

Only use lineTo(), which also "moves" to the target position. And you can skip the last lineTo() going to the point of origin, close() will do this automatically.

```<code>// create a triangle
Path p = new Path();
p.moveTo(100,100); //p1
p.lineTo(200,200); //p2
p.lineTo(100,200); //p3
p.close();
</code>```

Body:
I have a problem filling a path drawn on a canvas.
I read all those previous questions saying

Paint red = new Paint();
red.setColor(Color.RED);
red.setStyle(Paint.Style.FILL_AND_STROKE);

should be the way it works. Then I drew my Path like

Path p = new Path();
p.moveTo(100,100); //point1
p.lineTo(200,200);
p.moveTo(200,200); //point2
p.lineTo(100,200);
p.moveTo(100,200); //point3
p.lineTo(100,100);
p.close();

Which should be a closed path in my opinion.
After canvas.drawPath(p, red);
the triangle/path is drawn but not filled although style is FILL_AND_STROKE.
What am I getting wrong?

Body:
There is no path to fill because your path consists of multiple lines, but no coherent polygon. See moveTo documentation, which reads:

Set the beginning of the next contour to the point (x,y).

So by calling moveTo you are only drawing lines.

Only use lineTo(), which also "moves" to the target position. And you can skip the last lineTo() going to the point of origin, close() will do this automatically.

// create a triangle
Path p = new Path();
p.moveTo(100,100); //p1
p.lineTo(200,200); //p2
p.lineTo(100,200); //p3
p.close();


问:
Why is ARG in a DOCKERFILE not recommended for passing secrets?
In http://docs.docker.com/engine/reference/builder/#arg , It recommendeds secrets are not passed through ARGS.

Note: It is not recommended to use build-time variables for passing secrets like github keys, user credentials etc.

At what point are secrets passed through build-time variables in danger?

答:
I think the new (17.05) docker feature Multi-stage Builds (https://docs.docker.com/engine/userguide/eng-image/multistage-build/) mitigates these (valid) concerns about simply using --build-arg.

```<code>FROM mybuildertools
ADD my-git-creds /root/.ssh
RUN git clone git@bitbucket.org:example/foo /src
FROM mybuildertools
COPY --from=0 /src /src
RUN ...build /src with no git credentials ending up in final image...
</code>```

Unfortunately there doesn't seem to be an easy way to allow subsequent rebuilds (e.g. changes to the build step in the Dockerfile) unless you have the "my-git-creds" directory.

Body:
I think the new (17.05) docker feature Multi-stage Builds (https://docs.docker.com/engine/userguide/eng-image/multistage-build/) mitigates these (valid) concerns about simply using --build-arg.

FROM mybuildertools
ADD my-git-creds /root/.ssh
RUN git clone git@bitbucket.org:example/foo /src
FROM mybuildertools
COPY --from=0 /src /src
RUN ...build /src with no git credentials ending up in final image...

Unfortunately there doesn't seem to be an easy way to allow subsequent rebuilds (e.g. changes to the build step in the Dockerfile) unless you have the "my-git-creds" directory.


问:
For Loop not looping and detecting Char Array [Pointers and Char Arrays]
Basically, the code is asking for a user input. I type in the word hotkdog and I would like to use the function FindIndexOfCharacter 'k', which is 3. However, the function is always returning -1, so I guess my loop isn't being ++i for some reason??   </p>

```<code>#include <iostream>
#include <cstring>
#include <string>

void ReadString(char * c, int maxLength);
int FindIndexOfCharacter(char * c, char testVal);

int main()
{
    const int SIZE = 10;
    char ca[SIZE];
    char * cpointer = ca;

    ReadString(cpointer, 10);
    std::cout << FindIndexOfCharacter(cpointer, 'k');
    system("pause");
}

void ReadString(char * c, int Length)
{
    std::cout << "Enter a string " << Length << " characters." << std::endl;
    std::cin >> c;
}

int FindIndexOfCharacter(char * c, char Val)
{
    int sizeOfArray2 = std::strlen(c);
    std::cout << sizeOfArray2 << std::endl; // this confirms array size

    for (int i = 0; i < sizeOfArray2; ++i)
    {
        if (c[i] == Val)
            return i;
        else
            return -1;
    }
}
</code>```

答:
```<code>for (int i = 0; i < sizeOfArray2; ++i)
{
    if (c[i] == Val)
        return i;
    else
        return -1;
}
</code>```

You're only checking the first character. If it doesn't match, you return -1 right away.

Instead you need to proceed to the next character.

Perhaps try:

```<code>for (int i = 0; i < sizeOfArray2; ++i)
{
    if (c[i] == Val)
        return i;
}

return -1;
</code>```

Body:
Basically, the code is asking for a user input. I type in the word hotkdog and I would like to use the function FindIndexOfCharacter 'k', which is 3. However, the function is always returning -1, so I guess my loop isn't being ++i for some reason??

#include <iostream>
#include <cstring>
#include <string>

void ReadString(char * c, int maxLength);
int FindIndexOfCharacter(char * c, char testVal);

int main()
{
    const int SIZE = 10;
    char ca[SIZE];
    char * cpointer = ca;

    ReadString(cpointer, 10);
    std::cout << FindIndexOfCharacter(cpointer, 'k');
    system("pause");
}

void ReadString(char * c, int Length)
{
    std::cout << "Enter a string " << Length << " characters." << std::endl;
    std::cin >> c;
}

int FindIndexOfCharacter(char * c, char Val)
{
    int sizeOfArray2 = std::strlen(c);
    std::cout << sizeOfArray2 << std::endl; // this confirms array size

    for (int i = 0; i < sizeOfArray2; ++i)
    {
        if (c[i] == Val)
            return i;
        else
            return -1;
    }
}

Body:
for (int i = 0; i < sizeOfArray2; ++i)
{
    if (c[i] == Val)
        return i;
    else
        return -1;
}

You're only checking the first character. If it doesn't match, you return -1 right away.

Instead you need to proceed to the next character.

Perhaps try:

for (int i = 0; i < sizeOfArray2; ++i)
{
    if (c[i] == Val)
        return i;
}

return -1;


问:
writing to columns in same row in csv file (python)
Im trying to write values to a csv file such that for every two iterations, the result is in the same row and then the next the values print to a new row. Any help would be greatly appreciated. Thank you!
This is what I have so far:

```<code>import csv
import math
savePath = '/home/dehaoliu/opencv_test/Engineering_drawings_outputs/'

with open(str(savePath) +'outputsTest.csv','w') as f1:
        writer=csv.writer(f1, delimiter='\t',lineterminator='\n',)
        temp = []
 for k in range(0,2):
        temp = []
       for i in range(0,4):
            a = 2 +i
            b = 3+ i
            list = [a,b]
            temp.append(list)
       writer.writerow(temp)
</code>```

The result I am getting now is

```<code>[2 3][3 4][4 5][5 6]
[2 3][3 4][4 5][5 6]
</code>```

But I would like to get this (without the brackets) where each number in a row is in a separate column:

```<code>2 3 3 4
4 5 5 6
</code>```

答:
The way you present it you can do it with a simple seed and increment:

```<code>import csv
import os

save_path = "/home/dehaoliu/opencv_test/Engineering_drawings_outputs/"

with open(os.path.join(save_path, "outputsTest.csv"), "w") as f:
    writer = csv.writer(f, delimiter="\t", lineterminator="\n")
    temp = [2, 3, 3, 4]  # init seed
    increment = len(temp) // 2  # how many pairs we have, used to increase our seed each row
    for _ in range(2):  # how many rows do you need, any positive integer will do
        writer.writerow(temp)  # write the current value
        temp = [x + increment for x in temp]  # add 'increment' to the elements
</code>```

Resulting in:

```
2   3   3   4
4   5   5   6```

But if your seed is: temp = [2, 3, 3, 4, 4, 5] and you decide to generate 4 rows, it will still adapt:

```
2   3   3   4   4   5
5   6   6   7   7   8
8   9   9   10  10  11
11  12  12  13  13  14```

Body:
Im trying to write values to a csv file such that for every two iterations, the result is in the same row and then the next the values print to a new row. Any help would be greatly appreciated. Thank you!
This is what I have so far:

import csv
import math
savePath = '/home/dehaoliu/opencv_test/Engineering_drawings_outputs/'

with open(str(savePath) +'outputsTest.csv','w') as f1:
        writer=csv.writer(f1, delimiter='\t',lineterminator='\n',)
        temp = []
 for k in range(0,2):
        temp = []
       for i in range(0,4):
            a = 2 +i
            b = 3+ i
            list = [a,b]
            temp.append(list)
       writer.writerow(temp)

The result I am getting now is

[2 3][3 4][4 5][5 6]
[2 3][3 4][4 5][5 6]

But I would like to get this (without the brackets) where each number in a row is in a separate column:

2 3 3 4
4 5 5 6

Body:
The way you present it you can do it with a simple seed and increment:

import csv
import os

save_path = "/home/dehaoliu/opencv_test/Engineering_drawings_outputs/"

with open(os.path.join(save_path, "outputsTest.csv"), "w") as f:
    writer = csv.writer(f, delimiter="\t", lineterminator="\n")
    temp = [2, 3, 3, 4]  # init seed
    increment = len(temp) // 2  # how many pairs we have, used to increase our seed each row
    for _ in range(2):  # how many rows do you need, any positive integer will do
        writer.writerow(temp)  # write the current value
        temp = [x + increment for x in temp]  # add 'increment' to the elements

Resulting in:

2   3   3   4
4   5   5   6

But if your seed is: temp = [2, 3, 3, 4, 4, 5] and you decide to generate 4 rows, it will still adapt:

2   3   3   4   4   5
5   6   6   7   7   8
8   9   9   10  10  11
11  12  12  13  13  14


问:
Angular 2 Testing with Karma/Jasmine : Enable view of spec.ts files in Chrome
Does anyone if there is a more detailed blog post or video review dissecting the makeup of the configuration of the project that gets talked about in the The first karma test (1st-specs.testing.zip)?

I say this because if you setup an Angular project normally with ng new it sets up karma so you can run ng test, instead of the scripted npm test configured in the package.json of 1st-specs.testing.zip.

1st-specs.testing.zip is much better than ng test though, because it allows you to view spec.ts files and even set breakpoints on the test scripts and halt execution to interrogate things in the Chrome browser.

There is an awful lot of configuration going on in that example that I'm currently struggling to get my head around. I don't know specifically what part enables viewing the spec.ts files in Chrome.

Does anyone know:

what part enables that functionality, or

who wrote that code, so I could perhaps go Google their blog?

Nicer still, would be having this functionality baked into a project created by ng new!

答:
This problem has been addressed and a fix is on the way. If you apply the changes yourself, it will work again with the current CLI generated project:
fix(@angular/cli): use inline sourcemaps in test


问:
angularjs $setValidity from a directive not updating
I am trying to build a custom directive (based on an example I saw) to ensure that the confirm password is correct.
I am running into some trouble with the $setValidity tag, although all my console.log() execute and print out, it does not seem that the validity is being updated. Pass stays true even when I read in my console "set to false".
I made sure the name and the ng-model are the same and I also tried using scope.$apply, but that would comeout with an error saying i was trying to apply when something else is being applied.

Here is my code:
HTML

```<code><form ng-submit="signup()" name="profileForm">

            <div class="form-group">
              <label class="form-label" for="input-example-2">Password</label>
              <input class="form-input" ng-model="pnew" type="password" name="pnew" placeholder="Password" required>
            </div>
            <div class="form-group">
              <label class="form-label" for="input-example-2">Confirm Password</label>
              <input class="form-input" name="confirm" ng-model="confirm" type="password"  placeholder="Password" required pwcheck>
            </div>
            {{profileForm.confrim.$error.pass}}
            <hr>
            {{profileForm.confirm.$error}}
            <hr>
            {{profileForm.confirm.$valid}}
            <span ng-show="profileForm.confirm.$error.pwCheck"> the passwords dont match</span>
            <div class="form-group">
              <button class="btn btn-primary">Sign up</button>
            </div>
          </form>
</code>```

JS code for the pwcheck directive

```<code>.directive('pwcheck', function() {
  return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {
      function valid(value){
          scope.$watch("confirm", function(newval, oldval){
            console.log(value);
            console.log(scope.pnew);
              if(value==scope.pnew){
                console.log("success!");
                ctrl.$setValidity('pass', true);
                return value;
              }
              else {
                console.log("set to false");
                ctrl.$setValidity('pass', false);
                return undefined;
              }

          });
      }
      ctrl.$parsers.push(valid);
    }   } });
</code>```

答:
No need to use $watch on confirm if you're using your directive on same element & having ng-model in require. So your code can be

```<code>ctrl.$parsers.unshift(valid);
ctrl.$formatters.unshift(valid);

function valid(viewValue){
    console.log(viewValue);
    console.log(scope.pnew);
      if(viewValue==scope.pnew){
        console.log("success!");
        ctrl.$setValidity('pass', true);
        return viewValue;
      }
      else {
        console.log("set to false");
        ctrl.$setValidity('pass', false);
        return undefined;
      }
}
</code>```

Most trivial example plunk
https://plnkr.co/edit/vPbICfSCDnwHKh07DAXJ?p=preview

Body:
I am trying to build a custom directive (based on an example I saw) to ensure that the confirm password is correct.
I am running into some trouble with the $setValidity tag, although all my console.log() execute and print out, it does not seem that the validity is being updated. Pass stays true even when I read in my console "set to false".
I made sure the name and the ng-model are the same and I also tried using scope.$apply, but that would comeout with an error saying i was trying to apply when something else is being applied.

Here is my code:
HTML

<form ng-submit="signup()" name="profileForm">

              Password
              <input class="form-input" ng-model="pnew" type="password" name="pnew" placeholder="Password" required>

              Confirm Password
              <input class="form-input" name="confirm" ng-model="confirm" type="password"  placeholder="Password" required pwcheck>

            {{profileForm.confrim.$error.pass}}

            {{profileForm.confirm.$error}}

            {{profileForm.confirm.$valid}}
             the passwords dont match

              <button class="btn btn-primary">Sign up</button>

          </form>

JS code for the pwcheck directive

.directive('pwcheck', function() {
  return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {
      function valid(value){
          scope.$watch("confirm", function(newval, oldval){
            console.log(value);
            console.log(scope.pnew);
              if(value==scope.pnew){
                console.log("success!");
                ctrl.$setValidity('pass', true);
                return value;
              }
              else {
                console.log("set to false");
                ctrl.$setValidity('pass', false);
                return undefined;
              }

          });
      }
      ctrl.$parsers.push(valid);
    }   } });

Body:
No need to use $watch on confirm if you're using your directive on same element & having ng-model in require. So your code can be

ctrl.$parsers.unshift(valid);
ctrl.$formatters.unshift(valid);

function valid(viewValue){
    console.log(viewValue);
    console.log(scope.pnew);
      if(viewValue==scope.pnew){
        console.log("success!");
        ctrl.$setValidity('pass', true);
        return viewValue;
      }
      else {
        console.log("set to false");
        ctrl.$setValidity('pass', false);
        return undefined;
      }
}

Most trivial example plunk
https://plnkr.co/edit/vPbICfSCDnwHKh07DAXJ?p=preview


问:
Google KMS on AppEngine Dev Server - logging clutter

This is a known issue: https://issuetracker.google.com/issues/63253097

Further to my question about getting Google KMS working with App Engine, I'm opening a new question about a related but problematic side effect.

Namely, the Google Cloud API discovery appears to want to walk a number of paths outside the AppEngine sandbox.  This itself is not a problem, but it makes testing and debugging very problematic because each attempt is logged, producing hundreds of lines like the following:

INFO  03 Jul 2017 14:44:51  Sandbox prevented access to file "/Users"

INFO  03 Jul 2017 14:44:51  If it is a static file, check that application_readable: true is set in your app.yaml

INFO  03 Jul 2017 14:44:52  Sandbox prevented access to file "/usr/lib/Acrobat9/Resource/CMap"

INFO  03 Jul 2017 14:44:52  If it is a static file, check that application_readable: true is set in your app.yaml

INFO  03 Jul 2017 14:44:52  Sandbox prevented access to file "/usr/lib/Acrobat8/Resource/CMap"

INFO  03 Jul 2017 14:44:52  If it is a static file, check that application_readable: true is set in your app.yaml

Is there a way to disable or silence these requests or logs?

EDIT* One of the many results printed by adding traceback.print_stack() to log_access_check_fail in stub.py (sorry it's not very legible here):

Test #1: Sentry.io's Raven imports pkg_resources

```<code>  File "/Users/bmh/testapp/application.py", line 3, in <module>
    from nassau.application import app, sentry
  File "/Users/bmh/testapp/nassau/application.py", line 28, in <module>
    from raven.contrib.flask import Sentry
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/raven/__init__.py", line 16, in <module>
    VERSION = __import__('pkg_resources') \
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3037, in <module>
    @_call_aside
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3021, in _call_aside
    f(*args, **kwargs)
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3050, in _initialize_master_working_set
    working_set = WorkingSet._build_master()
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 646, in _build_master
    ws = cls()
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 639, in __init__
    self.add_entry(entry)
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 695, in add_entry
    for dist in find_distributions(entry, True):
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 2006, in find_on_path
    path_item = _normalize_cached(path_item)
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 2217, in _normalize_cached
    _cache[filename] = result = normalize_path(filename)
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 2210, in normalize_path
    return os.path.normcase(os.path.realpath(filename))
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/posixpath.py", line 375, in realpath
    path, ok = _joinrealpath('', filename, {})
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/posixpath.py", line 400, in _joinrealpath
    if not islink(newpath):
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/posixpath.py", line 135, in islink
    st = os.lstat(path)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/stubs.py", line 286, in __call__
    log_access_check_fail(path)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/stubs.py", line 51, in log_access_check_fail
    traceback.print_stack()
</code>```

I removed the dependency on Sentry / Raven, but the stack traces continue, via:

Test #2: Flask imports pkgutil

```<code>  File "/Users/bmh/testapp/application.py", line 3, in <module>
    from nassau.application import app
  File "/Users/bmh/testapp/nassau/application.py", line 72, in <module>
    app = Flask('nassau')
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/flask/app.py", line 331, in __init__
    instance_path = self.auto_find_instance_path()
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/flask/app.py", line 622, in auto_find_instance_path
    prefix, package_path = find_package(self.import_name)
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/flask/helpers.py", line 661, in find_package
    loader = pkgutil.get_loader(root_mod_name)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pkgutil.py", line 464, in get_loader
    return find_loader(fullname)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pkgutil.py", line 475, in find_loader
    loader = importer.find_module(fullname)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pkgutil.py", line 184, in find_module
    path = [os.path.realpath(self.path)]
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/posixpath.py", line 375, in realpath
    path, ok = _joinrealpath('', filename, {})
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/posixpath.py", line 400, in _joinrealpath
    if not islink(newpath):
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/posixpath.py", line 135, in islink
    st = os.lstat(path)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/stubs.py", line 286, in __call__
    log_access_check_fail(path)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/stubs.py", line 51, in log_access_check_fail
    traceback.print_stack()
</code>```

There must be a better way to represent a stack trace on stack overflow :)

答:
For me, these messages appear to originate from a GAE (.local) file called stubs.py.

In my first case, stubs.py was looking for files that were not there. So you might want to check to see if  "/usr/lib/Acrobat8/Resource/CMap" actually exists. Then, starting with stubs.py, try to find out what file is trying to load it.

My project is using web.py, all of a sudden I started getting (stubs.py) messages again, this time about .pyc files. I put a skip_files: in the bottom of my app.yaml file, and it does suppress the messages, but I haven't tested to see if my app still fully compiles.

```<code>skip_files:
- ^(.*/)?\.pyc$
</code>```

More on the Python GAE runtime and sandbox here.
https://cloud.google.com/appengine/docs/standard/python/runtime

Body:
This is a known issue: https://issuetracker.google.com/issues/63253097

Further to my question about getting Google KMS working with App Engine, I'm opening a new question about a related but problematic side effect.

Namely, the Google Cloud API discovery appears to want to walk a number of paths outside the AppEngine sandbox.  This itself is not a problem, but it makes testing and debugging very problematic because each attempt is logged, producing hundreds of lines like the following:

INFO  03 Jul 2017 14:44:51  Sandbox prevented access to file "/Users"

INFO  03 Jul 2017 14:44:51  If it is a static file, check that application_readable: true is set in your app.yaml

INFO  03 Jul 2017 14:44:52  Sandbox prevented access to file "/usr/lib/Acrobat9/Resource/CMap"

INFO  03 Jul 2017 14:44:52  If it is a static file, check that application_readable: true is set in your app.yaml

INFO  03 Jul 2017 14:44:52  Sandbox prevented access to file "/usr/lib/Acrobat8/Resource/CMap"

INFO  03 Jul 2017 14:44:52  If it is a static file, check that application_readable: true is set in your app.yaml

Is there a way to disable or silence these requests or logs?

EDIT* One of the many results printed by adding traceback.print_stack() to log_access_check_fail in stub.py (sorry it's not very legible here):

Test #1: Sentry.io's Raven imports pkg_resources

  File "/Users/bmh/testapp/application.py", line 3, in <module>
    from nassau.application import app, sentry
  File "/Users/bmh/testapp/nassau/application.py", line 28, in <module>
    from raven.contrib.flask import Sentry
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/raven/__init__.py", line 16, in <module>
    VERSION = __import__('pkg_resources') \
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3037, in <module>
    @_call_aside
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3021, in _call_aside
    f(*args, **kwargs)
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3050, in _initialize_master_working_set
    working_set = WorkingSet._build_master()
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 646, in _build_master
    ws = cls()
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 639, in __init__
    self.add_entry(entry)
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 695, in add_entry
    for dist in find_distributions(entry, True):
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 2006, in find_on_path
    path_item = _normalize_cached(path_item)
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 2217, in _normalize_cached
    _cache[filename] = result = normalize_path(filename)
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/pkg_resources/__init__.py", line 2210, in normalize_path
    return os.path.normcase(os.path.realpath(filename))
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/posixpath.py", line 375, in realpath
    path, ok = _joinrealpath('', filename, {})
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/posixpath.py", line 400, in _joinrealpath
    if not islink(newpath):
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/posixpath.py", line 135, in islink
    st = os.lstat(path)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/stubs.py", line 286, in __call__
    log_access_check_fail(path)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/stubs.py", line 51, in log_access_check_fail
    traceback.print_stack()

I removed the dependency on Sentry / Raven, but the stack traces continue, via:

Test #2: Flask imports pkgutil

  File "/Users/bmh/testapp/application.py", line 3, in <module>
    from nassau.application import app
  File "/Users/bmh/testapp/nassau/application.py", line 72, in <module>
    app = Flask('nassau')
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/flask/app.py", line 331, in __init__
    instance_path = self.auto_find_instance_path()
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/flask/app.py", line 622, in auto_find_instance_path
    prefix, package_path = find_package(self.import_name)
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/site-packages/flask/helpers.py", line 661, in find_package
    loader = pkgutil.get_loader(root_mod_name)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pkgutil.py", line 464, in get_loader
    return find_loader(fullname)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pkgutil.py", line 475, in find_loader
    loader = importer.find_module(fullname)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pkgutil.py", line 184, in find_module
    path = [os.path.realpath(self.path)]
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/posixpath.py", line 375, in realpath
    path, ok = _joinrealpath('', filename, {})
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/posixpath.py", line 400, in _joinrealpath
    if not islink(newpath):
  File "/Users/bmh/testapp/python-virtualenv/lib/python2.7/posixpath.py", line 135, in islink
    st = os.lstat(path)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/stubs.py", line 286, in __call__
    log_access_check_fail(path)
  File "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/stubs.py", line 51, in log_access_check_fail
    traceback.print_stack()

There must be a better way to represent a stack trace on stack overflow :)

Body:
For me, these messages appear to originate from a GAE (.local) file called stubs.py.

In my first case, stubs.py was looking for files that were not there. So you might want to check to see if  "/usr/lib/Acrobat8/Resource/CMap" actually exists. Then, starting with stubs.py, try to find out what file is trying to load it.

My project is using web.py, all of a sudden I started getting (stubs.py) messages again, this time about .pyc files. I put a skip_files: in the bottom of my app.yaml file, and it does suppress the messages, but I haven't tested to see if my app still fully compiles.

skip_files:
- ^(.*/)?\.pyc$

More on the Python GAE runtime and sandbox here.
https://cloud.google.com/appengine/docs/standard/python/runtime


问:
Xamarin.Android support for OxygenOS
I am doing some research on running Xamarin.Android apps on OxygenOS (https://en.wikipedia.org/wiki/OxygenOS). Unfortunately, information online is scarce on the subject.

Appreciate thoughts on the subject. Specifically suggestions around following 2 questions:

Will Xamarin.Android apps work on OxygenOS?

If yes to the query above, are there any compatibility issues that one needs to be aware off?

Appreciate your help!

Cheers

答:
After some research and web crawling, turns out OxygenOS, at least for now, will support any android app. It is essentially a custom ROM, as some blog post has suggested.

Reference

https://forums.oneplus.net/threads/closed-does-oxygenos-supports-android-apps.329802/

https://www.xda-developers.com/everything-oxygenos-what-we-know-what-to-expect/

https://en.wikipedia.org/wiki/OxygenOS

Title: Xamarin.Android support for OxygenOS


问:
Are string literals const?
Both GCC and Clang do not complain if I assign a string literal to a char*, even when using lots of pedantic options (-Wall -W -pedantic -std=c99):

```<code>char *foo = "bar";
</code>```

while they (of course) do complain if I assign a const char* to a char*.

Does this mean that string literals are considered to be of char* type? Shouldn't they be const char*? It's not defined behavior if they get modified!

And (an uncorrelated question) what about command line parameters (ie: argv): is it considered to be an array of string literals?

答:
They are of type char[N] where N is the number of characters including the terminating \0. So yes you can assign them to char*, but you still cannot write to them (the effect will be undefined).

Wrt argv: It points to an array of pointers to strings. Those strings are explicitly modifiable. You can change them and they are required to hold the last stored value.

Title: Are string literals const?

Body:
Both GCC and Clang do not complain if I assign a string literal to a char*, even when using lots of pedantic options (-Wall -W -pedantic -std=c99):

char *foo = "bar";

while they (of course) do complain if I assign a const char* to a char*.

Does this mean that string literals are considered to be of char* type? Shouldn't they be const char*? It's not defined behavior if they get modified!

And (an uncorrelated question) what about command line parameters (ie: argv): is it considered to be an array of string literals?


问:
Not able to get all songs from a device on Android
I'm trying to learn how to develop an Android app and I found a very useful tutorial on the web which was trying to create a simple music player.

Even though I followed it, I've got a problem:
When I try to run the app, I don't get any error in the compiler, but on the emulator the app won't start with the following error message:

Unfortunately, MusicPlayer has stopped.

This is the code:

```<code>public class MainActivity extends AppCompatActivity {
private ArrayList<Song> songList;
private ListView songView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    songView = (ListView) findViewById(R.id.song_list);
    songList = new ArrayList<Song>();
    getSongList();
}

public void getSongList(){
    // retrieve song info
    ContentResolver musicResolver = getContentResolver();
    Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
    if(musicCursor!=null && musicCursor.moveToFirst()){
        //get columns

        int titleColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media.TITLE);
        int idColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media._ID);
        int artistColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media.ARTIST);
        //add songs to list
        do {
            long thisId = musicCursor.getLong(idColumn);
            String thisTitle = musicCursor.getString(titleColumn);
            String thisArtist = musicCursor.getString(artistColumn);
            songList.add(new Song(thisId, thisTitle, thisArtist));
        }
        while (musicCursor.moveToNext());
    }
}
</code>```

}

After reviewing the code a bit, I found out that the app crashes when I call the following command:

```<code>Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
</code>```

Any idea of what's the problem?

答: Have you granted permission to read external storage?</p>

Body:
I'm trying to learn how to develop an Android app and I found a very useful tutorial on the web which was trying to create a simple music player.

Even though I followed it, I've got a problem:
When I try to run the app, I don't get any error in the compiler, but on the emulator the app won't start with the following error message:

Unfortunately, MusicPlayer has stopped.

This is the code:

public class MainActivity extends AppCompatActivity {
private ArrayList<Song> songList;
private ListView songView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    songView = (ListView) findViewById(R.id.song_list);
    songList = new ArrayList<Song>();
    getSongList();
}

public void getSongList(){
    // retrieve song info
    ContentResolver musicResolver = getContentResolver();
    Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
    if(musicCursor!=null && musicCursor.moveToFirst()){
        //get columns

        int titleColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media.TITLE);
        int idColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media._ID);
        int artistColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media.ARTIST);
        //add songs to list
        do {
            long thisId = musicCursor.getLong(idColumn);
            String thisTitle = musicCursor.getString(titleColumn);
            String thisArtist = musicCursor.getString(artistColumn);
            songList.add(new Song(thisId, thisTitle, thisArtist));
        }
        while (musicCursor.moveToNext());
    }
}

}

After reviewing the code a bit, I found out that the app crashes when I call the following command:

Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);

Any idea of what's the problem?


问:
shapes not compatible issue when running optimizer step in tensorflow image segmentation
I am performing an image segmentation task in tensorflow.

Code:

```<code>height = 1024
width = 1024
channels = 1

# input place holders
X = tf.placeholder(tf.float32, [None, height, width, channels], name = 'image')

Y = tf.placeholder(tf.float32, [None, height, width, channels], name = 'annotation')

# variable learning rate
lr = tf.placeholder(tf.float32, name = 'lr')

W1 = tf.Variable(tf.truncated_normal([3, 3, 1, 2], stddev=0.1))
B1 = tf.Variable(tf.ones([2])/(2*2))

W2 = tf.Variable(tf.truncated_normal([3, 3, 2, 1], stddev=0.1))
B2 = tf.Variable(tf.ones([1])/(1*1))

W3 = tf.Variable(tf.truncated_normal([2, 2, 1, 1], stddev=0.1))
B3 = tf.Variable(tf.ones([1])/(1*1))

stride = 1
Y1 = tf.nn.relu(tf.nn.conv2d(X, W1, strides=[1, stride, stride, 1], padding= 'VALID') + B1)

stride = 1
Y2 = tf.nn.relu(tf.nn.conv2d(Y1, W2, strides=[1, stride, stride, 1], padding='VALID') + B2)

Ylogits = tf.nn.conv2d_transpose(Y2, W3, output_shape = [1, 1024, 1024, 1], strides = [1, 2, 2, 1])
</code>```

Everything is good except when I run this line :

train_step = tf.train.GradientDescentOptimizer(learning_rate=lr).minimize(cross_entropy_sum)

Traceback:

train_step =
tf.train.GradientDescentOptimizer(learning_rate=lr).minimize(cross_entropy_sum)

```<code>File "/home/anaconda/lib/python2.7/site-packages/tensorflow/python/training/optimizer.py", line 315, in minimize
    grad_loss=grad_loss)
  File "/home/anaconda/lib/python2.7/site-packages/tensorflow/python/training/optimizer.py", line 386, in compute_gradients
    colocate_gradients_with_ops=colocate_gradients_with_ops)
  File "/home/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/gradients_impl.py", line 580, in gradients
    in_grad.set_shape(t_in.get_shape())
  File "/home/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 413, in set_shape
    self._shape = self._shape.merge_with(shape)
  File "/home/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/tensor_shape.py", line 564, in merge_with
    (self, other))
ValueError: Shapes (1, 512, 512, 1) and (?, 1020, 1020, 1) are not compatible
</code>```

答:
Because the strides on your conv2d_transpose operation are [1, 2, 2, 1], it will result in an output with twice the height and width of the input. See this Data Science answer and the page it links here for visualizations of why this happens.

You set your output_shape = [1, 1024, 1024, 1], and the deconvolutional layer expects half the height and width as input, and the same batch size and number of channels, which means it expects a shape of [1, 512, 512, 1].

The input you gave it, Y2, is of shape [None, 1020, 1020, 1], because the two conv2d layers each trim off a little around the edges of your data, but because the stride is one, they do not significantly decrease the width or height. The batch size is None because it stays the same through those layers.

To fix this, one option is to use a stride of [1, 2, 2, 1] on one of your convolutional layers, which will roughly halve the width and height (To exactly halve them, use padding='SAME'. This will prevent the edges from being slightly trimmed). You'll also have to change the output_shape of the deconvolutional layer to [None, 1024, 1024, 1].

Body:
I am performing an image segmentation task in tensorflow.

Code:

height = 1024
width = 1024
channels = 1

# input place holders
X = tf.placeholder(tf.float32, [None, height, width, channels], name = 'image')

Y = tf.placeholder(tf.float32, [None, height, width, channels], name = 'annotation')

# variable learning rate
lr = tf.placeholder(tf.float32, name = 'lr')

W1 = tf.Variable(tf.truncated_normal([3, 3, 1, 2], stddev=0.1))
B1 = tf.Variable(tf.ones([2])/(2*2))

W2 = tf.Variable(tf.truncated_normal([3, 3, 2, 1], stddev=0.1))
B2 = tf.Variable(tf.ones([1])/(1*1))

W3 = tf.Variable(tf.truncated_normal([2, 2, 1, 1], stddev=0.1))
B3 = tf.Variable(tf.ones([1])/(1*1))

stride = 1
Y1 = tf.nn.relu(tf.nn.conv2d(X, W1, strides=[1, stride, stride, 1], padding= 'VALID') + B1)

stride = 1
Y2 = tf.nn.relu(tf.nn.conv2d(Y1, W2, strides=[1, stride, stride, 1], padding='VALID') + B2)

Ylogits = tf.nn.conv2d_transpose(Y2, W3, output_shape = [1, 1024, 1024, 1], strides = [1, 2, 2, 1])

Everything is good except when I run this line :

train_step = tf.train.GradientDescentOptimizer(learning_rate=lr).minimize(cross_entropy_sum)

Traceback:

train_step =
tf.train.GradientDescentOptimizer(learning_rate=lr).minimize(cross_entropy_sum)

File "/home/anaconda/lib/python2.7/site-packages/tensorflow/python/training/optimizer.py", line 315, in minimize
    grad_loss=grad_loss)
  File "/home/anaconda/lib/python2.7/site-packages/tensorflow/python/training/optimizer.py", line 386, in compute_gradients
    colocate_gradients_with_ops=colocate_gradients_with_ops)
  File "/home/anaconda/lib/python2.7/site-packages/tensorflow/python/ops/gradients_impl.py", line 580, in gradients
    in_grad.set_shape(t_in.get_shape())
  File "/home/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 413, in set_shape
    self._shape = self._shape.merge_with(shape)
  File "/home/anaconda/lib/python2.7/site-packages/tensorflow/python/framework/tensor_shape.py", line 564, in merge_with
    (self, other))
ValueError: Shapes (1, 512, 512, 1) and (?, 1020, 1020, 1) are not compatible


问:
Django Grapelli add autocomplete lookups on InlineAdmin
I have this 3 models:

class MyFile(models.Model):
    file = models.FileField(upload_to="files/%Y/%m/%d")

    def __unicode__(self):
        """."""
        return "%s" % (
            self.file.name)

class ExampleModel(models.Model):
    attached_files =models.ManyToManyField(MyFile)
    main_model = models.ForeignKey(MainModel)

class MainModel(models.Model):
    attached_files =models.ManyToManyField(MyFile)
```

<p>And my <code>admin.py</code> as follows:</p>

<pre class="lang-python prettyprint-override"><code>class ExampleModelAdminInline(admin.TabularInline):
    model = ExampleModel
    extra = 2

class MainModelAdmin(admin.ModelAdmin):
    inlines = [ExampleModelAdminInline]
</code>```

Im using django-grapelli because it offer autocomplete lookups for many to many fields. However, Im not sure how to add this autocomplete lookup to a TabularInline admin. Can anyone explain me how to set up the attached_files field to have autocomplete lookups?

答:
First you need to set the static method autocomplete_search_fields() in the Model you want to search from, in your case MyFile. From the docs we get:

```<code>class MyFile(models.Model):
    #your variable declaration...

    @staticmethod
    def autocomplete_search_fields():
        return ("id__iexact", "name__icontains",) #the fields you want here
</code>```

You can also define GRAPPELLI_AUTOCOMPLETE_SEARCH_FIELDS instead of declaring the static method, like:

```<code>GRAPPELLI_AUTOCOMPLETE_SEARCH_FIELDS = {
    "myapp": {
        "MyFile": ("id__iexact", "name__icontains",)
    }
}
</code>```

Then you should add the lookup and raw fields to your desired admin class, considering its related Model (say, your  ExampleModel) which is the one that has a ManyToManyField. You can also handle ForeignKey in a similar way. Also from the mentioned docs:

```<code>class ExampleModel(models.Model):
    main_model = models.ForeignKey(MainModel) #some FK to other Model related
    attached_files =models.ManyToManyField(MyFile) #the one with static decl

class MainModelAdmin(admin.ModelAdmin):
    #your variable declaration...

    # define raw fields
    raw_id_fields = ('main_model','attached_files',)
    # define the autocomplete_lookup_fields
    autocomplete_lookup_fields = {
        'fk': ['main_model'],
        'm2m': ['attached_files'],
    }
</code>```

Remember to register both ends (your models) of the relationship to your admin.site, like this:

```<code>#the one with the m2m and the one with the lookup
admin.site.register(ExampleModel, MainModelAdmin)
</code>```

You can also check this question to understand better.

Body:
I have this 3 models:

class MyFile(models.Model):
    file = models.FileField(upload_to="files/%Y/%m/%d")

    def __unicode__(self):
        """."""
        return "%s" % (
            self.file.name)

class ExampleModel(models.Model):
    attached_files =models.ManyToManyField(MyFile)
    main_model = models.ForeignKey(MainModel)

class MainModel(models.Model):
    attached_files =models.ManyToManyField(MyFile)

And my admin.py as follows:

class ExampleModelAdminInline(admin.TabularInline):
    model = ExampleModel
    extra = 2

class MainModelAdmin(admin.ModelAdmin):
    inlines = [ExampleModelAdminInline]

Im using django-grapelli because it offer autocomplete lookups for many to many fields. However, Im not sure how to add this autocomplete lookup to a TabularInline admin. Can anyone explain me how to set up the attached_files field to have autocomplete lookups?

Body:
First you need to set the static method autocomplete_search_fields() in the Model you want to search from, in your case MyFile. From the docs we get:

class MyFile(models.Model):
    #your variable declaration...

    @staticmethod
    def autocomplete_search_fields():
        return ("id__iexact", "name__icontains",) #the fields you want here

You can also define GRAPPELLI_AUTOCOMPLETE_SEARCH_FIELDS instead of declaring the static method, like:

GRAPPELLI_AUTOCOMPLETE_SEARCH_FIELDS = {
    "myapp": {
        "MyFile": ("id__iexact", "name__icontains",)
    }
}

Then you should add the lookup and raw fields to your desired admin class, considering its related Model (say, your  ExampleModel) which is the one that has a ManyToManyField. You can also handle ForeignKey in a similar way. Also from the mentioned docs:

class ExampleModel(models.Model):
    main_model = models.ForeignKey(MainModel) #some FK to other Model related
    attached_files =models.ManyToManyField(MyFile) #the one with static decl

class MainModelAdmin(admin.ModelAdmin):
    #your variable declaration...

    # define raw fields
    raw_id_fields = ('main_model','attached_files',)
    # define the autocomplete_lookup_fields
    autocomplete_lookup_fields = {
        'fk': ['main_model'],
        'm2m': ['attached_files'],
    }

Remember to register both ends (your models) of the relationship to your admin.site, like this:

#the one with the m2m and the one with the lookup
admin.site.register(ExampleModel, MainModelAdmin)

You can also check this question to understand better.


问:
How can I ask setup.py to list dependencies?
I have a third-party package which has a setup.py file that calls setup() in the standard way, passing test_requires, install_requires and extras_require. (It does not use a requirements.txt file.)

I am running a Windows machine (on Appveyor) and pip install is notoriously poor on Windows with some of the packages. I would like to use Conda.

It seems to me, the ideal way to proceed is:

Ask setup.py to list the dependencies it needs, without taking any action.

Pass that list to conda to install.

Call setup.py with the install or test command, confident that it will check its requirements, and not find anything it needs to install.

I thought python setup.py --requires might do the trick, but it is poorly documented and is returning nothing.

If this a reasonable approach? If so, is there a way of asking setup.py to evaluated its dependencies, and list them without installing them.

答: python setup.py egg_info will write a package_name.egg-info/requires.txt file which contains the dependencies you want.


问:
How to display row values as column names?
I have three tables in below format:

```<code>Table_1 (Tax Types)

TaxTypeID   Code       Description  LocationID
 1          TaxA         DescA         1
 2          TaxB         DescB         1
 3          TaxC         DescB         1

Table_2 (Tax Plans)

PlanID    Name   Description   LocationID
 1        Plan1     Plan1          1

Table_3 (Cross Reference)

TaxTypeID   PlanID    TaxPercentage
   1           1          5.00
   2           1          7.00
</code>```

So I need to write a query which outputs below result when Plan_Id is passed and also by matching Table 1 and 2 LocationID:

```<code>PlanID  Name    TaxA   TaxB   TaxC
   1    Plan1   5.00   7.00   0.00
</code>```

If table_3 does not have cross reference between table_1 and table_2 percentage should be displayed as 0.00. Mainly I need to display rows in Table_1(tax types) as column names in my output and this should be dynamic, based on rows in Table_1(tax types). So, if a new tax type row "TaxD" is added, out should have a new column TaxD with 0.00 as percentage.

I know by using Pivot in SQL,we can get row values as column names and I tried below query

```<code>select *
from
(
select TaxTypeId,Code from Table_1  ) as p
pivot
(
max(Code)
for Code in ( [TaxA],[TaxB],[TaxC])
)as pvt
</code>```

But it is not close to what I need.

答:
You need to use max(TaxPercentage) instead of max(code) in pivot

```<code>select * from
(
SELECT c.planid,c.NAME,taxpercentage,a.Code
FROM   table_1 a
       JOIN table_3 b
         ON a.taxtypeid = b.taxtypeid
       JOIN table_2 c
         ON c.planid = b.planid
) as p
pivot
(
max(TaxPercentage)
for Code in ( [TaxA],[TaxB],[TaxC])
)as pvt
</code>```

If the values in code is not fixed then you need to use dynamic pivot

```<code>declare @sql varchar(8000),@col_list varchar(8000),@pivot_list varchar(8000)

set @col_list =stuff((select distinct  ',Coalesce('+ quotename(Code) + ',0) as '+ quotename(Code) from Table_1 for xml path('')),1,1,'')

set @pivot_list =stuff((select distinct  ','+quotename(Code) from Table_1 for xml path('')),1,1,'')

set @sql  = 'select * from
(
SELECT c.planid,c.NAME,taxpercentage,a.Code
FROM   table_1 a
       JOIN table_3 b
         ON a.taxtypeid = b.taxtypeid
       JOIN table_2 c
         ON c.planid = b.planid
) as p
pivot
(
max(TaxPercentage)
for Code in ( '+@pivot_list+')
)as pvt'
--print @sql
exec(@sql)
</code>```

Body:
I have three tables in below format:

Table_1 (Tax Types)

TaxTypeID   Code       Description  LocationID
 1          TaxA         DescA         1
 2          TaxB         DescB         1
 3          TaxC         DescB         1

Table_2 (Tax Plans)

PlanID    Name   Description   LocationID
 1        Plan1     Plan1          1

Table_3 (Cross Reference)

TaxTypeID   PlanID    TaxPercentage
   1           1          5.00
   2           1          7.00

So I need to write a query which outputs below result when Plan_Id is passed and also by matching Table 1 and 2 LocationID:

PlanID  Name    TaxA   TaxB   TaxC
   1    Plan1   5.00   7.00   0.00

If table_3 does not have cross reference between table_1 and table_2 percentage should be displayed as 0.00. Mainly I need to display rows in Table_1(tax types) as column names in my output and this should be dynamic, based on rows in Table_1(tax types). So, if a new tax type row "TaxD" is added, out should have a new column TaxD with 0.00 as percentage.

I know by using Pivot in SQL,we can get row values as column names and I tried below query

select *
from
(
select TaxTypeId,Code from Table_1  ) as p
pivot
(
max(Code)
for Code in ( [TaxA],[TaxB],[TaxC])
)as pvt

But it is not close to what I need.

Body:
You need to use max(TaxPercentage) instead of max(code) in pivot

select * from
(
SELECT c.planid,c.NAME,taxpercentage,a.Code
FROM   table_1 a
       JOIN table_3 b
         ON a.taxtypeid = b.taxtypeid
       JOIN table_2 c
         ON c.planid = b.planid
) as p
pivot
(
max(TaxPercentage)
for Code in ( [TaxA],[TaxB],[TaxC])
)as pvt

If the values in code is not fixed then you need to use dynamic pivot

declare @sql varchar(8000),@col_list varchar(8000),@pivot_list varchar(8000)

set @col_list =stuff((select distinct  ',Coalesce('+ quotename(Code) + ',0) as '+ quotename(Code) from Table_1 for xml path('')),1,1,'')

set @pivot_list =stuff((select distinct  ','+quotename(Code) from Table_1 for xml path('')),1,1,'')

set @sql  = 'select * from
(
SELECT c.planid,c.NAME,taxpercentage,a.Code
FROM   table_1 a
       JOIN table_3 b
         ON a.taxtypeid = b.taxtypeid
       JOIN table_2 c
         ON c.planid = b.planid
) as p
pivot
(
max(TaxPercentage)
for Code in ( '+@pivot_list+')
)as pvt'
--print @sql
exec(@sql)