问:
Porting range-slider widget to PyQt5
I am currently in need for a range slider (a slider where I can set up a min and a max value). I found two related questions Range slider in Qt (two handles in a QSlider) and Why RangeSlider is available in QtQuick and not as standard Widget but neither of them is written in python3 and I am not very familiar with C++.

I found this perfect github tool https://github.com/rsgalloway/qrangeslider but it is unfortunately written for PyQt4 and I am using PyQt5.

I am planning to reformat this github source with PyQt5 bindings but before doing so I want to know if anyone has done it before so I could save time?
Or if anyone has a different solution, I am open to suggestions.

答:
Below is a PyQt5 port of the QRangeSlider widget. For the sake of brevity, I have removed all comments, doc-strings, assert statements, etc. It seems to work okay with both Python 2 and Python 3, but I haven't really tested it much.

qrangeslider.py:

```<code>import sys, os
from PyQt5 import QtCore, QtGui, QtWidgets

__all__ = ['QRangeSlider']

DEFAULT_CSS = """
QRangeSlider * {
    border: 0px;
    padding: 0px;
}
QRangeSlider #Head {
    background: #222;
}
QRangeSlider #Span {
    background: #393;
}
QRangeSlider #Span:active {
    background: #282;
}
QRangeSlider #Tail {
    background: #222;
}
QRangeSlider > QSplitter::handle {
    background: #393;
}
QRangeSlider > QSplitter::handle:vertical {
    height: 4px;
}
QRangeSlider > QSplitter::handle:pressed {
    background: #ca5;
}
"""

def scale(val, src, dst):
    return int(((val - src[0]) / float(src[1]-src[0])) * (dst[1]-dst[0]) + dst[0])

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("QRangeSlider")
        Form.resize(300, 30)
        Form.setStyleSheet(DEFAULT_CSS)
        self.gridLayout = QtWidgets.QGridLayout(Form)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setSpacing(0)
        self.gridLayout.setObjectName("gridLayout")
        self._splitter = QtWidgets.QSplitter(Form)
        self._splitter.setMinimumSize(QtCore.QSize(0, 0))
        self._splitter.setMaximumSize(QtCore.QSize(16777215, 16777215))
        self._splitter.setOrientation(QtCore.Qt.Horizontal)
        self._splitter.setObjectName("splitter")
        self._head = QtWidgets.QGroupBox(self._splitter)
        self._head.setTitle("")
        self._head.setObjectName("Head")
        self._handle = QtWidgets.QGroupBox(self._splitter)
        self._handle.setTitle("")
        self._handle.setObjectName("Span")
        self._tail = QtWidgets.QGroupBox(self._splitter)
        self._tail.setTitle("")
        self._tail.setObjectName("Tail")
        self.gridLayout.addWidget(self._splitter, 0, 0, 1, 1)
        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("QRangeSlider", "QRangeSlider"))

class Element(QtWidgets.QGroupBox):
    def __init__(self, parent, main):
        super(Element, self).__init__(parent)
        self.main = main

    def setStyleSheet(self, style):
        self.parent().setStyleSheet(style)

    def textColor(self):
        return getattr(self, '__textColor', QtGui.QColor(125, 125, 125))

    def setTextColor(self, color):
        if type(color) == tuple and len(color) == 3:
            color = QtGui.QColor(color[0], color[1], color[2])
        elif type(color) == int:
            color = QtGui.QColor(color, color, color)
        setattr(self, '__textColor', color)

    def paintEvent(self, event):
        qp = QtGui.QPainter()
        qp.begin(self)
        if self.main.drawValues():
            self.drawText(event, qp)
        qp.end()

class Head(Element):
    def __init__(self, parent, main):
        super(Head, self).__init__(parent, main)

    def drawText(self, event, qp):
        qp.setPen(self.textColor())
        qp.setFont(QtGui.QFont('Arial', 10))
        qp.drawText(event.rect(), QtCore.Qt.AlignLeft, str(self.main.min()))

class Tail(Element):
    def __init__(self, parent, main):
        super(Tail, self).__init__(parent, main)

    def drawText(self, event, qp):
        qp.setPen(self.textColor())
        qp.setFont(QtGui.QFont('Arial', 10))
        qp.drawText(event.rect(), QtCore.Qt.AlignRight, str(self.main.max()))

class Handle(Element):
    def __init__(self, parent, main):
        super(Handle, self).__init__(parent, main)

    def drawText(self, event, qp):
        qp.setPen(self.textColor())
        qp.setFont(QtGui.QFont('Arial', 10))
        qp.drawText(event.rect(), QtCore.Qt.AlignLeft, str(self.main.start()))
        qp.drawText(event.rect(), QtCore.Qt.AlignRight, str(self.main.end()))

    def mouseMoveEvent(self, event):
        event.accept()
        mx = event.globalX()
        _mx = getattr(self, '__mx', None)
        if not _mx:
            setattr(self, '__mx', mx)
            dx = 0
        else:
            dx = mx - _mx
        setattr(self, '__mx', mx)
        if dx == 0:
            event.ignore()
            return
        elif dx > 0:
            dx = 1
        elif dx < 0:
            dx = -1
        s = self.main.start() + dx
        e = self.main.end() + dx
        if s >= self.main.min() and e <= self.main.max():
            self.main.setRange(s, e)

class QRangeSlider(QtWidgets.QWidget, Ui_Form):
    endValueChanged = QtCore.pyqtSignal(int)
    maxValueChanged = QtCore.pyqtSignal(int)
    minValueChanged = QtCore.pyqtSignal(int)
    startValueChanged = QtCore.pyqtSignal(int)
    minValueChanged = QtCore.pyqtSignal(int)
    maxValueChanged = QtCore.pyqtSignal(int)
    startValueChanged = QtCore.pyqtSignal(int)
    endValueChanged = QtCore.pyqtSignal(int)

    _SPLIT_START = 1
    _SPLIT_END = 2

    def __init__(self, parent=None):
        super(QRangeSlider, self).__init__(parent)
        self.setupUi(self)
        self.setMouseTracking(False)
        self._splitter.splitterMoved.connect(self._handleMoveSplitter)
        self._head_layout = QtWidgets.QHBoxLayout()
        self._head_layout.setSpacing(0)
        self._head_layout.setContentsMargins(0, 0, 0, 0)
        self._head.setLayout(self._head_layout)
        self.head = Head(self._head, main=self)
        self._head_layout.addWidget(self.head)
        self._handle_layout = QtWidgets.QHBoxLayout()
        self._handle_layout.setSpacing(0)
        self._handle_layout.setContentsMargins(0, 0, 0, 0)
        self._handle.setLayout(self._handle_layout)
        self.handle = Handle(self._handle, main=self)
        self.handle.setTextColor((150, 255, 150))
        self._handle_layout.addWidget(self.handle)
        self._tail_layout = QtWidgets.QHBoxLayout()
        self._tail_layout.setSpacing(0)
        self._tail_layout.setContentsMargins(0, 0, 0, 0)
        self._tail.setLayout(self._tail_layout)
        self.tail = Tail(self._tail, main=self)
        self._tail_layout.addWidget(self.tail)
        self.setMin(0)
        self.setMax(99)
        self.setStart(0)
        self.setEnd(99)
        self.setDrawValues(True)

    def min(self):
        return getattr(self, '__min', None)

    def max(self):
        return getattr(self, '__max', None)

    def setMin(self, value):
        setattr(self, '__min', value)
        self.minValueChanged.emit(value)

    def setMax(self, value):
        setattr(self, '__max', value)
        self.maxValueChanged.emit(value)

    def start(self):
        return getattr(self, '__start', None)

    def end(self):
        return getattr(self, '__end', None)

    def _setStart(self, value):
        setattr(self, '__start', value)
        self.startValueChanged.emit(value)

    def setStart(self, value):
        v = self._valueToPos(value)
        self._splitter.splitterMoved.disconnect()
        self._splitter.moveSplitter(v, self._SPLIT_START)
        self._splitter.splitterMoved.connect(self._handleMoveSplitter)
        self._setStart(value)

    def _setEnd(self, value):
        setattr(self, '__end', value)
        self.endValueChanged.emit(value)

    def setEnd(self, value):
        v = self._valueToPos(value)
        self._splitter.splitterMoved.disconnect()
        self._splitter.moveSplitter(v, self._SPLIT_END)
        self._splitter.splitterMoved.connect(self._handleMoveSplitter)
        self._setEnd(value)

    def drawValues(self):
        return getattr(self, '__drawValues', None)

    def setDrawValues(self, draw):
        setattr(self, '__drawValues', draw)

    def getRange(self):
        return (self.start(), self.end())

    def setRange(self, start, end):
        self.setStart(start)
        self.setEnd(end)

    def keyPressEvent(self, event):
        key = event.key()
        if key == QtCore.Qt.Key_Left:
            s = self.start()-1
            e = self.end()-1
        elif key == QtCore.Qt.Key_Right:
            s = self.start()+1
            e = self.end()+1
        else:
            event.ignore()
            return
        event.accept()
        if s >= self.min() and e <= self.max():
            self.setRange(s, e)

    def setBackgroundStyle(self, style):
        self._tail.setStyleSheet(style)
        self._head.setStyleSheet(style)

    def setSpanStyle(self, style):
        self._handle.setStyleSheet(style)

    def _valueToPos(self, value):
        return scale(value, (self.min(), self.max()), (0, self.width()))

    def _posToValue(self, xpos):
        return scale(xpos, (0, self.width()), (self.min(), self.max()))

    def _handleMoveSplitter(self, xpos, index):
        hw = self._splitter.handleWidth()
        def _lockWidth(widget):
            width = widget.size().width()
            widget.setMinimumWidth(width)
            widget.setMaximumWidth(width)
        def _unlockWidth(widget):
            widget.setMinimumWidth(0)
            widget.setMaximumWidth(16777215)
        v = self._posToValue(xpos)
        if index == self._SPLIT_START:
            _lockWidth(self._tail)
            if v >= self.end():
                return
            offset = -20
            w = xpos + offset
            self._setStart(v)
        elif index == self._SPLIT_END:
            _lockWidth(self._head)
            if v <= self.start():
                return
            offset = -40
            w = self.width() - xpos + offset
            self._setEnd(v)
        _unlockWidth(self._tail)
        _unlockWidth(self._head)
        _unlockWidth(self._handle)

if __name__ == '__main__':

    app = QtWidgets.QApplication(sys.argv)
    rs = QRangeSlider()
    rs.show()
    rs.setRange(15, 35)
    rs.setBackgroundStyle('background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #222, stop:1 #333);')
    rs.handle.setStyleSheet('background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #282, stop:1 #393);')
    app.exec_()
</code>```

If you want to run the examples, you just need to change the following code block (at the top of the file):

examples.py:

```<code>import sys, os
from PyQt5 import QtCore
from PyQt5 import QtGui
from PyQt5 import QtWidgets

from qrangeslider import QRangeSlider

app = QtWidgets.QApplication(sys.argv)

...
</code>```

Title: Porting range-slider widget to PyQt5

Body:
Below is a PyQt5 port of the QRangeSlider widget. For the sake of brevity, I have removed all comments, doc-strings, assert statements, etc. It seems to work okay with both Python 2 and Python 3, but I haven't really tested it much.

qrangeslider.py:

import sys, os
from PyQt5 import QtCore, QtGui, QtWidgets

__all__ = ['QRangeSlider']

DEFAULT_CSS = """
QRangeSlider * {
    border: 0px;
    padding: 0px;
}
QRangeSlider #Head {
    background: #222;
}
QRangeSlider #Span {
    background: #393;
}
QRangeSlider #Span:active {
    background: #282;
}
QRangeSlider #Tail {
    background: #222;
}
QRangeSlider > QSplitter::handle {
    background: #393;
}
QRangeSlider > QSplitter::handle:vertical {
    height: 4px;
}
QRangeSlider > QSplitter::handle:pressed {
    background: #ca5;
}
"""

def scale(val, src, dst):
    return int(((val - src[0]) / float(src[1]-src[0])) * (dst[1]-dst[0]) + dst[0])

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("QRangeSlider")
        Form.resize(300, 30)
        Form.setStyleSheet(DEFAULT_CSS)
        self.gridLayout = QtWidgets.QGridLayout(Form)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setSpacing(0)
        self.gridLayout.setObjectName("gridLayout")
        self._splitter = QtWidgets.QSplitter(Form)
        self._splitter.setMinimumSize(QtCore.QSize(0, 0))
        self._splitter.setMaximumSize(QtCore.QSize(16777215, 16777215))
        self._splitter.setOrientation(QtCore.Qt.Horizontal)
        self._splitter.setObjectName("splitter")
        self._head = QtWidgets.QGroupBox(self._splitter)
        self._head.setTitle("")
        self._head.setObjectName("Head")
        self._handle = QtWidgets.QGroupBox(self._splitter)
        self._handle.setTitle("")
        self._handle.setObjectName("Span")
        self._tail = QtWidgets.QGroupBox(self._splitter)
        self._tail.setTitle("")
        self._tail.setObjectName("Tail")
        self.gridLayout.addWidget(self._splitter, 0, 0, 1, 1)
        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("QRangeSlider", "QRangeSlider"))

class Element(QtWidgets.QGroupBox):
    def __init__(self, parent, main):
        super(Element, self).__init__(parent)
        self.main = main

    def setStyleSheet(self, style):
        self.parent().setStyleSheet(style)

    def textColor(self):
        return getattr(self, '__textColor', QtGui.QColor(125, 125, 125))

    def setTextColor(self, color):
        if type(color) == tuple and len(color) == 3:
            color = QtGui.QColor(color[0], color[1], color[2])
        elif type(color) == int:
            color = QtGui.QColor(color, color, color)
        setattr(self, '__textColor', color)

    def paintEvent(self, event):
        qp = QtGui.QPainter()
        qp.begin(self)
        if self.main.drawValues():
            self.drawText(event, qp)
        qp.end()

class Head(Element):
    def __init__(self, parent, main):
        super(Head, self).__init__(parent, main)

    def drawText(self, event, qp):
        qp.setPen(self.textColor())
        qp.setFont(QtGui.QFont('Arial', 10))
        qp.drawText(event.rect(), QtCore.Qt.AlignLeft, str(self.main.min()))

class Tail(Element):
    def __init__(self, parent, main):
        super(Tail, self).__init__(parent, main)

    def drawText(self, event, qp):
        qp.setPen(self.textColor())
        qp.setFont(QtGui.QFont('Arial', 10))
        qp.drawText(event.rect(), QtCore.Qt.AlignRight, str(self.main.max()))

class Handle(Element):
    def __init__(self, parent, main):
        super(Handle, self).__init__(parent, main)

    def drawText(self, event, qp):
        qp.setPen(self.textColor())
        qp.setFont(QtGui.QFont('Arial', 10))
        qp.drawText(event.rect(), QtCore.Qt.AlignLeft, str(self.main.start()))
        qp.drawText(event.rect(), QtCore.Qt.AlignRight, str(self.main.end()))

    def mouseMoveEvent(self, event):
        event.accept()
        mx = event.globalX()
        _mx = getattr(self, '__mx', None)
        if not _mx:
            setattr(self, '__mx', mx)
            dx = 0
        else:
            dx = mx - _mx
        setattr(self, '__mx', mx)
        if dx == 0:
            event.ignore()
            return
        elif dx > 0:
            dx = 1
        elif dx < 0:
            dx = -1
        s = self.main.start() + dx
        e = self.main.end() + dx
        if s >= self.main.min() and e <= self.main.max():
            self.main.setRange(s, e)

class QRangeSlider(QtWidgets.QWidget, Ui_Form):
    endValueChanged = QtCore.pyqtSignal(int)
    maxValueChanged = QtCore.pyqtSignal(int)
    minValueChanged = QtCore.pyqtSignal(int)
    startValueChanged = QtCore.pyqtSignal(int)
    minValueChanged = QtCore.pyqtSignal(int)
    maxValueChanged = QtCore.pyqtSignal(int)
    startValueChanged = QtCore.pyqtSignal(int)
    endValueChanged = QtCore.pyqtSignal(int)

    _SPLIT_START = 1
    _SPLIT_END = 2

    def __init__(self, parent=None):
        super(QRangeSlider, self).__init__(parent)
        self.setupUi(self)
        self.setMouseTracking(False)
        self._splitter.splitterMoved.connect(self._handleMoveSplitter)
        self._head_layout = QtWidgets.QHBoxLayout()
        self._head_layout.setSpacing(0)
        self._head_layout.setContentsMargins(0, 0, 0, 0)
        self._head.setLayout(self._head_layout)
        self.head = Head(self._head, main=self)
        self._head_layout.addWidget(self.head)
        self._handle_layout = QtWidgets.QHBoxLayout()
        self._handle_layout.setSpacing(0)
        self._handle_layout.setContentsMargins(0, 0, 0, 0)
        self._handle.setLayout(self._handle_layout)
        self.handle = Handle(self._handle, main=self)
        self.handle.setTextColor((150, 255, 150))
        self._handle_layout.addWidget(self.handle)
        self._tail_layout = QtWidgets.QHBoxLayout()
        self._tail_layout.setSpacing(0)
        self._tail_layout.setContentsMargins(0, 0, 0, 0)
        self._tail.setLayout(self._tail_layout)
        self.tail = Tail(self._tail, main=self)
        self._tail_layout.addWidget(self.tail)
        self.setMin(0)
        self.setMax(99)
        self.setStart(0)
        self.setEnd(99)
        self.setDrawValues(True)

    def min(self):
        return getattr(self, '__min', None)

    def max(self):
        return getattr(self, '__max', None)

    def setMin(self, value):
        setattr(self, '__min', value)
        self.minValueChanged.emit(value)

    def setMax(self, value):
        setattr(self, '__max', value)
        self.maxValueChanged.emit(value)

    def start(self):
        return getattr(self, '__start', None)

    def end(self):
        return getattr(self, '__end', None)

    def _setStart(self, value):
        setattr(self, '__start', value)
        self.startValueChanged.emit(value)

    def setStart(self, value):
        v = self._valueToPos(value)
        self._splitter.splitterMoved.disconnect()
        self._splitter.moveSplitter(v, self._SPLIT_START)
        self._splitter.splitterMoved.connect(self._handleMoveSplitter)
        self._setStart(value)

    def _setEnd(self, value):
        setattr(self, '__end', value)
        self.endValueChanged.emit(value)

    def setEnd(self, value):
        v = self._valueToPos(value)
        self._splitter.splitterMoved.disconnect()
        self._splitter.moveSplitter(v, self._SPLIT_END)
        self._splitter.splitterMoved.connect(self._handleMoveSplitter)
        self._setEnd(value)

    def drawValues(self):
        return getattr(self, '__drawValues', None)

    def setDrawValues(self, draw):
        setattr(self, '__drawValues', draw)

    def getRange(self):
        return (self.start(), self.end())

    def setRange(self, start, end):
        self.setStart(start)
        self.setEnd(end)

    def keyPressEvent(self, event):
        key = event.key()
        if key == QtCore.Qt.Key_Left:
            s = self.start()-1
            e = self.end()-1
        elif key == QtCore.Qt.Key_Right:
            s = self.start()+1
            e = self.end()+1
        else:
            event.ignore()
            return
        event.accept()
        if s >= self.min() and e <= self.max():
            self.setRange(s, e)

    def setBackgroundStyle(self, style):
        self._tail.setStyleSheet(style)
        self._head.setStyleSheet(style)

    def setSpanStyle(self, style):
        self._handle.setStyleSheet(style)

    def _valueToPos(self, value):
        return scale(value, (self.min(), self.max()), (0, self.width()))

    def _posToValue(self, xpos):
        return scale(xpos, (0, self.width()), (self.min(), self.max()))

    def _handleMoveSplitter(self, xpos, index):
        hw = self._splitter.handleWidth()
        def _lockWidth(widget):
            width = widget.size().width()
            widget.setMinimumWidth(width)
            widget.setMaximumWidth(width)
        def _unlockWidth(widget):
            widget.setMinimumWidth(0)
            widget.setMaximumWidth(16777215)
        v = self._posToValue(xpos)
        if index == self._SPLIT_START:
            _lockWidth(self._tail)
            if v >= self.end():
                return
            offset = -20
            w = xpos + offset
            self._setStart(v)
        elif index == self._SPLIT_END:
            _lockWidth(self._head)
            if v <= self.start():
                return
            offset = -40
            w = self.width() - xpos + offset
            self._setEnd(v)
        _unlockWidth(self._tail)
        _unlockWidth(self._head)
        _unlockWidth(self._handle)

if __name__ == '__main__':

    app = QtWidgets.QApplication(sys.argv)
    rs = QRangeSlider()
    rs.show()
    rs.setRange(15, 35)
    rs.setBackgroundStyle('background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #222, stop:1 #333);')
    rs.handle.setStyleSheet('background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #282, stop:1 #393);')
    app.exec_()

If you want to run the examples, you just need to change the following code block (at the top of the file):

examples.py:

import sys, os
from PyQt5 import QtCore
from PyQt5 import QtGui
from PyQt5 import QtWidgets

from qrangeslider import QRangeSlider

app = QtWidgets.QApplication(sys.argv)

...


来源: stackexchange

问:
How to avoid warning of Unreachable code
I have the below

```<code>string currency = string.Empty;
Regex r = new Regex(@"~(\w*[a-zA-Z0-9$£~%]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
for (Match m = r.Match(expression); m.Success; m = m.NextMatch())
{
      currency = (m.Groups[1].Value);
      break;
}
return currency;
</code>```

The intension is that, after the first match in the loop it should break.

The warning messge(Unreachable code) is happening  m = m.NextMatch() of the loop.

How to overcome this?

Thanks

答:
The general rule on how to avoid warning about unreachable code, is to not write unreachable code.

Let's take a look at what you've written:

A loop

For each entry in the loop, extract the value of a group, then break the loop

Go to next, err.. no, we'll never get here

The entire loop is unnecessary.

Instead, this would suffice:

```<code>string currency = string.Empty;
Regex r = new Regex(@"~(\w*[a-zA-Z0-9$£~%]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
Match m = r.Match(expression);
if (m.Success)
    currency = (m.Groups[1].Value);
return currency;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have the below

string currency = string.Empty;
Regex r = new Regex(@"~(\w*[a-zA-Z0-9$£~%]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
for (Match m = r.Match(expression); m.Success; m = m.NextMatch())
{
      currency = (m.Groups[1].Value);
      break;
}
return currency;

The intension is that, after the first match in the loop it should break.

The warning messge(Unreachable code) is happening  m = m.NextMatch() of the loop.

How to overcome this?

Thanks

Body:
The general rule on how to avoid warning about unreachable code, is to not write unreachable code.

Let's take a look at what you've written:

A loop

For each entry in the loop, extract the value of a group, then break the loop

Go to next, err.. no, we'll never get here

The entire loop is unnecessary.

Instead, this would suffice:

string currency = string.Empty;
Regex r = new Regex(@"~(\w*[a-zA-Z0-9$£~%]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
Match m = r.Match(expression);
if (m.Success)
    currency = (m.Groups[1].Value);
return currency;


问:
Simple woocommerce checkout page
I want to make the woocommerce checkout page as simple as like attached image.

Payment method and cart section only, no customer details section.

How can customize the checkout page like this?

答: Modify the WooCommerce templates by copying them over to your child theme directory under the path child-theme/woocommerce/checkout.  The main file is called form-checkout.php

ContentLicense: CC BY-SA 3.0

Title: Simple woocommerce checkout page


问:
Nuget connection attempt failed "Unable to load the service index for source"
While trying to connect to Nuget, I'm getting the error below, and then I am unable to connect:

[nuget.org] Unable to load the service index for source
https://api.nuget.org/v3/index.json.
An error occurred while sending the request.
Unable to connect to the remote server
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection
failed because connected host has failed to respond 68.232.34.200:443

I am able to access https://api.nuget.org/v3/index.json on my browser.

答:
In support of the answer provided by @Eddie Chen (here) I had to add http_proxy setting to following file as well:

C:\Windows\system32\config\systemprofile\AppData\Roaming\NuGet\NuGet.Config

```<code><add key="http_proxy" value="http://your_proxy_url:8080" />
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In support of the answer provided by @Eddie Chen (here) I had to add http_proxy setting to following file as well:

C:\Windows\system32\config\systemprofile\AppData\Roaming\NuGet\NuGet.Config

<add key="http_proxy" value="http://your_proxy_url:8080" />


问:
When refreshing Angular app, it ignores current URL and goes back to root URl
If my Angular app, if I navigate (via explicitly typing in the URL or clicking a page link to it) to http://localhost:4200/#/sign-in the page loads fine and shows my sign in form. If I then click Refresh in my browser, I am taken back to the root page http://localhost:4200/#/.

My router is simple:

```<code>export const routes: Route[] = [
  { path: 'sign-up', component: SignUpComponent},
  { path: 'sign-in', component: SignInComponent},
  { path: 'admin', loadChildren: 'app/admin/admin.module#AdminModule'},
  { path: 'dashboard', loadChildren: 'app/user/user.module#UserModule', canActivate: [ UserLoggedInGuard ]},
  { path: '', pathMatch: 'full', component: HomeComponent},
  { path: '**', pathMatch: 'full', component: PageNotFoundComponent},
]
</code>```

I am using

Windows 8

Chrome 62

@angular/core": "^4.2.4

@angular/router": "^4.2.4

Any ideas why this is happening?

答: The problem ended up being some code I had in my app.component.ts that checked if the user was logged in and if not, navigated to the home page.

Body:
If my Angular app, if I navigate (via explicitly typing in the URL or clicking a page link to it) to http://localhost:4200/#/sign-in the page loads fine and shows my sign in form. If I then click Refresh in my browser, I am taken back to the root page http://localhost:4200/#/.

My router is simple:

export const routes: Route[] = [
  { path: 'sign-up', component: SignUpComponent},
  { path: 'sign-in', component: SignInComponent},
  { path: 'admin', loadChildren: 'app/admin/admin.module#AdminModule'},
  { path: 'dashboard', loadChildren: 'app/user/user.module#UserModule', canActivate: [ UserLoggedInGuard ]},
  { path: '', pathMatch: 'full', component: HomeComponent},
  { path: '**', pathMatch: 'full', component: PageNotFoundComponent},
]

I am using

Windows 8

Chrome 62

@angular/core": "^4.2.4

@angular/router": "^4.2.4

Any ideas why this is happening?


问:
SQL Constraint issue
Really new to SQL. I’m having some issues figuring out a constraint’

Here's what I want to do. I have a table with 2 columns CampusID and Location. I want a constraint that each element of the CampusID must be 'UMS' followed by two digits. Not sure how to code this. This is what I have done. I am using SQL Fiddle to do this.

```<code>CREATE TABLE IF NOT EXISTS Campuses(
    CampusID varchar(16) Primary Key,
    Location varchar(16) NOT NULL,
    CONSTRAINT CampusID Check CampusID LIKE (UMS[0-9]0-9]),
);

INSERT INTO Campuses VALUES
    (“UMS01”,“Augusta”),
    (“UMS02”,“Farmington”),
    (“UMS03”,“Fort Kent”),
    (“UMS04”,“Machais”),
    (“UMS05”,“Orono”),
    (“UMS06”,“Presque Isle”),
    (“UMS07”,“Southern Maine”);
</code>```

答:
MySQL does not actually implement check constraints.  It does accept them syntactically, but it ignores them.

Just about all other databases do support them.  For your table, the syntax would look like:

```<code>CREATE TABLE Campuses (
    CampusID varchar(16) Primary Key,
    Location varchar(16) NOT NULL,
    CONSTRAINT CampusID Check (CampusID LIKE 'UMS__')
);
</code>```

Note:  This is two characters after the UMS.  Two digits is database dependent.  For Postgres, you can use (CampusID REGEXP '^UMS[0-9][0-9]$').

Here is a SQL Fiddle using Postgres.

Notes:

Often, the primary key is auto incremented (called serial in Postgres).

The constraint name should not just be the name of the column.  I would call it "chk_campuses_campusId".

The LIKE pattern needs to be surrounded by single quotes.

The entire check constraint expression needs to be enclosed in parentheses.

Title: SQL Constraint issue

Body:
Really new to SQL. I’m having some issues figuring out a constraint’

Here's what I want to do. I have a table with 2 columns CampusID and Location. I want a constraint that each element of the CampusID must be 'UMS' followed by two digits. Not sure how to code this. This is what I have done. I am using SQL Fiddle to do this.

CREATE TABLE IF NOT EXISTS Campuses(
    CampusID varchar(16) Primary Key,
    Location varchar(16) NOT NULL,
    CONSTRAINT CampusID Check CampusID LIKE (UMS[0-9]0-9]),
);

INSERT INTO Campuses VALUES
    (“UMS01”,“Augusta”),
    (“UMS02”,“Farmington”),
    (“UMS03”,“Fort Kent”),
    (“UMS04”,“Machais”),
    (“UMS05”,“Orono”),
    (“UMS06”,“Presque Isle”),
    (“UMS07”,“Southern Maine”);

Body:
MySQL does not actually implement check constraints.  It does accept them syntactically, but it ignores them.

Just about all other databases do support them.  For your table, the syntax would look like:

CREATE TABLE Campuses (
    CampusID varchar(16) Primary Key,
    Location varchar(16) NOT NULL,
    CONSTRAINT CampusID Check (CampusID LIKE 'UMS__')
);

Note:  This is two characters after the UMS.  Two digits is database dependent.  For Postgres, you can use (CampusID REGEXP '^UMS[0-9][0-9]$').

Here is a SQL Fiddle using Postgres.

Notes:

Often, the primary key is auto incremented (called serial in Postgres).

The constraint name should not just be the name of the column.  I would call it "chk_campuses_campusId".

The LIKE pattern needs to be surrounded by single quotes.

The entire check constraint expression needs to be enclosed in parentheses.


问:
How to switch to f3 in the figure (Selenium + Python)
How to switch to f3?

How to know the current frame?

None of the commands below works:

```<code>driver.switch_to.frame('f3')
driver.switch_to.frame(driver.find_element_by_xpath("//frameset[@name='viewfrm']"))
driver.switch_to.frame(driver.find_element_by_xpath("//frameset[@name='f3']"))
</code>```

答:
Your question doesn't mention what you are trying to do once you get into the frame but this code is working. It does what your code does in a slightly different way but then prints the last column from the resulting table.</p>

```<code>driver.get("newsmth.net/frames.html")
driver.switch_to_frame("menu")
input = driver.find_element_by_css_selector("input[name='board']")
input.clear()
input.send_keys("foodinfo\n")
driver.switch_to_default_content()
driver.switch_to_frame("f3")
rows = driver.find_elements_by_xpath("//table[@class='main wide']//tr/td[5]")
for row in rows
    print row.text
</code>```

Body:
How to switch to f3?

How to know the current frame?

None of the commands below works:

driver.switch_to.frame('f3')
driver.switch_to.frame(driver.find_element_by_xpath("//frameset[@name='viewfrm']"))
driver.switch_to.frame(driver.find_element_by_xpath("//frameset[@name='f3']"))

Body:
Your question doesn't mention what you are trying to do once you get into the frame but this code is working. It does what your code does in a slightly different way but then prints the last column from the resulting table.

driver.get("newsmth.net/frames.html")
driver.switch_to_frame("menu")
input = driver.find_element_by_css_selector("input[name='board']")
input.clear()
input.send_keys("foodinfo\n")
driver.switch_to_default_content()
driver.switch_to_frame("f3")
rows = driver.find_elements_by_xpath("//table[@class='main wide']//tr/td[5]")
for row in rows
    print row.text


问:
"Open Type" command does not respond in Eclipse workspace
In Eclipse, you can use Ctrl + Shift + T to search for a type.  Unfortunately, Eclipse does not respond to this hotkey in one of my workspaces.

I am running IBM AST 6.1, which is built on Eclipse 3.2.1 (see http://publib.boulder.ibm.com/infocenter/wasinfo/v6r1/index.jsp?topic=/com.ibm.websphere.express.doc/info/exp/ae/tins_ast_roadmap.html).

When I go to Window -> Preferences -> General -> Keys, it shows the Open Type command is set to the Key Sequence Ctrl+Shift+T "When" "In Windows".  Is this correct?

I can use Ctrl+Shift+R to search for a resource in this same Workspace, using the same Ctrl and Shift keys (i.e. the keys are working).  I can also use Ctrl+Shift+T on other workspaces with the same Eclipse installation.

How can I enable Ctrl+Shift+T?  What other info do we need to troubleshoot?

答:
Although, this is a very old post. But it might be someone get this problem in future.

The above mentioned posts can help in most of the scenarios.
But sometimes, even you select the Java/J2EE perspective, but the selected project is not a nature of java/j2ee. And in that case, the Open Type will open but will not search anything. And to fix that you have to make sure, the selected project has the following code in .project file:

```<code><natures>
    <nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</code>```

Body:
Although, this is a very old post. But it might be someone get this problem in future.

The above mentioned posts can help in most of the scenarios.
But sometimes, even you select the Java/J2EE perspective, but the selected project is not a nature of java/j2ee. And in that case, the Open Type will open but will not search anything. And to fix that you have to make sure, the selected project has the following code in .project file:

<natures>
    <nature>org.eclipse.jdt.core.javanature</nature>
</natures>


问:
How to change the size of a HTML button?
So I have this line of code put into Sublime Text:

```<code><input id="MM" type="button" style="width: 150px" >
</code>```

But how  do I change the length?

答:
It appears what you're asking is how to make the button higher, since you have already found out how to make it wider. The answer to this is adding the "height:" CSS command inside of your "style" parenthesis:

```<code><input id="MM" type="button" style="width: 150px; height: 50px;">
</code>```

And editing the 50 after "height:" to the desired number will allow you to scale your button as big or small as you want.

Hope this helps.

Body:
So I have this line of code put into Sublime Text:

<input id="MM" type="button" style="width: 150px" >

But how  do I change the length?

Body:
It appears what you're asking is how to make the button higher, since you have already found out how to make it wider. The answer to this is adding the "height:" CSS command inside of your "style" parenthesis:

<input id="MM" type="button" style="width: 150px; height: 50px;">

And editing the 50 after "height:" to the desired number will allow you to scale your button as big or small as you want.

Hope this helps.


问:
What's the different between ctrl-c and kill -9 when making kafka broker down
I am going through the kafka official tutorial, and met a weird problem at multibroker part.

I will list what I have done briefly:

run local zookeeper on port 2181

run three kafka brokers on ports 9092, 9093, 9094

created a topic with one partition and three replicas: my-replicated-topic

produced several messages into this topic

then I wanna test the fault-tolerance of kafka. instead of kill -9 which works correctly as expected, I used ctrl-c to terminate the leader of the topic. Here is the problem:

I CANNOT consume any messages from kafka.

What's wrong?

p.s. the commands I used are exactly the same as the tutorial mentioned above

kafka 1.00

--updated
The following is the some key output:

```<code> bin/kafka-topics.sh --describe --zookeeper localhost:2181 --topic my-replicated-topic
Topic:my-replicated-topic   PartitionCount:1    ReplicationFactor:3 Configs:
    Topic: my-replicated-topic  Partition: 0    Leader: 0   Replicas: 0,1,2 Isr: 1,0,2
</code>```

then I ctrl-c to kill the broker 0:

```<code> bin/kafka-topics.sh --describe --zookeeper localhost:2181 --topic my-replicated-topic
Topic:my-replicated-topic   PartitionCount:1    ReplicationFactor:3 Configs:
    Topic: my-replicated-topic  Partition: 0    Leader: 1   Replicas: 0,1,2 Isr: 1,2
</code>```

at this time I cannot consume from other brokers

```<code>bin/kafka-console-consumer.sh --bootstrap-server 127.0.0.1:9093 --from-beginning --topic my-replicated-topic
</code>```

this is the config for broker 0, configs for others are same as this except for the broker id, port and log directory.

```<code>broker.id=0
num.network.threads=3
num.io.threads=8
socket.send.buffer.bytes=102400
socket.receive.buffer.bytes=102400
socket.request.max.bytes=104857600
log.dirs=/tmp/kafka-logs
num.partitions=1
num.recovery.threads.per.data.dir=1
offsets.topic.replication.factor=1
transaction.state.log.replication.factor=1
transaction.state.log.min.isr=1
log.retention.hours=168
log.segment.bytes=1073741824
log.retention.check.interval.ms=300000
zookeeper.connect=localhost:2181
zookeeper.connection.timeout.ms=6000
group.initial.rebalance.delay.ms=0
</code>```

答:
Your offsets.topic.replication.factor=1 so if you kill the broker with the offsets for your consumer, there is no other replica and so you have no offsets.

It is not a fault tolerant config to have replication factor = 1 on your __consumer_offsets topic

Not only will you need to change this config but you will then also have to modify the existing consumer offset topic to be replication factor = 3

Body:
I am going through the kafka official tutorial, and met a weird problem at multibroker part.

I will list what I have done briefly:

run local zookeeper on port 2181

run three kafka brokers on ports 9092, 9093, 9094

created a topic with one partition and three replicas: my-replicated-topic

produced several messages into this topic

then I wanna test the fault-tolerance of kafka. instead of kill -9 which works correctly as expected, I used ctrl-c to terminate the leader of the topic. Here is the problem:

I CANNOT consume any messages from kafka.

What's wrong?

p.s. the commands I used are exactly the same as the tutorial mentioned above

kafka 1.00

--updated
The following is the some key output:

 bin/kafka-topics.sh --describe --zookeeper localhost:2181 --topic my-replicated-topic
Topic:my-replicated-topic   PartitionCount:1    ReplicationFactor:3 Configs:
    Topic: my-replicated-topic  Partition: 0    Leader: 0   Replicas: 0,1,2 Isr: 1,0,2

then I ctrl-c to kill the broker 0:

 bin/kafka-topics.sh --describe --zookeeper localhost:2181 --topic my-replicated-topic
Topic:my-replicated-topic   PartitionCount:1    ReplicationFactor:3 Configs:
    Topic: my-replicated-topic  Partition: 0    Leader: 1   Replicas: 0,1,2 Isr: 1,2

at this time I cannot consume from other brokers

bin/kafka-console-consumer.sh --bootstrap-server 127.0.0.1:9093 --from-beginning --topic my-replicated-topic

this is the config for broker 0, configs for others are same as this except for the broker id, port and log directory.

broker.id=0
num.network.threads=3
num.io.threads=8
socket.send.buffer.bytes=102400
socket.receive.buffer.bytes=102400
socket.request.max.bytes=104857600
log.dirs=/tmp/kafka-logs
num.partitions=1
num.recovery.threads.per.data.dir=1
offsets.topic.replication.factor=1
transaction.state.log.replication.factor=1
transaction.state.log.min.isr=1
log.retention.hours=168
log.segment.bytes=1073741824
log.retention.check.interval.ms=300000
zookeeper.connect=localhost:2181
zookeeper.connection.timeout.ms=6000
group.initial.rebalance.delay.ms=0


问:
Add copy constructor based on template parameters
I have a container-like class, that I would like to be move-only if the underlying type is move-only, but copyable otherwise. To make things simple, let's assume copyability is determined by a single bool template parameter:

```<code>template<bool IsCopyable>
struct Foo
{
    Foo();
    Foo(const Foo&);    // only include this when IsCopyable is true
    Foo(Foo&&);

    Foo& operator=(const Foo&);  // only when IsCopyable
    Foo& operator=(Foo&&);
};
</code>```

Now, I can't just SFINAE the copy ctor away, because that requires making it templated and a templated function can't be a copy ctor. Also, I can't just do a static_assert() within the copy ctor. Although this will catch erroneous uses of the copy ctor, it also makes the class inherently copy constructible from the outside (the std::is_copy_constructible type trait will yield true).

By the way, an unfortunate requirement is that it needs to compile in VC++ 2012, so I can't use fancy expression SFINAE, inheriting ctors, defaulted/deleted functions or constexpr if (nevertheless, if you have a neat solution for C++17 I'd still like to hear it :))

The obvious method is to use template specialization. I'd rather not go this route, because in reality Foo has quite a lot of functionality and I don't like to repeat myself. Nevertheless, this seems my only option, and I can implement some code sharing using a base class, like so:

```<code>// Base functionality
template<bool IsCopyable>
struct FooBase
{
    FooBase();

    // move ctor and assignment can go here
    FooBase(FooBase&&);
    FooBase& operator=(FooBase&&);

    // some generic conversion ctor and assignment that I happen to need
    template<class T> FooBase(T&& t);
    template<class T> FooBase& operator=(T&&);

    // ... all sorts of functionality and datamembers
};

// Foo<false>
template<bool IsCopyable>
struct Foo : FooBase<IsCopyable>
{
    // can't use inheriting ctors in VS 2012, wrap the calls manually:
    Foo() { }
    Foo(Foo&& other) : FooBase<IsCopyable>(std::move(other)) { }
    Foo& operator=(Foo&& other)
    {
        FooBase<IsCopyable>::operator=(std::move(other));
        return *this;
    }

    template<class T> Foo(T&& t) : FooBase<IsCopyable>(std::forward<T>(t)) { }
    template<class T> Foo& operator=(T&& t)
    {
        FooBase<IsCopyable>::operator=(std::forward<T>(t));
        return *this;
    }
};

// Foo<true>
template<>
struct Foo<true> : FooBase<true>
{
    // add these
    Foo(const Foo&);
    Foo& operator=(const Foo&);

    // wrapping calls because of VS 2012:
    Foo() { }
    Foo(Foo&& other) : FooBase<true>(std::move(other)) { }
    Foo& operator=(Foo&& other)
    {
        FooBase<true>::operator=(std::move(other));
        return *this;
    }

    template<class T> Foo(T&& t) : FooBase<true>(std::forward<T>(t)) { }
    template<class T> Foo& operator=(T&& t)
    {
        FooBase<true>::operator=(std::forward<T>(t));
        return *this;
    }
};
</code>```

It's still a bit verbose. Fortunately it gets cleaner once you can use inheriting ctors and defaulted functions. Nevertheless, I was hoping there is a simpler way, ideally by not using a base class.

答:
```<code>struct nonesuch {
private:
    ~nonesuch();
    nonesuch(const nonesuch&);
    void operator=(const nonesuch&);
};

template<bool IsCopyable>
struct Foo {
    Foo(const typename std::conditional<IsCopyable, Foo, nonesuch>::type& other) {
        // copy ctor impl here
    }
private:
    Foo(const typename std::conditional<!IsCopyable, Foo, nonesuch>::type&);
};
</code>```

Likewise for assignment.

Body:
I have a container-like class, that I would like to be move-only if the underlying type is move-only, but copyable otherwise. To make things simple, let's assume copyability is determined by a single bool template parameter:

template<bool IsCopyable>
struct Foo
{
    Foo();
    Foo(const Foo&);    // only include this when IsCopyable is true
    Foo(Foo&&);

    Foo& operator=(const Foo&);  // only when IsCopyable
    Foo& operator=(Foo&&);
};

Now, I can't just SFINAE the copy ctor away, because that requires making it templated and a templated function can't be a copy ctor. Also, I can't just do a static_assert() within the copy ctor. Although this will catch erroneous uses of the copy ctor, it also makes the class inherently copy constructible from the outside (the std::is_copy_constructible type trait will yield true).

By the way, an unfortunate requirement is that it needs to compile in VC++ 2012, so I can't use fancy expression SFINAE, inheriting ctors, defaulted/deleted functions or constexpr if (nevertheless, if you have a neat solution for C++17 I'd still like to hear it :))

The obvious method is to use template specialization. I'd rather not go this route, because in reality Foo has quite a lot of functionality and I don't like to repeat myself. Nevertheless, this seems my only option, and I can implement some code sharing using a base class, like so:

// Base functionality
template<bool IsCopyable>
struct FooBase
{
    FooBase();

    // move ctor and assignment can go here
    FooBase(FooBase&&);
    FooBase& operator=(FooBase&&);

    // some generic conversion ctor and assignment that I happen to need
    template<class T> FooBase(T&& t);
    template<class T> FooBase& operator=(T&&);

    // ... all sorts of functionality and datamembers
};

// Foo<false>
template<bool IsCopyable>
struct Foo : FooBase<IsCopyable>
{
    // can't use inheriting ctors in VS 2012, wrap the calls manually:
    Foo() { }
    Foo(Foo&& other) : FooBase<IsCopyable>(std::move(other)) { }
    Foo& operator=(Foo&& other)
    {
        FooBase<IsCopyable>::operator=(std::move(other));
        return *this;
    }

    template<class T> Foo(T&& t) : FooBase<IsCopyable>(std::forward<T>(t)) { }
    template<class T> Foo& operator=(T&& t)
    {
        FooBase<IsCopyable>::operator=(std::forward<T>(t));
        return *this;
    }
};

// Foo<true>
template<>
struct Foo<true> : FooBase<true>
{
    // add these
    Foo(const Foo&);
    Foo& operator=(const Foo&);

    // wrapping calls because of VS 2012:
    Foo() { }
    Foo(Foo&& other) : FooBase<true>(std::move(other)) { }
    Foo& operator=(Foo&& other)
    {
        FooBase<true>::operator=(std::move(other));
        return *this;
    }

    template<class T> Foo(T&& t) : FooBase<true>(std::forward<T>(t)) { }
    template<class T> Foo& operator=(T&& t)
    {
        FooBase<true>::operator=(std::forward<T>(t));
        return *this;
    }
};

It's still a bit verbose. Fortunately it gets cleaner once you can use inheriting ctors and defaulted functions. Nevertheless, I was hoping there is a simpler way, ideally by not using a base class.

Body:
struct nonesuch {
private:
    ~nonesuch();
    nonesuch(const nonesuch&);
    void operator=(const nonesuch&);
};

template<bool IsCopyable>
struct Foo {
    Foo(const typename std::conditional<IsCopyable, Foo, nonesuch>::type& other) {
        // copy ctor impl here
    }
private:
    Foo(const typename std::conditional<!IsCopyable, Foo, nonesuch>::type&);
};

Likewise for assignment.


问:
Angularjs modal is updating my parent scope before the results sent back
I'm launching a modal from my web page and i'm making some changes to an array that i'm passing from my parent, but before I send the updated results back after closing the modal my parent scope object is getting updated. If the user changed the mind not to update and then cancel the modal I don't want those changes to be seen on my parent controller

Parent Controller Code:

const modalInstance = $modal.open({
                templateUrl: '/app/modal.html',
                controller: 'modalController',
                controllerAs: 'modal',
                resolve: {

                    mappedData: () => parentCntrl.groupData
                }
            });

```<code>        modalInstance.result.then(result => {
            if (result) {
                parentCntrl.groupData = result;
            }
        });
</code>```

Child Controller Code:

modal.ok = () => {
   $modalInstance.close(modal.mappedData);
};

modal.close = () => {
  $modalInstance.close();
};

答:
When you instantiate a $uibModal, you define a configuration object, where the setting scope : should be the object reference that this modal will use (as a scope). It is pretty normal to define something like scope: $scope. This way, if the variables inside the modal controller have the same names as the ones in the parent scope, then the assignment would occur to the same object.
As some comments say, the use of angular.copy() would be a good idea or maybe a simple $rootScope.new();

```<code>var modalInstance = $uibModal.open({
  ...
  scope : $rootScope.new(),
  //or
  scope : angular.copy($scope)
  ...
});
</code>```

I hope this helps

Body:
I'm launching a modal from my web page and i'm making some changes to an array that i'm passing from my parent, but before I send the updated results back after closing the modal my parent scope object is getting updated. If the user changed the mind not to update and then cancel the modal I don't want those changes to be seen on my parent controller

Parent Controller Code:

const modalInstance = $modal.open({
                templateUrl: '/app/modal.html',
                controller: 'modalController',
                controllerAs: 'modal',
                resolve: {

                    mappedData: () => parentCntrl.groupData
                }
            });

        modalInstance.result.then(result => {
            if (result) {
                parentCntrl.groupData = result;
            }
        });

Child Controller Code:

modal.ok = () => {
   $modalInstance.close(modal.mappedData);
};

modal.close = () => {
  $modalInstance.close();
};

Body:
When you instantiate a $uibModal, you define a configuration object, where the setting scope : should be the object reference that this modal will use (as a scope). It is pretty normal to define something like scope: $scope. This way, if the variables inside the modal controller have the same names as the ones in the parent scope, then the assignment would occur to the same object.
As some comments say, the use of angular.copy() would be a good idea or maybe a simple $rootScope.new();

var modalInstance = $uibModal.open({
  ...
  scope : $rootScope.new(),
  //or
  scope : angular.copy($scope)
  ...
});

I hope this helps


问:
Redistributing batch result in multi-threaded Tensorflow
I'm enqueqing multiple inputs to data a TF.FIFOqueue using

```<code>q = tf.FIFOQueue(...)
</code>```

The data is generated by threads, each loading a data point using q.enqueue, and waiting for evaluation. Once a batch is ready, I get the output using

```<code>batch = q.dequeue_many(batch_size)
</code>```

and process the data using some NN.
Now, here's my question:
How can I redistribute the results to each thread, so that each thread will get the prediction for its data point? In other words, how do I know which thread placed entry #1, in order to feed it with output #1?

Alternatively, should I approach the problem differently?

答: You can enqueue/dequeue tuples of tensors onto/from tf queues. One simple way would be to enqueue a pair (thread_id, data_point) instead of just data_point. thread_id can be a constant integer or string tensor, for example.

Body:
I'm enqueqing multiple inputs to data a TF.FIFOqueue using

q = tf.FIFOQueue(...)

The data is generated by threads, each loading a data point using q.enqueue, and waiting for evaluation. Once a batch is ready, I get the output using

batch = q.dequeue_many(batch_size)

and process the data using some NN.
Now, here's my question:
How can I redistribute the results to each thread, so that each thread will get the prediction for its data point? In other words, how do I know which thread placed entry #1, in order to feed it with output #1?

Alternatively, should I approach the problem differently?