问:
Algorithm - How to delete duplicate elements in a Haskell list
I'm having a problem creating an function similar to the nub function.

I need this func to remove duplicated elements form a list.
An element is duplicated when 2 elements have the same email, and it should keep the newer one (is closer to the end of the list).

```<code>type Regist = [name,email,,...,date]
type ListRe = [Regist]

rmDup ListRe -> ListRe
rmDup [] = []
rmDup [a] = [a]
rmDup (h:t) | isDup h (head t) = rmDup t
            | otherwise = h : rmDup t

isDup :: Regist -> Regist -> Bool
isDup (a:b:c:xs) (d:e:f:ts) = b==e
</code>```

The problem is that the function doesn't delete duplicated elements unless they are together in the list.

答:
Slightly doctored version of your original code to make it run:

```<code>type Regist = [String]
type ListRe = [Regist]

rmDup :: ListRe -> ListRe
rmDup [] = []
rmDup (x:xs) = x : rmDup (filter (\y -> not(x == y)) xs)
</code>```

Result:

```<code>*Main> rmDup [["a", "b"], ["a", "d"], ["a", "b"]]
[["a","b"],["a","d"]]
</code>```

Body:
I'm having a problem creating an function similar to the nub function.

I need this func to remove duplicated elements form a list.
An element is duplicated when 2 elements have the same email, and it should keep the newer one (is closer to the end of the list).

type Regist = [name,email,,...,date]
type ListRe = [Regist]

rmDup ListRe -> ListRe
rmDup [] = []
rmDup [a] = [a]
rmDup (h:t) | isDup h (head t) = rmDup t
            | otherwise = h : rmDup t

isDup :: Regist -> Regist -> Bool
isDup (a:b:c:xs) (d:e:f:ts) = b==e

The problem is that the function doesn't delete duplicated elements unless they are together in the list.

Body:
Slightly doctored version of your original code to make it run:

type Regist = [String]
type ListRe = [Regist]

rmDup :: ListRe -> ListRe
rmDup [] = []
rmDup (x:xs) = x : rmDup (filter (\y -> not(x == y)) xs)

Result:

*Main> rmDup [["a", "b"], ["a", "d"], ["a", "b"]]
[["a","b"],["a","d"]]


来源: stackexchange

问:
TFS lets me do compare and checkout, but not checkin
I have been using TFS in my visual studio 2013 for some time now but now I have a problem.

When it was initially setup I logged into TFS from VS using the domain\Administrator.

But company policy has changed and now the password is changed and I dont know it anymore.

But my own domain user has been granted administrator rights so I think ok no problem next time I start VS and TFS asks me to login I provide my own account.

This did not work I got tons of errors so I had to go to Control Panel and remove this credential from credential manager.

So I started VS again and let someone type in the pass for Administrator again, and click on remember.

That seemed to work, I can do a compare of files and it is correct.

I am also able to checkout files for editing.

But when I want to check in than it displays an error for a split second and it shuts down my project in VS.

After numerous tries I was able to capture a screenshot of the error (it only displayed for a split second).

This is the error :

I have no clue what this thing is talking about and I am hoping someone here can push me into the right way to find a solution for this.

Where can I find this workspace and how can I give it permissions ?

I am using visual studio 13 on local computer, logged in to domain and my user account has administrator rights.

EDIT:

I found a screen in VS to edit the workspace. The permissions are currently on Private Workspace.

So set it to public and now I also cannot do Compare and Checkout anymore.

Setting it back to private does not helps I keep getting this error now.

Any suggestions ?

Edit:

There seem to be 2 workspaces with the same name but I can only see on in manage workspaces. Maybe if I can get rid of one somehow.

In this screen I can see 2 workspaces :

How can I get rid of the second ?

EDIT:

IT seems that VS keeps searching for the wrong workspace.

See this screenshot :

I configured a new workspace PC_GUIDO_2 but if I do a compare it keeps searching for workspace PC_GUIDO even if the workspace combobox says PC_GUIDO_2.

How can I force it to stop searching for that workspace ?

答:
Please try following below steps to fix the issue:

Make sure your account has the check in permission for the project.
(Administer Server  >  Version Control > Set the permissions)

Close VS

Delete the VS client caches

Start VS as administrator (Right click and run as administrator) and DO NOT LOGIN WITH VISUAL STUDIO

In team explorer connect TFS with your account

Manage Workspace to delete current workspace "PC_GUIDO"

Create a new workspace and map sources to new local folder

Then check the issue again.

ContentLicense: CC BY-SA 3.0


问:
Unable to Inject Dependency ngMaterial
I am looking to develop an application that uses both dirPagination and AngularJS material. However, I am unable to inject the ngMaterial dependency into my application. The angularUtils.directives.dirPagination dependency works fine, but as soon as I add ngMaterial, the AngularJS application crashes.

Here is a Plunker with an example (https://plnkr.co/edit/7N7i9TnMc77Nz6xlNhuk?p=preview). In app.js, which is where I instantiate the module, both dependencies are there. If the line reads:

```<code>angular.module('myApp', ['angularUtils.directives.dirPagination', 'ngMaterial']);
</code>```

Then AngularJS crashes and the page reads {{hello}}. However, since in the controller, I have set $scope.hello to "Hello Plunker!", if the line reads:

```<code>angular.module('myApp', ['angularUtils.directives.dirPagination']);
</code>```

Then the page displays "Hello Plunker!".

What am I doing wrong?

Thanks for your help!

答:
You are missing the script for material.css, and the order is wrong.

```<code>  <script data-require="angular.js@1.3.0" data-semver="1.3.0" src="https://code.angularjs.org/1.3.0/angular.js"></script>
  <link rel="stylesheet" href="//rawgit.com/angular/bower-material/master/angular-material.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.js"></script>
  <script src="script.js"></script>
  <script src="dirPagination.js"></script>
</code>```

WORKING DEMO

Title: Unable to Inject Dependency ngMaterial

Body:
I am looking to develop an application that uses both dirPagination and AngularJS material. However, I am unable to inject the ngMaterial dependency into my application. The angularUtils.directives.dirPagination dependency works fine, but as soon as I add ngMaterial, the AngularJS application crashes.

Here is a Plunker with an example (https://plnkr.co/edit/7N7i9TnMc77Nz6xlNhuk?p=preview). In app.js, which is where I instantiate the module, both dependencies are there. If the line reads:

angular.module('myApp', ['angularUtils.directives.dirPagination', 'ngMaterial']);

Then AngularJS crashes and the page reads {{hello}}. However, since in the controller, I have set $scope.hello to "Hello Plunker!", if the line reads:

angular.module('myApp', ['angularUtils.directives.dirPagination']);

Then the page displays "Hello Plunker!".

What am I doing wrong?

Thanks for your help!

Body:
You are missing the script for material.css, and the order is wrong.

  <script data-require="angular.js@1.3.0" data-semver="1.3.0" src="https://code.angularjs.org/1.3.0/angular.js"></script>
  <link rel="stylesheet" href="//rawgit.com/angular/bower-material/master/angular-material.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.js"></script>
  <script src="script.js"></script>
  <script src="dirPagination.js"></script>

WORKING DEMO


问:
Consumer not receiving messages, kafka console, new consumer api, Kafka 0.9
I am doing the Kafka Quickstart for Kafka 0.9.0.0.

I have zookeeper listening at localhost:2181 because I ran

```<code>bin/zookeeper-server-start.sh config/zookeeper.properties
</code>```

I have a single broker listening at localhost:9092 because I ran

```<code>bin/kafka-server-start.sh config/server.properties
</code>```

I have a producer posting to topic "test" because I ran

```<code>bin/kafka-console-producer.sh --broker-list localhost:9092 --topic test
yello
is this thing on?
let's try another
gimme more
</code>```

When I run the old API consumer, it works by running

```<code>bin/kafka-console-consumer.sh --zookeeper localhost:2181 --topic test --from-beginning
</code>```

However, when I run the new API consumer, I don't get anything when I run

```<code>bin/kafka-console-consumer.sh --new-consumer --topic test --from-beginning \
    --bootstrap-server localhost:9092
</code>```

Is it possible to subscribe to a topic from the console consumer using the new api? How can I fix it?

答:
I just ran into this issue and the solution was to delete /brokers in zookeeper and restart the kafka nodes.

bin/zookeeper-shell <zk-host>:2181

and then

rmr /brokers

Not sure why this solves it.

When I enabled debug logging, I saw this error message over and over again in the consumer:

2017-07-07 01:20:12 DEBUG AbstractCoordinator:548 - Sending GroupCoordinator request for group test to broker xx.xx.xx.xx:9092 (id: 1007 rack: null)
2017-07-07 01:20:12 DEBUG AbstractCoordinator:559 - Received GroupCoordinator response ClientResponse(receivedTimeMs=1499390412231, latencyMs=84, disconnected=false, requestHeader={api_key=10,api_version=0,correlation_id=13,client_id=consumer-1}, responseBody={error_code=15,coordinator={node_id=-1,host=,port=-1}}) for group test
2017-07-07 01:20:12 DEBUG AbstractCoordinator:581 - Group coordinator lookup for group test failed: The group coordinator is not available.
2017-07-07 01:20:12 DEBUG AbstractCoordinator:215 - Coordinator discovery failed for group test, refreshing metadata

Body:
I am doing the Kafka Quickstart for Kafka 0.9.0.0.

I have zookeeper listening at localhost:2181 because I ran

bin/zookeeper-server-start.sh config/zookeeper.properties

I have a single broker listening at localhost:9092 because I ran

bin/kafka-server-start.sh config/server.properties

I have a producer posting to topic "test" because I ran

bin/kafka-console-producer.sh --broker-list localhost:9092 --topic test
yello
is this thing on?
let's try another
gimme more

When I run the old API consumer, it works by running

bin/kafka-console-consumer.sh --zookeeper localhost:2181 --topic test --from-beginning

However, when I run the new API consumer, I don't get anything when I run

bin/kafka-console-consumer.sh --new-consumer --topic test --from-beginning \
    --bootstrap-server localhost:9092

Is it possible to subscribe to a topic from the console consumer using the new api? How can I fix it?


问:
Why doesn't AWT/Swing repaint automatically when adding a component to a container?
We have some code implemented as follows:

```<code>@Override
public void showPanel(CardPanel panel)
{
    cardPanel.removeAll();
    cardPanel.add((Component) panel);

    // Even though you'd think adding a component should automatically repaint,
    // it turns out that it doesn't.
    cardPanel.repaint();
}
</code>```

cardPanel is just a JPanel and CardPanel is just one of our own interfaces, but all card panels are just using normal Swing components.

This comment was baffling because, as far as I knew, Container#add was supposed to automatically repaint itself if a child was added. Yet, if I delete the line, indeed I do see that it doesn't repaint its contents when the child is added.

Is there some particular reason why Container behaves this way? To me, it seems to violate the "principle of least surprise"...

答:
Is there some particular reason why Container behaves this way?

By default all Swing components have a default size of (0, 0) so there is nothing to paint.

Components are given a size (and location) when the layout manager is invoked. Since you could be adding multiple components to the panel it doesn't make sense for the layout manager to continually be invoked as each component is added.

So when you finish adding components to the panel you do:

```<code>panel.revalidate(); // to invoke the layout manager
panel.repaint(); // not always needed, but will ensure the panel is repainted.
</code>```

Body:
We have some code implemented as follows:

@Override
public void showPanel(CardPanel panel)
{
    cardPanel.removeAll();
    cardPanel.add((Component) panel);

    // Even though you'd think adding a component should automatically repaint,
    // it turns out that it doesn't.
    cardPanel.repaint();
}

cardPanel is just a JPanel and CardPanel is just one of our own interfaces, but all card panels are just using normal Swing components.

This comment was baffling because, as far as I knew, Container#add was supposed to automatically repaint itself if a child was added. Yet, if I delete the line, indeed I do see that it doesn't repaint its contents when the child is added.

Is there some particular reason why Container behaves this way? To me, it seems to violate the "principle of least surprise"...

Body:
Is there some particular reason why Container behaves this way?

By default all Swing components have a default size of (0, 0) so there is nothing to paint.

Components are given a size (and location) when the layout manager is invoked. Since you could be adding multiple components to the panel it doesn't make sense for the layout manager to continually be invoked as each component is added.

So when you finish adding components to the panel you do:

panel.revalidate(); // to invoke the layout manager
panel.repaint(); // not always needed, but will ensure the panel is repainted.


问:
How can I use QTimer with QT' QMainWindow (QTimer works with QTWidget but not QMainWindow)
I have a QMainWindow created in QT Designer with a GraphicsView object that has been promoted to a pyQTGraph PlotWidget. I want to use a QTimer event to get live serial data (Y) and plot it with (X) being 1 second increments set by the QTimer event. However, the problem I'm having is that when using QT's QMainWindow as the main form I get the error "QObject::startTimer: QTimer can only be used with threads started with QThread", but if I use QT's QWidget as the main form everything works fine with no errors.

How can I use QTimer with QT's QMainWindow

QT4 and QT Designer
Python 3
PyQTGraph

Here is the Form Code:

```<code># -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'MainPlotWindow.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(735, 374)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.plot = PlotWidget(self.centralwidget)
        self.plot.setGeometry(QtCore.QRect(30, 40, 681, 261))
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.plot.sizePolicy().hasHeightForWidth())
        self.plot.setSizePolicy(sizePolicy)
        self.plot.setFrameShape(QtGui.QFrame.WinPanel)
        self.plot.setFrameShadow(QtGui.QFrame.Sunken)
        self.plot.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.plot.setObjectName(_fromUtf8("plot"))
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 735, 21))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)

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

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))

from pyqtgraph import PlotWidget
</code>```

Here is the simple test program that reproduces the error:

```<code>from PyQt4.QtCore import QThread, SIGNAL, QSettings
import sys
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg

from MainPlotWindow import *

'''=====================================================================
                            M A I N  G U I
   ====================================================================='''

class MyForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

def PlotUpdate():
    print("Hello")

timer = QtCore.QTimer()
timer.timeout.connect(PlotUpdate)
timer.start(1000) # 1 Second Refesh Rate

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MyForm()
    myapp.show()
    sys.exit(app.exec_())
</code>```

Any help would be very much appreciated!

答:
I recommend that the QTimer this inside the widget, as I show in the following example:

```<code>class MyForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        timer = QtCore.QTimer(self)
        timer.timeout.connect(self.PlotUpdate)
        timer.start(100) # 1 Second Refesh Rate
        self.curve = self.ui.plot.plot()
        self.counter = 0

    def PlotUpdate(self):
        x = self.counter + np.arange(0, 10)
        y = 10*np.sin(np.pi*x/10)
        self.curve.setData(x, y)
        self.counter += 1
</code>```

Output:

Body:
I have a QMainWindow created in QT Designer with a GraphicsView object that has been promoted to a pyQTGraph PlotWidget. I want to use a QTimer event to get live serial data (Y) and plot it with (X) being 1 second increments set by the QTimer event. However, the problem I'm having is that when using QT's QMainWindow as the main form I get the error "QObject::startTimer: QTimer can only be used with threads started with QThread", but if I use QT's QWidget as the main form everything works fine with no errors.

How can I use QTimer with QT's QMainWindow

QT4 and QT Designer
Python 3
PyQTGraph

Here is the Form Code:

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'MainPlotWindow.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(735, 374)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.plot = PlotWidget(self.centralwidget)
        self.plot.setGeometry(QtCore.QRect(30, 40, 681, 261))
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.plot.sizePolicy().hasHeightForWidth())
        self.plot.setSizePolicy(sizePolicy)
        self.plot.setFrameShape(QtGui.QFrame.WinPanel)
        self.plot.setFrameShadow(QtGui.QFrame.Sunken)
        self.plot.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.plot.setObjectName(_fromUtf8("plot"))
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 735, 21))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)

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

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))

from pyqtgraph import PlotWidget

Here is the simple test program that reproduces the error:

from PyQt4.QtCore import QThread, SIGNAL, QSettings
import sys
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg

from MainPlotWindow import *

'''=====================================================================
                            M A I N  G U I
   ====================================================================='''

class MyForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

def PlotUpdate():
    print("Hello")

timer = QtCore.QTimer()
timer.timeout.connect(PlotUpdate)
timer.start(1000) # 1 Second Refesh Rate

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MyForm()
    myapp.show()
    sys.exit(app.exec_())

Any help would be very much appreciated!

Body:
I recommend that the QTimer this inside the widget, as I show in the following example:

class MyForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        timer = QtCore.QTimer(self)
        timer.timeout.connect(self.PlotUpdate)
        timer.start(100) # 1 Second Refesh Rate
        self.curve = self.ui.plot.plot()
        self.counter = 0

    def PlotUpdate(self):
        x = self.counter + np.arange(0, 10)
        y = 10*np.sin(np.pi*x/10)
        self.curve.setData(x, y)
        self.counter += 1

Output:


问:
Using lookup function to return list of values with filtering
I am currently using lookup function to return multiple values. I got this function from Extend Office.
https://www.extendoffice.com/documents/excel/2706-excel-vlookup-return-multiple-values-in-one-cell.html

I want to edit the codes to cater to my needs where it can further filter the multiple values to only what I need. I am currently using Instr Function to return only values that start with whatever the alphabet  the user keys in. However, the function cannot work as the result would show '#VALUE!'. I have no idea where I have gone wrong.

For example I use key in the function in the sheet itself, 'MYVLOOKUP(C2,Table!A:B,2,"J")'. This means that I only want to return values starting with 'J' but it returns #VALUE!.

```<code>Function MYVLOOKUP(pValue As String, pWorkRng As Range, pIndex As Long,
filter As String)
Dim rng As Range
Dim xResult As String
Dim result As Integer

xResult = vbNullString
'the next line trims pWorkRng down to the .UsedRange
Set pWorkRng = Intersect(pWorkRng, pWorkRng.Parent.UsedRange)

For Each rng In pWorkRng
    If rng = pValue Then
        result = InStr(rng.Value, filter, vbTextCompare)
        If result = 1 Then
        xResult = xResult & rng.Offset(0, pIndex - 1) & ","
        Else
        End If
   End If
Next
MYVLOOKUP = Trim(xResult)
End Function
</code>```

答:
I think that you are seeking this UDF:

```<code>Function MYVLOOKUP(pValue As String, pWorkRng As Range, pIndex As Long, _
                   Optional filter As String = "*")
  Dim rng As Range, ret As String
  For Each rng In Intersect(pWorkRng.Columns(1), pWorkRng.Parent.UsedRange)
    If rng Like pValue Then If rng(1, pIndex) Like filter Then _
      ret = ret & IIf(Len(ret), ",", "") & rng(1, pIndex)
  Next
  MYVLOOKUP = ret
End Function
</code>```

Notice how to use it:

the first parameter is an exact match on the first column. You can use wildcards (*) inside, such as "xx*" to match anything starting with "xx", or "*yy*" to match anything containing "yy".

the last parameter is a similar filter but on the returned values. Hence you can use "J*" to limit the returned values to those starting with "J". This parameter is optional: you can omit it if you don't want any filtering.

the returned value is a comma-separated list of all the matches found.

Example:

Body:
I am currently using lookup function to return multiple values. I got this function from Extend Office.
https://www.extendoffice.com/documents/excel/2706-excel-vlookup-return-multiple-values-in-one-cell.html

I want to edit the codes to cater to my needs where it can further filter the multiple values to only what I need. I am currently using Instr Function to return only values that start with whatever the alphabet  the user keys in. However, the function cannot work as the result would show '#VALUE!'. I have no idea where I have gone wrong.

For example I use key in the function in the sheet itself, 'MYVLOOKUP(C2,Table!A:B,2,"J")'. This means that I only want to return values starting with 'J' but it returns #VALUE!.

Function MYVLOOKUP(pValue As String, pWorkRng As Range, pIndex As Long,
filter As String)
Dim rng As Range
Dim xResult As String
Dim result As Integer

xResult = vbNullString
'the next line trims pWorkRng down to the .UsedRange
Set pWorkRng = Intersect(pWorkRng, pWorkRng.Parent.UsedRange)

For Each rng In pWorkRng
    If rng = pValue Then
        result = InStr(rng.Value, filter, vbTextCompare)
        If result = 1 Then
        xResult = xResult & rng.Offset(0, pIndex - 1) & ","
        Else
        End If
   End If
Next
MYVLOOKUP = Trim(xResult)
End Function

Body:
I think that you are seeking this UDF:

Function MYVLOOKUP(pValue As String, pWorkRng As Range, pIndex As Long, _
                   Optional filter As String = "*")
  Dim rng As Range, ret As String
  For Each rng In Intersect(pWorkRng.Columns(1), pWorkRng.Parent.UsedRange)
    If rng Like pValue Then If rng(1, pIndex) Like filter Then _
      ret = ret & IIf(Len(ret), ",", "") & rng(1, pIndex)
  Next
  MYVLOOKUP = ret
End Function

Notice how to use it:

the first parameter is an exact match on the first column. You can use wildcards (*) inside, such as "xx*" to match anything starting with "xx", or "*yy*" to match anything containing "yy".

the last parameter is a similar filter but on the returned values. Hence you can use "J*" to limit the returned values to those starting with "J". This parameter is optional: you can omit it if you don't want any filtering.

the returned value is a comma-separated list of all the matches found.

Example:


问:
Remote Debugging in Eclipse/Intellij
Can I attach my eclise or Intellij Debugger to an already running remote application?

PS - I know how to remotely debug. But the key part here is that the application is already running and I don't know if the debug port was opened or not. And assuming that it wasn't, can anything be done about it? Or do I have to restart the application?

Just so the readers know, I have already gone through this post
and even though the answer is accepted, it doesn't answer my question.

答:
You can attach debugger to running JVM process (that was not started with debug parameters) but you will have very limited options while in debug session.

Take a look here:

https://docs.oracle.com/javase/8/docs/technotes/guides/jpda/conninv.html

SA PID Attaching Connector

Title: Remote Debugging in Eclipse/Intellij


问:
Linking CXX executable - /usr/bin/ld: cannot find
Hello C++ and/or ROS Experts

I just made a fresh install of Ubuntu 12.04 and ROS.

My old installations was also on ubunru 12.04, and it worked great.

But now when i try to make or rosmake on of my project, i get the follwing error:

```<code>  Linking CXX executable ../bin/robot_task_execution
  /usr/bin/ld: cannot find -lrw_sandbox
  /usr/bin/ld: cannot find -lrw_control
  /usr/bin/ld: cannot find -lrw_algorithms
  /usr/bin/ld: cannot find -lrw_pathplanners
  /usr/bin/ld: cannot find -lrw_pathoptimization
  /usr/bin/ld: cannot find -lrw_task
  /usr/bin/ld: cannot find -lrw_simulation
  /usr/bin/ld: cannot find -lrw_opengl
  /usr/bin/ld: cannot find -lrw_lua
  /usr/bin/ld: cannot find -llua51
  /usr/bin/ld: cannot find -lrw_proximitystrategies
  /usr/bin/ld: cannot find -lyaobi
  /usr/bin/ld: cannot find -lpqp
  /usr/bin/ld: cannot find -lrw
  /usr/bin/ld: cannot find -lrw_qhull
  collect2: ld returned 1 exit status
</code>```

Do you have any idear what this mean, or how to fix this?

I installed ROS like this, maybe i need something else?:

```<code>sudo sh -c 'echo "deb http://packages.ros.org/ros/ubuntu precise main" > /etc/apt/sources.list.d/ros-latest.list'
wget http://packages.ros.org/ros.key -O - | sudo apt-key add -
sudo apt-get update
sudo apt-get install ros-fuerte-desktop-full
echo "source /opt/ros/fuerte/setup.bash" >> ~/.bashrc
. ~/.bashrc
sudo apt-get install python-rosinstall python-rosdep
</code>```

Best regards Bjarke

答:
You can link the libraries directly by adding the -llibs to the g++ command line.

Please check this answer:
Compile roscpp without ros (using g++)

There the linking is done by adding the individual libraries on the command line.

Body:
Hello C++ and/or ROS Experts

I just made a fresh install of Ubuntu 12.04 and ROS.

My old installations was also on ubunru 12.04, and it worked great.

But now when i try to make or rosmake on of my project, i get the follwing error:

  Linking CXX executable ../bin/robot_task_execution
  /usr/bin/ld: cannot find -lrw_sandbox
  /usr/bin/ld: cannot find -lrw_control
  /usr/bin/ld: cannot find -lrw_algorithms
  /usr/bin/ld: cannot find -lrw_pathplanners
  /usr/bin/ld: cannot find -lrw_pathoptimization
  /usr/bin/ld: cannot find -lrw_task
  /usr/bin/ld: cannot find -lrw_simulation
  /usr/bin/ld: cannot find -lrw_opengl
  /usr/bin/ld: cannot find -lrw_lua
  /usr/bin/ld: cannot find -llua51
  /usr/bin/ld: cannot find -lrw_proximitystrategies
  /usr/bin/ld: cannot find -lyaobi
  /usr/bin/ld: cannot find -lpqp
  /usr/bin/ld: cannot find -lrw
  /usr/bin/ld: cannot find -lrw_qhull
  collect2: ld returned 1 exit status

Do you have any idear what this mean, or how to fix this?

I installed ROS like this, maybe i need something else?:

sudo sh -c 'echo "deb http://packages.ros.org/ros/ubuntu precise main" > /etc/apt/sources.list.d/ros-latest.list'
wget http://packages.ros.org/ros.key -O - | sudo apt-key add -
sudo apt-get update
sudo apt-get install ros-fuerte-desktop-full
echo "source /opt/ros/fuerte/setup.bash" >> ~/.bashrc
. ~/.bashrc
sudo apt-get install python-rosinstall python-rosdep

Best regards Bjarke


问:
Bug? UILabel live updating by UITextFieldDelegate is off by one character
Here is a sample app to demonstrate the issue that I ran into:

```<code>import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var aTextField: UITextField!
    @IBOutlet weak var aTextLbl: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        aTextField.delegate = self
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        aTextLbl.text = aTextField.text
        return true
    }
}
</code>```

Here is a demo:

Link to Animated Gif

My question is, how to make it such that the label is exactly synced with what I type in the textfield? Thanks!

答:
Rather than using delegate method shouldChangeCharactersIn, you can use EditingChanged as follows.

```<code>import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var aTextLbl: UILabel!
    @IBOutlet weak var aTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func editingChanged(_ sender: UITextField) {
        aTextLbl.text = aTextField.text
    }
}
</code>```

Body:
Here is a sample app to demonstrate the issue that I ran into:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var aTextField: UITextField!
    @IBOutlet weak var aTextLbl: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        aTextField.delegate = self
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        aTextLbl.text = aTextField.text
        return true
    }
}

Here is a demo:

Link to Animated Gif

My question is, how to make it such that the label is exactly synced with what I type in the textfield? Thanks!

Body:
Rather than using delegate method shouldChangeCharactersIn, you can use EditingChanged as follows.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var aTextLbl: UILabel!
    @IBOutlet weak var aTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func editingChanged(_ sender: UITextField) {
        aTextLbl.text = aTextField.text
    }
}


问:
Nonlinear e^(-x) regression using scipy, python, numpy
The code below is giving me a flat line for the line of best fit rather than a nice curve along the model of e^(-x) that would fit the data.  Can anyone show me how to fix the code below so that it fits my data?</p>

```<code>import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize

def _eNegX_(p,x):
    x0,y0,c,k=p
    y = (c * np.exp(-k*(x-x0))) + y0
    return y

def _eNegX_residuals(p,x,y):
    return y - _eNegX_(p,x)

def Get_eNegX_Coefficients(x,y):
    print 'x is:  ',x
    print 'y is:  ',y

    # Calculate p_guess for the vectors x,y.  Note that p_guess is the
    # starting estimate for the minimization.
    p_guess=(np.median(x),np.min(y),np.max(y),.01)

    # Calls the leastsq() function, which calls the residuals function with an initial
    # guess for the parameters and with the x and y vectors.  Note that the residuals
    # function also calls the _eNegX_ function.  This will return the parameters p that
    # minimize the least squares error of the _eNegX_ function with respect to the original
    # x and y coordinate vectors that are sent to it.
    p, cov, infodict, mesg, ier = scipy.optimize.leastsq(
        _eNegX_residuals,p_guess,args=(x,y),full_output=1,warning=True)

    # Define the optimal values for each element of p that were returned by the leastsq() function.
    x0,y0,c,k=p
    print('''Reference data:\
    x0 = {x0}
    y0 = {y0}
    c = {c}
    k = {k}
    '''.format(x0=x0,y0=y0,c=c,k=k))

    print 'x.min() is:  ',x.min()
    print 'x.max() is:  ',x.max()
    # Create a numpy array of x-values
    numPoints = np.floor((x.max()-x.min())*100)
    xp = np.linspace(x.min(), x.max(), numPoints)
    print 'numPoints is:  ',numPoints
    print 'xp is:  ',xp
    print 'p is:  ',p
    pxp=_eNegX_(p,xp)
    print 'pxp is:  ',pxp

    # Plot the results
    plt.plot(x, y, '>', xp, pxp, 'g-')
    plt.xlabel('BPM%Rest')
    plt.ylabel('LVET/BPM',rotation='vertical')
    plt.xlim(0,3)
    plt.ylim(0,4)
    plt.grid(True)
    plt.show()

    return p

# Declare raw data for use in creating regression equation
x = np.array([1,1.425,1.736,2.178,2.518],dtype='float')
y = np.array([3.489,2.256,1.640,1.043,0.853],dtype='float')

p=Get_eNegX_Coefficients(x,y)
</code>```

答:
It looks like it's a problem with your initial guesses; something like (1, 1, 1, 1) works fine:

You have

```<code>p_guess=(np.median(x),np.min(y),np.max(y),.01)
</code>```

for the function

```<code>def _eNegX_(p,x):
    x0,y0,c,k=p
    y = (c * np.exp(-k*(x-x0))) + y0
    return y
</code>```

So that's test_data_maxe^( -.01(x - test_data_median)) + test_data_min

I don't know much about the art of choosing good starting parameters, but I can say a few things.  leastsq is finding a local minimum here - the key in choosing these values is to find the right mountain to climb, not to try to cut down on the work that the minimization algorithm has to do.  Your initial guess looks like this (green):
(1.736, 0.85299999999999998, 3.4889999999999999, 0.01)

which results in your flat line (blue):
(-59.20295956,   1.8562    ,   1.03477144,   0.69483784)

Greater gains were made in adjusting the height of the line than in increasing the k value.  If you know you're fitting to this kind of data, use a larger k.  If you don't know, I guess you could try to find a decent k value by sampling your data, or working back from the slope between an average of the first half and the second half, but I wouldn't know how to go about that.

Edit:  You could also start with several guesses, run the minimization several times, and take the line with the lowest residuals.

ContentLicense: CC BY-SA 2.5

Body:
The code below is giving me a flat line for the line of best fit rather than a nice curve along the model of e^(-x) that would fit the data.  Can anyone show me how to fix the code below so that it fits my data?

import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize

def _eNegX_(p,x):
    x0,y0,c,k=p
    y = (c * np.exp(-k*(x-x0))) + y0
    return y

def _eNegX_residuals(p,x,y):
    return y - _eNegX_(p,x)

def Get_eNegX_Coefficients(x,y):
    print 'x is:  ',x
    print 'y is:  ',y

    # Calculate p_guess for the vectors x,y.  Note that p_guess is the
    # starting estimate for the minimization.
    p_guess=(np.median(x),np.min(y),np.max(y),.01)

    # Calls the leastsq() function, which calls the residuals function with an initial
    # guess for the parameters and with the x and y vectors.  Note that the residuals
    # function also calls the _eNegX_ function.  This will return the parameters p that
    # minimize the least squares error of the _eNegX_ function with respect to the original
    # x and y coordinate vectors that are sent to it.
    p, cov, infodict, mesg, ier = scipy.optimize.leastsq(
        _eNegX_residuals,p_guess,args=(x,y),full_output=1,warning=True)

    # Define the optimal values for each element of p that were returned by the leastsq() function.
    x0,y0,c,k=p
    print('''Reference data:\
    x0 = {x0}
    y0 = {y0}
    c = {c}
    k = {k}
    '''.format(x0=x0,y0=y0,c=c,k=k))

    print 'x.min() is:  ',x.min()
    print 'x.max() is:  ',x.max()
    # Create a numpy array of x-values
    numPoints = np.floor((x.max()-x.min())*100)
    xp = np.linspace(x.min(), x.max(), numPoints)
    print 'numPoints is:  ',numPoints
    print 'xp is:  ',xp
    print 'p is:  ',p
    pxp=_eNegX_(p,xp)
    print 'pxp is:  ',pxp

    # Plot the results
    plt.plot(x, y, '>', xp, pxp, 'g-')
    plt.xlabel('BPM%Rest')
    plt.ylabel('LVET/BPM',rotation='vertical')
    plt.xlim(0,3)
    plt.ylim(0,4)
    plt.grid(True)
    plt.show()

    return p

# Declare raw data for use in creating regression equation
x = np.array([1,1.425,1.736,2.178,2.518],dtype='float')
y = np.array([3.489,2.256,1.640,1.043,0.853],dtype='float')

p=Get_eNegX_Coefficients(x,y)

Body:
It looks like it's a problem with your initial guesses; something like (1, 1, 1, 1) works fine:

You have

p_guess=(np.median(x),np.min(y),np.max(y),.01)

for the function

def _eNegX_(p,x):
    x0,y0,c,k=p
    y = (c * np.exp(-k*(x-x0))) + y0
    return y

So that's test_data_maxe^( -.01(x - test_data_median)) + test_data_min

I don't know much about the art of choosing good starting parameters, but I can say a few things.  leastsq is finding a local minimum here - the key in choosing these values is to find the right mountain to climb, not to try to cut down on the work that the minimization algorithm has to do.  Your initial guess looks like this (green):
(1.736, 0.85299999999999998, 3.4889999999999999, 0.01)

which results in your flat line (blue):
(-59.20295956,   1.8562    ,   1.03477144,   0.69483784)

Greater gains were made in adjusting the height of the line than in increasing the k value.  If you know you're fitting to this kind of data, use a larger k.  If you don't know, I guess you could try to find a decent k value by sampling your data, or working back from the slope between an average of the first half and the second half, but I wouldn't know how to go about that.

Edit:  You could also start with several guesses, run the minimization several times, and take the line with the lowest residuals.


问:
Find the count of each category in a dataframe for uniques value of third column
I have dataframe df1:

```<code>A|A2|A3
-+--+--
a|ut|x
a|tv|y
a|ut|x
a|pq|y
a|ut|y
b|st|x
b|qp|x
b|nt|y
c|st|x
c|st|x
c|st|y
c|st|z
</code>```

I want to know the frequency of A2 with unique A3 for each A, i.e. I want following output:

```<code>A|A2|freq
-+--+----
a|ut|2
a|tv|1
a|pq|1
b|st|1
b|qp|1
b|nt|1
c|st|3
</code>```

I tried

```<code>count(df1, A, A2, A3)
</code>```

but get the error

Error in count(df1, A, A2, A3)  :  unused argument A3

答:
With dplyr, you can use distinct to remove duplicated rows, then count to aggregate:

library(dplyr)

df1 <- data_frame(A = c("a", "a", "a", "a", "a", "b", "b", "b", "c", "c", "c", "c"),
                  A2 = c("ut", "tv", "ut", "pq", "ut", "st", "qp", "nt", "st", "st", "st", "st"),
                  A3 = c("x", "y", "x", "y", "y", "x", "x", "y", "x", "x", "y", "z"))

df2 <- df1 %>% distinct() %>% count(A, A2)

df2
#> # A tibble: 7 x 3
#>       A    A2     n
#>   <chr> <chr> <int>
#> 1     a    pq     1
#> 2     a    tv     1
#> 3     a    ut     2
#> 4     b    nt     1
#> 5     b    qp     1
#> 6     b    st     1
#> 7     c    st     3
```

<p>or more generalizably, use <code>n_distinct</code>:</p>

<pre class="lang-r prettyprint-override"><code>df1 %>% group_by(A, A2) %>% summarise(freq = n_distinct(A3))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have dataframe df1:

A|A2|A3
-+--+--
a|ut|x
a|tv|y
a|ut|x
a|pq|y
a|ut|y
b|st|x
b|qp|x
b|nt|y
c|st|x
c|st|x
c|st|y
c|st|z

I want to know the frequency of A2 with unique A3 for each A, i.e. I want following output:

A|A2|freq
-+--+----
a|ut|2
a|tv|1
a|pq|1
b|st|1
b|qp|1
b|nt|1
c|st|3

I tried

count(df1, A, A2, A3)

but get the error

Error in count(df1, A, A2, A3)  :  unused argument A3

Body:
With dplyr, you can use distinct to remove duplicated rows, then count to aggregate:

library(dplyr)

df1 <- data_frame(A = c("a", "a", "a", "a", "a", "b", "b", "b", "c", "c", "c", "c"),
                  A2 = c("ut", "tv", "ut", "pq", "ut", "st", "qp", "nt", "st", "st", "st", "st"),
                  A3 = c("x", "y", "x", "y", "y", "x", "x", "y", "x", "x", "y", "z"))

df2 <- df1 %>% distinct() %>% count(A, A2)

df2
#> # A tibble: 7 x 3
#>       A    A2     n
#>   <chr> <chr> <int>
#> 1     a    pq     1
#> 2     a    tv     1
#> 3     a    ut     2
#> 4     b    nt     1
#> 5     b    qp     1
#> 6     b    st     1
#> 7     c    st     3

or more generalizably, use n_distinct:

df1 %>% group_by(A, A2) %>% summarise(freq = n_distinct(A3))


问:
Unable to load database file in android
I have a sqlite database file called MainExerciseDatabaseOne.db stored in my app/src/main/assets/databases folder.  I'm trying to open the file in a function of my main activity:

```<code>private ExerciseDb createDatabase(){
    final String inFileName = "/data/data/<mypackage>/databases/MainExerciseDatabaseOne.db";
    File dbFile = new File(inFileName);
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(dbFile);
    } catch (FileNotFoundException e) {
        Log.e("error",e.toString());
    }
    String outFileName = DB_PATH + ExerciseDb.DATABASE_NAME;
    // Open the empty db as the output stream
    OutputStream output = null;
    try {
        output = new FileOutputStream(outFileName);
    } catch (FileNotFoundException e) {
        Log.e("error",e.toString());
    }
    // Transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    try {
        while ((length = fis.read(buffer))>0){
            output.write(buffer, 0, length);
        }
    } catch (IOException e) {
        Log.e("error",e.toString());
    }

    // Close the streams
    try {
        output.flush();
        output.close();
        fis.close();
    } catch (IOException e) {
        Log.e("error",e.toString());
    }
    ExerciseDb ret = new ExerciseDb(this);
    return ret;
}
</code>```

But I get a file not found exception on the line:

```<code> fis = new FileInputStream(dbFile);
</code>```

In every tutorial I look at this seems to be the correct path to access this file so I am not sure why its not working.  It's also strange because this exact code did work until I uninstalled the app on my phone and did a clean build and reinstalled the app from android studio

答:
Try:

to use your package name (e.g., com.example.package) instead of myactivity in /data/data/com.example.package/databases/MainExerciseDatabaseOne.db

Use mkdirs for /data/data/com.example.package/databases/. I'm not sure that this directory exists by default.

Use file without extention (just a suggestion): MainExerciseDatabaseOne.db > MainExerciseDatabaseOne

Title: Unable to load database file in android

Body:
I have a sqlite database file called MainExerciseDatabaseOne.db stored in my app/src/main/assets/databases folder.  I'm trying to open the file in a function of my main activity:

private ExerciseDb createDatabase(){
    final String inFileName = "/data/data/<mypackage>/databases/MainExerciseDatabaseOne.db";
    File dbFile = new File(inFileName);
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(dbFile);
    } catch (FileNotFoundException e) {
        Log.e("error",e.toString());
    }
    String outFileName = DB_PATH + ExerciseDb.DATABASE_NAME;
    // Open the empty db as the output stream
    OutputStream output = null;
    try {
        output = new FileOutputStream(outFileName);
    } catch (FileNotFoundException e) {
        Log.e("error",e.toString());
    }
    // Transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    try {
        while ((length = fis.read(buffer))>0){
            output.write(buffer, 0, length);
        }
    } catch (IOException e) {
        Log.e("error",e.toString());
    }

    // Close the streams
    try {
        output.flush();
        output.close();
        fis.close();
    } catch (IOException e) {
        Log.e("error",e.toString());
    }
    ExerciseDb ret = new ExerciseDb(this);
    return ret;
}

But I get a file not found exception on the line:

 fis = new FileInputStream(dbFile);

In every tutorial I look at this seems to be the correct path to access this file so I am not sure why its not working.  It's also strange because this exact code did work until I uninstalled the app on my phone and did a clean build and reinstalled the app from android studio


问:
Hibernate 3.x to 5.x migration issues
I am migrating hibernate 3.x to latest version 5.x and I see many issues that I need some help with.

SessionFactory.evict() - My code uses SessionFactory.evict() which I don't see in 5.x. What should I replace this code with? HibernateTemplate.evict()?

Changed AnnotationSessionFactoryBean to LocalSessionFactoryBean in spring config xml. AnnotationSessionFactoryBean had properties configurationClass and namingStrategy. What should these be replaced with?

Class HibernateInterceptor is used in spring config xml and now it is not found in spring 4.x under hibernate5 package.

ConnectionProvider.configure() is missing in Hibernate.

I am using,
Spring - 4.3.9.RELEASE
Hibernate - 5.2.10.Final

答:
you see this image, then find it on github.

about version 5.2.9

Title: Hibernate 3.x to 5.x migration issues


问:
python - List hold data after del, none, []
I am building a short game (for a study project). The game is meant to be run in Python Shell (using 3.6.1).

The issue I am having is upon "quit" (exit the game). If a users types "quit" during an input prompt, the game exits. The functionality is fine, however if the user than RESTARTS the game, the list used to hold user data remains populated. It is critical that the list get emptied, and I tried setting list = [] and list = NONE, but neither emptied the list. What gives?

Here is a much condensed version of the code:

```<code>import sys
class Game(object):

myList = [] #init list

def inflate_list(self):
    for x in range(0, 10):
        self.myList.append([x]) #just putting x into the list (as example)
    print(self.myList)
    self.run_game()

def check_user_input(self, thisEntry):
    try:
        val = int(thisEntry)#an integer was entered
        return True

    except ValueError: #needed because an error will be thrown
        #integer not entered

        if thisEntry == "quit":
            #user wants to quit
            print("..thanks for playing")

            #cleanup
            self.thisGame = None
            self.myList = []
            del self.myList

            print("..exiting")
            #exit
            sys.exit()

        else:
            print("Invalid entry. Please enter a num. Quit to end game")
            return False

def run_game(self):

    #init
    getUserInput = False

    #loop
    while getUserInput == False:

        #check and check user's input
        guess = input("Guess a coordinate : ")
        getUserInput = self.check_user_input(guess)

        print (guess, " was entered.")

#start game
thisGame = Game()
thisGame.inflate_list()
</code>```

Run Example

```<code>>>>thisGame = Game()
>>>thisGame.inflate_list()
[[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]
Guess a coordinate : aaaaa
Invalid entry. Please enter a coordinate. Quit to end game
aaaaa  was entered.
Guess a coordinate : quit
..thanks for playing
..exiting
>>>thisGame = Game()
>>>thisGame.inflate_list()
[[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]
Guess a coordinate :
</code>```

The second time the game is started, the list still holds data....

答:
Change this line:

```<code>myList = [] #init list
</code>```

to this:

```<code>def __init__(self):
    self.myList = [] #init list
</code>```

(After that fix, none of the "cleanup" should be needed.)

As @JoshLee pointed out in the comments above, this Stack Overflow question is a good place to learn about the difference between a class attribute and an instance attribute: Python Class Members.

Body:
I am building a short game (for a study project). The game is meant to be run in Python Shell (using 3.6.1).

The issue I am having is upon "quit" (exit the game). If a users types "quit" during an input prompt, the game exits. The functionality is fine, however if the user than RESTARTS the game, the list used to hold user data remains populated. It is critical that the list get emptied, and I tried setting list = [] and list = NONE, but neither emptied the list. What gives?

Here is a much condensed version of the code:

import sys
class Game(object):

myList = [] #init list

def inflate_list(self):
    for x in range(0, 10):
        self.myList.append([x]) #just putting x into the list (as example)
    print(self.myList)
    self.run_game()

def check_user_input(self, thisEntry):
    try:
        val = int(thisEntry)#an integer was entered
        return True

    except ValueError: #needed because an error will be thrown
        #integer not entered

        if thisEntry == "quit":
            #user wants to quit
            print("..thanks for playing")

            #cleanup
            self.thisGame = None
            self.myList = []
            del self.myList

            print("..exiting")
            #exit
            sys.exit()

        else:
            print("Invalid entry. Please enter a num. Quit to end game")
            return False

def run_game(self):

    #init
    getUserInput = False

    #loop
    while getUserInput == False:

        #check and check user's input
        guess = input("Guess a coordinate : ")
        getUserInput = self.check_user_input(guess)

        print (guess, " was entered.")

#start game
thisGame = Game()
thisGame.inflate_list()

Run Example

>>>thisGame = Game()
>>>thisGame.inflate_list()
[[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]
Guess a coordinate : aaaaa
Invalid entry. Please enter a coordinate. Quit to end game
aaaaa  was entered.
Guess a coordinate : quit
..thanks for playing
..exiting
>>>thisGame = Game()
>>>thisGame.inflate_list()
[[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]
Guess a coordinate :

The second time the game is started, the list still holds data....

Body:
Change this line:

myList = [] #init list

to this:

def __init__(self):
    self.myList = [] #init list

(After that fix, none of the "cleanup" should be needed.)

As @JoshLee pointed out in the comments above, this Stack Overflow question is a good place to learn about the difference between a class attribute and an instance attribute: Python Class Members.


问:
What is wrong with this package structure in python?
I have the following structure:

```<code>/MyApp
   /Module_A
   __init__.py
   serviceFile.py
   /Module_B
   clientFile.py
</code>```

I am trying to call a function in ServiceFile.py from ClientFile.py

```<code>From MyApp.Module_a import ServiceFile
</code>```

but I am getting the error

ImportError: No module named MyApp.Module_a

Why?
BTW, When I run this from pyCharm it works fine only in CDM.
Both uses python 2.7

答:
You should put a __init__.py file in both MyApp directory and Module_B. That makes the call from MyApp.Module_B import clientFile work for me. Here's my tree:

```<code>└── MyApp
    ├── __init__.py
    ├── Module_B
    │   ├── clientFile.py
    │   ├── __init__.py
</code>```

By default Python won't know a certain .py file is part of your module if it isn't "linked" to an __init__.py file.

Body:
I have the following structure:

/MyApp
   /Module_A
   __init__.py
   serviceFile.py
   /Module_B
   clientFile.py

I am trying to call a function in ServiceFile.py from ClientFile.py

From MyApp.Module_a import ServiceFile

but I am getting the error

ImportError: No module named MyApp.Module_a

Why?
BTW, When I run this from pyCharm it works fine only in CDM.
Both uses python 2.7

Body:
You should put a __init__.py file in both MyApp directory and Module_B. That makes the call from MyApp.Module_B import clientFile work for me. Here's my tree:

└── MyApp
    ├── __init__.py
    ├── Module_B
    │   ├── clientFile.py
    │   ├── __init__.py

By default Python won't know a certain .py file is part of your module if it isn't "linked" to an __init__.py file.


问:
.getText() not retrieving the text message from div class tag
From the following HTML code

```<code><div class="message-main-contents">
  <div class="message-title">Title Message</div>
  <div class="message-content">
    <div class="licenseexpiryannouncement">
        <div>
            Message Content 1
            <a class="licenseexpiryannouncement-installlicenselink">Link that can be clicked</a>
            under Home> Upload.
        </div>
        <div>Message Content 2</div>
    </div>
</div>
</code>```

I am trying to retrieve the "Title Message" text using the following code but is returning empty string

```<code>@FindBy(how = How.XPATH, using = "//div[contains(@class, 'message-title')]")
private WebElement contentMessageTitle;

String titleMessage = contentMessageTitle.getText();
System.out.println(titleMessage);
</code>```

答:
Here is the Answer to your Question:

```<code>@FindBy(how = How.XPATH, using = "//div[@class='message-title']")
private WebElement contentMessageTitle;

String titleMessage = contentMessageTitle.getText();
System.out.println(titleMessage);
</code>```

or

```<code>@FindBy(how = How.XPATH, using = "//div[@class='message-main-contents']/div[@class='message-title']")
private WebElement contentMessageTitle;

String titleMessage = contentMessageTitle.getText();
System.out.println(titleMessage);
</code>```

or

```<code>@FindBy(how = How.XPATH, using = "//div[@class='message-main-contents']/div[@class='message-title']")
private WebElement contentMessageTitle;

String titleMessage = contentMessageTitle.getAttribute("text");
System.out.println(titleMessage);
</code>```

Let me know if this Answers your Question.

Body:
From the following HTML code

Title Message

            Message Content 1
            Link that can be clicked
            under Home> Upload.

Message Content 2

I am trying to retrieve the "Title Message" text using the following code but is returning empty string

@FindBy(how = How.XPATH, using = "//div[contains(@class, 'message-title')]")
private WebElement contentMessageTitle;

String titleMessage = contentMessageTitle.getText();
System.out.println(titleMessage);

Body:
Here is the Answer to your Question:

@FindBy(how = How.XPATH, using = "//div[@class='message-title']")
private WebElement contentMessageTitle;

String titleMessage = contentMessageTitle.getText();
System.out.println(titleMessage);

or

@FindBy(how = How.XPATH, using = "//div[@class='message-main-contents']/div[@class='message-title']")
private WebElement contentMessageTitle;

String titleMessage = contentMessageTitle.getText();
System.out.println(titleMessage);

or

@FindBy(how = How.XPATH, using = "//div[@class='message-main-contents']/div[@class='message-title']")
private WebElement contentMessageTitle;

String titleMessage = contentMessageTitle.getAttribute("text");
System.out.println(titleMessage);

Let me know if this Answers your Question.


问:
Can I send periodic messages to my Android app users?
Is it possible to make a app on Android such that whoever downloads this app receives a message from me weekly? I want to be the only person who can write on this message board and no one else. If this is possible, where should I start looking for tutorials about doing this sort of stuff?</p>

答: You can create a RSS/Atom feed for yourself. Your android app can then just sync to this feed. Update the feed as often as you like. If you like this approach I can give more details. </p>


问:
Get multiple element value in jquery
code

HTML

```<code>    <table>

    <tr>
       <td><input type="hidden" name="zxc_0" value="105" quantity="1"></td>
    </tr>

    <tr>
       <td><input type="hidden" name="zxc_1" value="155" quantity="3"></td>
    </tr>

    <tr>
       <td><input type="hidden" name="zxc_2" value="15" quantity="7"></td>
    </tr>

    </table>

<a id="button-generate" class="button" style="">Generate</a>
</code>```

Question:

The above code is that html store with the data value, so how can I using java script to store the value data into Array once the user click the generate button?

答:
$("#button-generate").on("click", function(){

  var values = $('input').map(function() {
    return $(this).attr('value');
  }).toArray();

  console.log(values);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>

    <tr>
       <td><input type="hidden" name="zxc_0" value="105" quantity="1"></td>
    </tr>

    <tr>
       <td><input type="hidden" name="zxc_1" value="155" quantity="3"></td>
    </tr>

    <tr>
       <td><input type="hidden" name="zxc_2" value="15" quantity="7"></td>
    </tr>

    </table>

Generate</code>```

Title: Get multiple element value in jquery

Body:
code

HTML

       <input type="hidden" name="zxc_0" value="105" quantity="1">

       <input type="hidden" name="zxc_1" value="155" quantity="3">

       <input type="hidden" name="zxc_2" value="15" quantity="7">

Generate

Question:

The above code is that html store with the data value, so how can I using java script to store the value data into Array once the user click the generate button?

Body:
$("#button-generate").on("click", function(){

  var values = $('input').map(function() {
    return $(this).attr('value');
  }).toArray();

  console.log(values);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>

    <tr>
       <td><input type="hidden" name="zxc_0" value="105" quantity="1"></td>
    </tr>

    <tr>
       <td><input type="hidden" name="zxc_1" value="155" quantity="3"></td>
    </tr>

    <tr>
       <td><input type="hidden" name="zxc_2" value="15" quantity="7"></td>
    </tr>

    </table>

<a id="button-generate" class="button" style="">Generate</a>


问:
Parallel Stream in scala
is there any (hopefully out of the box) way to traverse an Scala stream in parallel?

for instance, see this java 8 code:

```<code>String[] s = {"a","b","c","d","e"};
List<String> list = Arrays.asList(s);
list.parallelStream().forEach(System.out::println);
</code>```

this will print all list stream contents in parallel..
however, to my understanding, streams in scala are sequential.

any workarounds for this?

EDIT:
please notice that, streams allows us to process data as they arrive. then, if data is not necessary, remove them from memory.
for instance:

```<code>"abcd".toStream.filter { x =>
  println(s"1 filter $x")
   if(x.toInt%2==0) true;else false;
  } //end of first block
  .foreach { x =>
  println(s"2 filter->$x")
  } //end of second block
</code>```

will output something like this:

1 filter a

1 filter b

2 filter->b

1 filter c

1 filter d

2 filter->d

on the other hand, the below code, will process data in blocks. keeping variables in memory on each transformation:

```<code>  "abcd".toVector.par.filter { x =>
  println(s"1 filter $x")
   if(x.toInt%2==0) true;else false;
  } //end of first block
  .foreach { x =>
  println(s"2 filter->$x")
  } //end of second block
</code>```

output:
1 filter c

1 filter a

1 filter b

1 filter d

2 filter->b

2 filter->d

答:
You can use parallel collections </p>

```<code>import scala.collection.parallel.immutable.ParVector

val pv = new ParVector[Int]

val pv = Vector(1,2,3,4,5,6,7,8,9).par

pv.foreach(x => println(x));
</code>```

Title: Parallel Stream in scala

Body:
is there any (hopefully out of the box) way to traverse an Scala stream in parallel?

for instance, see this java 8 code:

String[] s = {"a","b","c","d","e"};
List<String> list = Arrays.asList(s);
list.parallelStream().forEach(System.out::println);

this will print all list stream contents in parallel..
however, to my understanding, streams in scala are sequential.

any workarounds for this?

EDIT:
please notice that, streams allows us to process data as they arrive. then, if data is not necessary, remove them from memory.
for instance:

"abcd".toStream.filter { x =>
  println(s"1 filter $x")
   if(x.toInt%2==0) true;else false;
  } //end of first block
  .foreach { x =>
  println(s"2 filter->$x")
  } //end of second block

will output something like this:

1 filter a

1 filter b

2 filter->b

1 filter c

1 filter d

2 filter->d

on the other hand, the below code, will process data in blocks. keeping variables in memory on each transformation:

  "abcd".toVector.par.filter { x =>
  println(s"1 filter $x")
   if(x.toInt%2==0) true;else false;
  } //end of first block
  .foreach { x =>
  println(s"2 filter->$x")
  } //end of second block

output:
1 filter c

1 filter a

1 filter b

1 filter d

2 filter->b

2 filter->d

Body:
You can use parallel collections

import scala.collection.parallel.immutable.ParVector

val pv = new ParVector[Int]

val pv = Vector(1,2,3,4,5,6,7,8,9).par

pv.foreach(x => println(x));


问:
How to Animate Sprites in Gamemaker
I would like to make my sprite stand still when not moving and animate when keys are pressed. I have a sprite with 8 images and an object that I have created where I assigned the sprite. I have added a key press and key release command and I have added a section where you can put your own custom code. However when I play the game the sprite is animating right away until I press a key and then he stops animating and moves in a still position. How can I fix this?</p>

```<code>if image_index = 0
{
image_speed = 0;
}
else
{
image_index = 1;
image_speed = 1;
}
</code>```

答:
Your answer is in what you posted.

So in other words. If your going to do it this way. Why not just use 3 sprites one for stand one for left and one for right?

of if you insist on not doing that then just set image_index to 0 to start so

Title: How to Animate Sprites in Gamemaker

Body:
I would like to make my sprite stand still when not moving and animate when keys are pressed. I have a sprite with 8 images and an object that I have created where I assigned the sprite. I have added a key press and key release command and I have added a section where you can put your own custom code. However when I play the game the sprite is animating right away until I press a key and then he stops animating and moves in a still position. How can I fix this?

if image_index = 0
{
image_speed = 0;
}
else
{
image_index = 1;
image_speed = 1;
}


问:
Using "generated strings" (stringWithFormat) as keys for NSDictionary
I would like to do something like this:

```<code>#define GETKEY (a) ([NSString stringWithFormat:@"%d",a])

NSMutableDictionary *mutableDictionay=[NSMutableDictionary dictionary];
//population of dictionary
[mutableDictionary setObject:anObject forKey:GETKEY(someIntValue)];
//... then retrive the object
[mutableDictionary getObjectForKey:GETKEY(someIntValue)];
</code>```

But I'm concerned the stringWithFormat method returns a different instance of NSString with the same value, I mean like having, 2 strings: "0" and another instance with value "0". I would like to know if this is a safe way to get and set the objects in the dictionary. If not, what other way could be the best way to "generate" a key object from an integer?

答:
Yes, what you're doing is perfectly safe, and will work as expected. The keys of a dictionary when getting and setting are compared using the isEqual method, which only checks the values of the strings, and not their addresses. "0" and "0" are equal, regardless of whether they are the same instance or not.

You can read more about the isEqual documentation in the NSObject Protocol Reference. Just be aware that == and isEqual are not the same thing (== checks addresses, isEqual checks values).

Body:
I would like to do something like this:

#define GETKEY (a) ([NSString stringWithFormat:@"%d",a])

NSMutableDictionary *mutableDictionay=[NSMutableDictionary dictionary];
//population of dictionary
[mutableDictionary setObject:anObject forKey:GETKEY(someIntValue)];
//... then retrive the object
[mutableDictionary getObjectForKey:GETKEY(someIntValue)];

But I'm concerned the stringWithFormat method returns a different instance of NSString with the same value, I mean like having, 2 strings: "0" and another instance with value "0". I would like to know if this is a safe way to get and set the objects in the dictionary. If not, what other way could be the best way to "generate" a key object from an integer?


问:
hive order by 1 asc results in incorrect oder
The query:

SELECT DISTINCT   seg from mytable ORDER BY 1 ASC results in

```<code>+-------+--+
|  seg  |
+-------+--+
| NONE  |
| AFS   |
+-------+--+
</code>```

where as SELECT DISTINCT   seg from mytable ORDER BY seg ASC results in

```<code>+-------+--+
|  seg  |
+-------+--+
| AFS   |
| NONE  |
+-------+--+
</code>```

Is referring to the columns by position in the ORDER BY not supported by Hive?

答:
Order by position is supported since Hive 0.11 but only from Hive 2.2.0 it is turned on by default.

https://cwiki.apache.org/confluence/display/Hive/Configuration+Properties

hive.groupby.orderby.position.alias

  Default Value: false

  Added In: Hive 0.11.0 with HIVE-581

  Deprecated In: Hive 2.2.0 with HIVE-15797

  Whether to enable using Column Position Alias in GROUP BY and ORDER BY clauses of queries (deprecated as of Hive 2.2.0; use hive.groupby.position.alias and hive.orderby.position.alias instead).

hive.orderby.position.alias

  Default Value: true

  Added In: Hive 2.2.0 with HIVE-15797

  Whether to enable using Column Position Alias in ORDER BY.

Body:
The query:

SELECT DISTINCT   seg from mytable ORDER BY 1 ASC results in

+-------+--+
|  seg  |
+-------+--+
| NONE  |
| AFS   |
+-------+--+

where as SELECT DISTINCT   seg from mytable ORDER BY seg ASC results in

+-------+--+
|  seg  |
+-------+--+
| AFS   |
| NONE  |
+-------+--+

Is referring to the columns by position in the ORDER BY not supported by Hive?


问:
okHttp3 java.lang.NoSuchMethodError: No virtual method setCallWebSocket
I've updated from okhttp + retrofit to okhttp3 + retrofit2 but my app doesn't start cause of this Exception</p>

```<code>FATAL EXCEPTION: EventThread
Process: appli.speaky.com, PID: 14705
java.lang.NoSuchMethodError: No virtual method setCallWebSocket(Lokhttp3/Call;)V in class Lokhttp3/internal/Internal; or its super classes (declaration of 'okhttp3.internal.Internal' appears in /data/data/appli.example.com/files/instant-run/dex/slice-okhttp-3.6.0_29bb10e5f590229716bfa8daf196d09ea67f56a8-classes.dex)
    at okhttp3.ws.WebSocketCall.enqueue(WebSocketCall.java:108)
    at io.socket.engineio.client.transports.WebSocket.doOpen(WebSocket.java:84)
    at io.socket.engineio.client.Transport$1.run(Transport.java:82)
    at io.socket.thread.EventThread.exec(EventThread.java:55)
    at io.socket.engineio.client.Transport.open(Transport.java:77)
    at io.socket.engineio.client.Socket.probe(Socket.java:472)
    at io.socket.engineio.client.Socket.onOpen(Socket.java:485)
    at io.socket.engineio.client.Socket.onHandshake(Socket.java:526)
    at io.socket.engineio.client.Socket.onPacket(Socket.java:499)
    at io.socket.engineio.client.Socket.access$1000(Socket.java:31)
    at io.socket.engineio.client.Socket$5.call(Socket.java:313)
    at io.socket.emitter.Emitter.emit(Emitter.java:117)
    at io.socket.engineio.client.Transport.onPacket(Transport.java:134)
    at io.socket.engineio.client.transports.Polling.access$700(Polling.java:17)
    at io.socket.engineio.client.transports.Polling$2.call(Polling.java:124)
    at io.socket.engineio.parser.Parser.decodePayload(Parser.java:251)
    at io.socket.engineio.client.transports.Polling._onData(Polling.java:134)
    at io.socket.engineio.client.transports.Polling.onData(Polling.java:106)
    at io.socket.engineio.client.transports.PollingXHR$5$1.run(PollingXHR.java:111)
    at io.socket.thread.EventThread$2.run(EventThread.java:80)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
    at java.lang.Thread.run(Thread.java:761)
</code>```

答:
Hi there，I have the same issue just days ago(my app is a react-native) ,I just use the 3.4.1 version to replace the latest，and solved it！

```<code>compile "com.squareup.okhttp3:okhttp:3.4.1"
compile "com.squareup.okhttp3:logging-interceptor:3.4.1"
</code>```

and I guess it is caused by the Retrofit2's okhttp lib

Body:
I've updated from okhttp + retrofit to okhttp3 + retrofit2 but my app doesn't start cause of this Exception

FATAL EXCEPTION: EventThread
Process: appli.speaky.com, PID: 14705
java.lang.NoSuchMethodError: No virtual method setCallWebSocket(Lokhttp3/Call;)V in class Lokhttp3/internal/Internal; or its super classes (declaration of 'okhttp3.internal.Internal' appears in /data/data/appli.example.com/files/instant-run/dex/slice-okhttp-3.6.0_29bb10e5f590229716bfa8daf196d09ea67f56a8-classes.dex)
    at okhttp3.ws.WebSocketCall.enqueue(WebSocketCall.java:108)
    at io.socket.engineio.client.transports.WebSocket.doOpen(WebSocket.java:84)
    at io.socket.engineio.client.Transport$1.run(Transport.java:82)
    at io.socket.thread.EventThread.exec(EventThread.java:55)
    at io.socket.engineio.client.Transport.open(Transport.java:77)
    at io.socket.engineio.client.Socket.probe(Socket.java:472)
    at io.socket.engineio.client.Socket.onOpen(Socket.java:485)
    at io.socket.engineio.client.Socket.onHandshake(Socket.java:526)
    at io.socket.engineio.client.Socket.onPacket(Socket.java:499)
    at io.socket.engineio.client.Socket.access$1000(Socket.java:31)
    at io.socket.engineio.client.Socket$5.call(Socket.java:313)
    at io.socket.emitter.Emitter.emit(Emitter.java:117)
    at io.socket.engineio.client.Transport.onPacket(Transport.java:134)
    at io.socket.engineio.client.transports.Polling.access$700(Polling.java:17)
    at io.socket.engineio.client.transports.Polling$2.call(Polling.java:124)
    at io.socket.engineio.parser.Parser.decodePayload(Parser.java:251)
    at io.socket.engineio.client.transports.Polling._onData(Polling.java:134)
    at io.socket.engineio.client.transports.Polling.onData(Polling.java:106)
    at io.socket.engineio.client.transports.PollingXHR$5$1.run(PollingXHR.java:111)
    at io.socket.thread.EventThread$2.run(EventThread.java:80)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
    at java.lang.Thread.run(Thread.java:761)

Body:
Hi there，I have the same issue just days ago(my app is a react-native) ,I just use the 3.4.1 version to replace the latest，and solved it！

compile "com.squareup.okhttp3:okhttp:3.4.1"
compile "com.squareup.okhttp3:logging-interceptor:3.4.1"

and I guess it is caused by the Retrofit2's okhttp lib


问:
php - why is my query not working?
I just created a .php file, unfortunately my sql query is not working on my web hosting but the .php file is working perfectly. so the problem is, my sql query is failing to be executed

It says:

Post Gagal or Post failed (in english)

can you tell why I have an sql error and how to fix this error

this my php code

```<code>                        date_default_timezone_set("Asia/Bangkok");
            ob_start();
             session_start();
            require 'connection.php';

             // if session is not set this will redirect to login page
             if( !isset($_SESSION['user']) ) {
              header("Location: loginpanel.php");
              exit;
             }
             // select loggedin users detail
             $res=mysqli_query($conn,"SELECT * FROM akun_admin WHERE idadmin=".$_SESSION['user']);
             $userRow=mysqli_fetch_array($res);

            if ( isset($_POST['btn-post']) ) {
                $error = false;
              // clean user inputs to prevent sql injections
              $jd = trim($_POST['jd']);
              $jd = strip_tags($jd);

              $sa = trim($_POST['sa']);
              $sa = strip_tags($sa);

              $note = trim($_POST['note']);
              $note = strip_tags($note);

              $genre = trim($_POST['genre']);
              $genre = strip_tags($genre);

              $ps = trim($_POST['ps']);
              $ps = strip_tags($ps);

              $ep14 = trim($_POST['1Link480p']);
              $ep17 = trim($_POST['1Link720p']);
              $ep1 = trim($ep14.'-'.$ep17);
              $ep1 = strip_tags($ep1);

              $ep24 = trim($_POST['2Link480p']);
              $ep27 = trim($_POST['2Link720p']);
              $ep2 = trim($ep24.'-'.$ep27);
              $ep2 = strip_tags($ep2);

              $ep34 = trim($_POST['3Link480p']);
              $ep37 = trim($_POST['3Link720p']);
              $ep3 = trim($ep34.'-'.$ep37);
              $ep3 = strip_tags($ep3);

              $ep44 = trim($_POST['4Link480p']);
              $ep47 = trim($_POST['4Link720p']);
              $ep4 = trim($ep44.'-'.$ep47);
              $ep4 = strip_tags($ep4);

              $ep54 = trim($_POST['5Link480p']);
              $ep57 = trim($_POST['5Link720p']);
              $ep5 = trim($ep54.'-'.$ep57);
              $ep5 = strip_tags($ep5);

              $ep64 = trim($_POST['6Link480p']);
              $ep67 = trim($_POST['6Link720p']);
              $ep6 = trim($ep64.'-'.$ep67);
              $ep6 = strip_tags($ep6);

              $ep74 = trim($_POST['7Link480p']);
              $ep77 = trim($_POST['7Link720p']);
              $ep7 = trim($ep74.'-'.$ep77);
              $ep7 = strip_tags($ep7);

              $ep84 = trim($_POST['8Link480p']);
              $ep87 = trim($_POST['8Link720p']);
              $ep8 = trim($ep84.'-'.$ep87);
              $ep8 = strip_tags($ep8);

              $ep94 = trim($_POST['9Link480p']);
              $ep97 = trim($_POST['9Link720p']);
              $ep9 = trim($ep94.'-'.$ep97);
              $ep9 = strip_tags($ep9);

              $ep104 = trim($_POST['10Link480p']);
              $ep107 = trim($_POST['10Link720p']);
              $ep10 = trim($ep104.'-'.$ep107);
              $ep10 = strip_tags($ep10);

              $ep114 = trim($_POST['11Link480p']);
              $ep117 = trim($_POST['11Link720p']);
              $ep11 = trim($ep114.'-'.$ep117);
              $ep11 = strip_tags($ep11);

              $ep124 = trim($_POST['12Link480p']);
              $ep127 = trim($_POST['12Link720p']);
              $ep12 = trim($ep124.'-'.$ep127);
              $ep12 = strip_tags($ep12);

              $ep134 = trim($_POST['13Link480p']);
              $ep137 = trim($_POST['13Link720p']);
              $ep13 = trim($ep134.'-'.$ep137);
              $ep13 = strip_tags($ep13);

              $ep144 = trim($_POST['14Link480p']);
              $ep147 = trim($_POST['14Link720p']);
              $ep14 = trim($ep144.'-'.$ep147);
              $ep14 = strip_tags($ep14);

              $ep154 = trim($_POST['15Link480p']);
              $ep157 = trim($_POST['15Link720p']);
              $ep15 = trim($ep154.'-'.$ep157);
              $ep15 = strip_tags($ep15);

              $ep164 = trim($_POST['16Link480p']);
              $ep167 = trim($_POST['16Link720p']);
              $ep16 = trim($ep164.'-'.$ep167);
              $ep16 = strip_tags($ep16);

              $ep174 = trim($_POST['17Link480p']);
              $ep177 = trim($_POST['17Link720p']);
              $ep17 = trim($ep174.'-'.$ep177);
              $ep17 = strip_tags($ep17);

              $ep184 = trim($_POST['18Link480p']);
              $ep187 = trim($_POST['18Link720p']);
              $ep18 = trim($ep184.'-'.$ep187);
              $ep18 = strip_tags($ep18);

              $ep194 = trim($_POST['19Link480p']);
              $ep197 = trim($_POST['19Link720p']);
              $ep19 = trim($ep194.'-'.$ep197);
              $ep19 = strip_tags($ep19);

              $ep204 = trim($_POST['20Link480p']);
              $ep207 = trim($_POST['20Link720p']);
              $ep20 = trim($ep204.'-'.$ep207);
              $ep20 = strip_tags($ep20);

              $ep214 = trim($_POST['21Link480p']);
              $ep217 = trim($_POST['21Link720p']);
              $ep21 = trim($ep214.'-'.$ep217);
              $ep21 = strip_tags($ep21);

              $ep224 = trim($_POST['22Link480p']);
              $ep227 = trim($_POST['22Link720p']);
              $ep22 = trim($ep224.'-'.$ep227);
              $ep22 = strip_tags($ep22);

              $ep234 = trim($_POST['23Link480p']);
              $ep237 = trim($_POST['23Link720p']);
              $ep23 = trim($ep234.'-'.$ep237);
              $ep23 = strip_tags($ep23);

              $ep244 = trim($_POST['24Link480p']);
              $ep247 = trim($_POST['24Link720p']);
              $ep24 = trim($ep244.'-'.$ep247);
              $ep24 = strip_tags($ep24);

              $tp = date("Y-m-d");
              $wp = date("h:i:sa");

              $ap = $userRow['alias'];

            function generateRandomString($length = 50) {
                $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                $charactersLength = strlen($characters);
                $randomString = '';
                for ($i = 0; $i < $length; $i++) {
                    $randomString .= $characters[rand(0, $charactersLength - 1)];
                }
                return $randomString;
            }
              $postID = generateRandomString();
              // if there's no error, continue to signup
              if(!empty($jd)) {
               $res = mysqli_query($conn,"INSERT INTO postperepisode1_12 (idpost, judulpost, tanggal, waktu, adminposting, genre, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1`, 18, 19, 20, 21, 22, 23, 24, note, sinopsis) VALUES ('$postID', '$jd', '$tp', '$wp', '$ap', '$genre', '$ep1', '$ep2', '$ep3', '$ep4', '$ep5', '$ep6', '$ep7', '$ep8', '$ep9', '$ep10', '$ep11', '$ep12', '$ep13', '$ep14', '$ep15', '$ep16', '$ep17', '$ep18', '$ep19', '$ep20', '$ep21', '$ep22', '$ep23', '$ep24', '$sa', '$note')");

               if ($res) {
                $errTyp = "success";
                $errMSG = "Posting Berhasil";
               } else {
                $errTyp = "danger";
                $errMSG = "Post Gagal";
               }

              }

             }
            ?>
</code>```

答:
yes，i see ,but it is your custom error, maybe you can print your sql and excute in

 mysql client. you can check the mysqli_error($conn) firstly

Title: php - why is my query not working?

Body:
I just created a .php file, unfortunately my sql query is not working on my web hosting but the .php file is working perfectly. so the problem is, my sql query is failing to be executed

It says:

Post Gagal or Post failed (in english)

can you tell why I have an sql error and how to fix this error

this my php code

                        date_default_timezone_set("Asia/Bangkok");
            ob_start();
             session_start();
            require 'connection.php';

             // if session is not set this will redirect to login page
             if( !isset($_SESSION['user']) ) {
              header("Location: loginpanel.php");
              exit;
             }
             // select loggedin users detail
             $res=mysqli_query($conn,"SELECT * FROM akun_admin WHERE idadmin=".$_SESSION['user']);
             $userRow=mysqli_fetch_array($res);

            if ( isset($_POST['btn-post']) ) {
                $error = false;
              // clean user inputs to prevent sql injections
              $jd = trim($_POST['jd']);
              $jd = strip_tags($jd);

              $sa = trim($_POST['sa']);
              $sa = strip_tags($sa);

              $note = trim($_POST['note']);
              $note = strip_tags($note);

              $genre = trim($_POST['genre']);
              $genre = strip_tags($genre);

              $ps = trim($_POST['ps']);
              $ps = strip_tags($ps);

              $ep14 = trim($_POST['1Link480p']);
              $ep17 = trim($_POST['1Link720p']);
              $ep1 = trim($ep14.'-'.$ep17);
              $ep1 = strip_tags($ep1);

              $ep24 = trim($_POST['2Link480p']);
              $ep27 = trim($_POST['2Link720p']);
              $ep2 = trim($ep24.'-'.$ep27);
              $ep2 = strip_tags($ep2);

              $ep34 = trim($_POST['3Link480p']);
              $ep37 = trim($_POST['3Link720p']);
              $ep3 = trim($ep34.'-'.$ep37);
              $ep3 = strip_tags($ep3);

              $ep44 = trim($_POST['4Link480p']);
              $ep47 = trim($_POST['4Link720p']);
              $ep4 = trim($ep44.'-'.$ep47);
              $ep4 = strip_tags($ep4);

              $ep54 = trim($_POST['5Link480p']);
              $ep57 = trim($_POST['5Link720p']);
              $ep5 = trim($ep54.'-'.$ep57);
              $ep5 = strip_tags($ep5);

              $ep64 = trim($_POST['6Link480p']);
              $ep67 = trim($_POST['6Link720p']);
              $ep6 = trim($ep64.'-'.$ep67);
              $ep6 = strip_tags($ep6);

              $ep74 = trim($_POST['7Link480p']);
              $ep77 = trim($_POST['7Link720p']);
              $ep7 = trim($ep74.'-'.$ep77);
              $ep7 = strip_tags($ep7);

              $ep84 = trim($_POST['8Link480p']);
              $ep87 = trim($_POST['8Link720p']);
              $ep8 = trim($ep84.'-'.$ep87);
              $ep8 = strip_tags($ep8);

              $ep94 = trim($_POST['9Link480p']);
              $ep97 = trim($_POST['9Link720p']);
              $ep9 = trim($ep94.'-'.$ep97);
              $ep9 = strip_tags($ep9);

              $ep104 = trim($_POST['10Link480p']);
              $ep107 = trim($_POST['10Link720p']);
              $ep10 = trim($ep104.'-'.$ep107);
              $ep10 = strip_tags($ep10);

              $ep114 = trim($_POST['11Link480p']);
              $ep117 = trim($_POST['11Link720p']);
              $ep11 = trim($ep114.'-'.$ep117);
              $ep11 = strip_tags($ep11);

              $ep124 = trim($_POST['12Link480p']);
              $ep127 = trim($_POST['12Link720p']);
              $ep12 = trim($ep124.'-'.$ep127);
              $ep12 = strip_tags($ep12);

              $ep134 = trim($_POST['13Link480p']);
              $ep137 = trim($_POST['13Link720p']);
              $ep13 = trim($ep134.'-'.$ep137);
              $ep13 = strip_tags($ep13);

              $ep144 = trim($_POST['14Link480p']);
              $ep147 = trim($_POST['14Link720p']);
              $ep14 = trim($ep144.'-'.$ep147);
              $ep14 = strip_tags($ep14);

              $ep154 = trim($_POST['15Link480p']);
              $ep157 = trim($_POST['15Link720p']);
              $ep15 = trim($ep154.'-'.$ep157);
              $ep15 = strip_tags($ep15);

              $ep164 = trim($_POST['16Link480p']);
              $ep167 = trim($_POST['16Link720p']);
              $ep16 = trim($ep164.'-'.$ep167);
              $ep16 = strip_tags($ep16);

              $ep174 = trim($_POST['17Link480p']);
              $ep177 = trim($_POST['17Link720p']);
              $ep17 = trim($ep174.'-'.$ep177);
              $ep17 = strip_tags($ep17);

              $ep184 = trim($_POST['18Link480p']);
              $ep187 = trim($_POST['18Link720p']);
              $ep18 = trim($ep184.'-'.$ep187);
              $ep18 = strip_tags($ep18);

              $ep194 = trim($_POST['19Link480p']);
              $ep197 = trim($_POST['19Link720p']);
              $ep19 = trim($ep194.'-'.$ep197);
              $ep19 = strip_tags($ep19);

              $ep204 = trim($_POST['20Link480p']);
              $ep207 = trim($_POST['20Link720p']);
              $ep20 = trim($ep204.'-'.$ep207);
              $ep20 = strip_tags($ep20);

              $ep214 = trim($_POST['21Link480p']);
              $ep217 = trim($_POST['21Link720p']);
              $ep21 = trim($ep214.'-'.$ep217);
              $ep21 = strip_tags($ep21);

              $ep224 = trim($_POST['22Link480p']);
              $ep227 = trim($_POST['22Link720p']);
              $ep22 = trim($ep224.'-'.$ep227);
              $ep22 = strip_tags($ep22);

              $ep234 = trim($_POST['23Link480p']);
              $ep237 = trim($_POST['23Link720p']);
              $ep23 = trim($ep234.'-'.$ep237);
              $ep23 = strip_tags($ep23);

              $ep244 = trim($_POST['24Link480p']);
              $ep247 = trim($_POST['24Link720p']);
              $ep24 = trim($ep244.'-'.$ep247);
              $ep24 = strip_tags($ep24);

              $tp = date("Y-m-d");
              $wp = date("h:i:sa");

              $ap = $userRow['alias'];

            function generateRandomString($length = 50) {
                $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                $charactersLength = strlen($characters);
                $randomString = '';
                for ($i = 0; $i < $length; $i++) {
                    $randomString .= $characters[rand(0, $charactersLength - 1)];
                }
                return $randomString;
            }
              $postID = generateRandomString();
              // if there's no error, continue to signup
              if(!empty($jd)) {
               $res = mysqli_query($conn,"INSERT INTO postperepisode1_12 (idpost, judulpost, tanggal, waktu, adminposting, genre, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1`, 18, 19, 20, 21, 22, 23, 24, note, sinopsis) VALUES ('$postID', '$jd', '$tp', '$wp', '$ap', '$genre', '$ep1', '$ep2', '$ep3', '$ep4', '$ep5', '$ep6', '$ep7', '$ep8', '$ep9', '$ep10', '$ep11', '$ep12', '$ep13', '$ep14', '$ep15', '$ep16', '$ep17', '$ep18', '$ep19', '$ep20', '$ep21', '$ep22', '$ep23', '$ep24', '$sa', '$note')");

               if ($res) {
                $errTyp = "success";
                $errMSG = "Posting Berhasil";
               } else {
                $errTyp = "danger";
                $errMSG = "Post Gagal";
               }

              }

             }
            ?>


问:
Unable to Inject Dependency ngMaterial
I am looking to develop an application that uses both dirPagination and AngularJS material. However, I am unable to inject the ngMaterial dependency into my application. The angularUtils.directives.dirPagination dependency works fine, but as soon as I add ngMaterial, the AngularJS application crashes.

Here is a Plunker with an example (https://plnkr.co/edit/7N7i9TnMc77Nz6xlNhuk?p=preview). In app.js, which is where I instantiate the module, both dependencies are there. If the line reads:

```<code>angular.module('myApp', ['angularUtils.directives.dirPagination', 'ngMaterial']);
</code>```

Then AngularJS crashes and the page reads {{hello}}. However, since in the controller, I have set $scope.hello to "Hello Plunker!", if the line reads:

```<code>angular.module('myApp', ['angularUtils.directives.dirPagination']);
</code>```

Then the page displays "Hello Plunker!".

What am I doing wrong?

Thanks for your help!

答:
You need to include angular.js before any other script that is going to use angular. Here you add script.js before angular.js

You also need to use the same versions of angular modules angular-animate, angular-aria, angular-messages as that of angular.js version
Here you used 1.6.4 version of angular.js

```<code>    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-animate.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-aria.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-messages.min.js"></script>
</code>```

You can check for the modifications I made to your plnkr https://plnkr.co/edit/En0YaiaiqD1MPPOydAf8?p=preview

Also there were errors for cross domain request for bootstrap.min.css which can be easily fixed by using

https://

cdn

Title: Unable to Inject Dependency ngMaterial

Body:
I am looking to develop an application that uses both dirPagination and AngularJS material. However, I am unable to inject the ngMaterial dependency into my application. The angularUtils.directives.dirPagination dependency works fine, but as soon as I add ngMaterial, the AngularJS application crashes.

Here is a Plunker with an example (https://plnkr.co/edit/7N7i9TnMc77Nz6xlNhuk?p=preview). In app.js, which is where I instantiate the module, both dependencies are there. If the line reads:

angular.module('myApp', ['angularUtils.directives.dirPagination', 'ngMaterial']);

Then AngularJS crashes and the page reads {{hello}}. However, since in the controller, I have set $scope.hello to "Hello Plunker!", if the line reads:

angular.module('myApp', ['angularUtils.directives.dirPagination']);

Then the page displays "Hello Plunker!".

What am I doing wrong?

Thanks for your help!

Body:
You need to include angular.js before any other script that is going to use angular. Here you add script.js before angular.js

You also need to use the same versions of angular modules angular-animate, angular-aria, angular-messages as that of angular.js version
Here you used 1.6.4 version of angular.js

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-animate.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-aria.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-messages.min.js"></script>

You can check for the modifications I made to your plnkr https://plnkr.co/edit/En0YaiaiqD1MPPOydAf8?p=preview

Also there were errors for cross domain request for bootstrap.min.css which can be easily fixed by using

https://

cdn


问:
Is there a way to push foralls past constructors when sound?
Suppose I have

```<code>data Foo p =
    NoFoo
  | YesFoo (forall a. p a)
</code>```

I can write

```<code>fromFoo :: Foo p -> Maybe (p a)
fromFoo NoFoo = Nothing
fromFoo (YesFoo p) = Just p
</code>```

It's also possible to go the other way:

```<code>toFoo :: forall p.
         (forall a. Maybe (p a))
      -> Foo p
toFoo m =
  case m :: Maybe (p ()) of
    Nothing -> NoFoo
    Just _ -> YesFoo (fromJust m)
</code>```

The fromJust is disgusting! toFoo is actually total, because parametricity ensures that m @a behaves exactly the same as m @(), but this is gross. Is there any cleaner way?

Edit: rampion pointed out that this can be written more concisely, still with fromJust. I just realized it can be done a bit humorously, making fun of the newbies:

```<code>toFoo m
  | isNothing m = NoFoo
  | otherwise = YesFoo (fromJust m)
</code>```

The only way I see to avoid creating a thunk to apply fromJust is by getting super-evil:

```<code>toFoo Nothing = NoFoo
toFoo (Just x) = YesFoo (unsafeCoerce# x)
</code>```

答:
The best I can come up with so far still uses fromJust, but it's simpler:

```<code>toFoo :: forall p.
         (forall a. Maybe (p a))
      -> Foo p
toFoo Nothing = NoFoo
toFoo m = YesFoo $ fromJust m
</code>```

Body:
Suppose I have

data Foo p =
    NoFoo
  | YesFoo (forall a. p a)

I can write

fromFoo :: Foo p -> Maybe (p a)
fromFoo NoFoo = Nothing
fromFoo (YesFoo p) = Just p

It's also possible to go the other way:

toFoo :: forall p.
         (forall a. Maybe (p a))
      -> Foo p
toFoo m =
  case m :: Maybe (p ()) of
    Nothing -> NoFoo
    Just _ -> YesFoo (fromJust m)

The fromJust is disgusting! toFoo is actually total, because parametricity ensures that m @a behaves exactly the same as m @(), but this is gross. Is there any cleaner way?

Edit: rampion pointed out that this can be written more concisely, still with fromJust. I just realized it can be done a bit humorously, making fun of the newbies:

toFoo m
  | isNothing m = NoFoo
  | otherwise = YesFoo (fromJust m)

The only way I see to avoid creating a thunk to apply fromJust is by getting super-evil:

toFoo Nothing = NoFoo
toFoo (Just x) = YesFoo (unsafeCoerce# x)

Body:
The best I can come up with so far still uses fromJust, but it's simpler:

toFoo :: forall p.
         (forall a. Maybe (p a))
      -> Foo p
toFoo Nothing = NoFoo
toFoo m = YesFoo $ fromJust m


问:
Database and connections
I am interested in knowing how databases handle connections that are not explicitly closed by the entity that initiated the connection.

Say I have a database that can accept only 2 concurrent connections at a time. I have a piece of code that opens a connection and never closes it. This piece of code runs forever, but it uses the connection only once in it's lifetime but the connection object never goes out of scope, so it is not garbage collected. Say I run 2 instances of this code. Does it mean that until the program is terminated or the connection times out (due to inactivity) the database can accept no more connections?

In the above scenario if the connection object is garbage collected, then is the connection terminated automatically or does it depend on the database driver that I am using or the connection is not terminated at all until I close it explicitly?

If I open a connection in piece of code and I do not close the connection explicitly, but the program terminates then how does the database reclaim that connection?

答:
To answer your questions in order:

Yes, probably. Unless by "concurrent connections" you actually mean "concurrent queries". If yo're holding the database connection open, it's open.

Garbage collection may or may not clean up the connection. Depends on the language and the database driver used. (Garbage collection may be limited to reclaiming memory, not resources like TCP connections.)

When your program terminates, generally the OS is responsible for cleaning up all resources it used. This includes closing TCP, etc. connections. So, for most connection types, the database will be notified that the other side closed the connection.

OwnerDisplayName: Abhi

Title: Database and connections

OwnerDisplayName: derobert