问:
C# equivalent of VB6's GetObject
The following VB6 code connects to some third party software and forces a login with the admin username and password:

```<code>Set obj = GetObject(, "workspace.application")
obj.System.FixLogin strAdminUsername, strAdminPassword
</code>```

I am wanting to do the same task in C# but as a very green C# developer (about 3 months experience) I have no idea how to do this.  I've spent a very frustrating day on Google but have found nothing that fits the bill (most of it I couldn't even understand) I know even less about VB6 than I do about C#, but VB6 makes it look so easy.

Also I can't test connecting to this third party software until I implement to our QA environment. So I would like to test the functionality with a simple app, Notepad for example.  What function / method could I call on Notepad instead of "FixLogin"?

I would be most grateful if someone could help me with this problem.

Kind Regards,
Steve.

答: Marshal.GetActiveObject Method</p>

Title: C# equivalent of VB6's GetObject

Body:
The following VB6 code connects to some third party software and forces a login with the admin username and password:

Set obj = GetObject(, "workspace.application")
obj.System.FixLogin strAdminUsername, strAdminPassword

I am wanting to do the same task in C# but as a very green C# developer (about 3 months experience) I have no idea how to do this.  I've spent a very frustrating day on Google but have found nothing that fits the bill (most of it I couldn't even understand) I know even less about VB6 than I do about C#, but VB6 makes it look so easy.

Also I can't test connecting to this third party software until I implement to our QA environment. So I would like to test the functionality with a simple app, Notepad for example.  What function / method could I call on Notepad instead of "FixLogin"?

I would be most grateful if someone could help me with this problem.

Kind Regards,
Steve.

Body: Marshal.GetActiveObject Method


来源: stackexchange

问:
Error while doing sudo apt-get upgrade in Ubuntu 16.04(LTS)
I have used this command to upgrade "sudo apt-get upgrade" and I have received this following error. I am new to Linux...
Any help would be appreciated..??

Here is the output from the terminal
$ sudo apt-get upgrade

```<code> Reading package lists... Done
 Building dependency tree
 Reading state information... Done
 Calculating upgrade... Done
 The following packages will be upgraded: apport
 1 to upgrade, 0 to newly install, 0 to remove and 0 not to upgrade.
 34 not fully installed or removed.
 Need to get 0 B/120 kB of archives.
 After this operation, 0 B of additional disk space will be used.
 Do you want to continue? [Y/n] y
 (Reading database ... 565317 files and directories currently
 installed.)
 Preparing to unpack .../apport_2.20.1-0ubuntu2.12_all.deb ...
 Traceback (most recent call last):
 File "/usr/bin/pyclean", line 24, in <module>
 import logging
 File "/usr/lib/python2.7/logging/__init__.py", line 26, in <module>
 import sys, os, time, cStringIO, traceback, warnings, weakref,
 collections
 File "/usr/lib/python2.7/collections.py", line 9, in <module>
 from operator import itemgetter as _itemgetter, eq as _eq
 ImportError: /usr/lib/python2.7/lib-dynload/operator.so: undefined s
 symbol: _PyUnicodeUCS4_AsDefaultEncodedString
 dpkg: warning: subprocess old pre-removal script returned error exit
 status 1
 dpkg: trying script from the new package instead ...
 Traceback (most recent call last):
 File "/usr/bin/pyclean", line 24, in <module>
 import logging
 File "/usr/lib/python2.7/logging/__init__.py", line 26, in <module>
 import sys, os, time, cStringIO, traceback, warnings, weakref,
 collections
 File "/usr/lib/python2.7/collections.py", line 9, in <module>
 from operator import itemgetter as _itemgetter, eq as _eq
 ImportError: /usr/lib/python2.7/lib-dynload/operator.so: undefined
 symbol: _PyUnicodeUCS4_AsDefaultEncodedString
 dpkg: error processing archive /var/cache/apt/archives/apport_2.20.1-
 0ubuntu2.12_all.deb (--unpack):
 subprocess new pre-removal script returned error exit status 1
 Traceback (most recent call last):
 File "/usr/bin/pycompile", line 26, in <module>
 import logging
 File "/usr/lib/python2.7/logging/__init__.py", line 26, in <module>
 import sys, os, time, cStringIO, traceback, warnings, weakref,
 collections
 File "/usr/lib/python2.7/collections.py", line 9, in <module>
 from operator import itemgetter as _itemgetter, eq as _eq
 ImportError: /usr/lib/python2.7/lib-dynload/operator.so: undefined
 symbol: _PyUnicodeUCS4_AsDefaultEncodedString
 dpkg: error while cleaning up:
 subprocess installed post-installation script returned error exit
 status 1
 Errors were encountered while processing:
 /var/cache/apt/archives/apport_2.20.1-0ubuntu2.12_all.deb
 E: Sub-process /usr/bin/dpkg returned an error code (1)
</code>```

How can I rectify this problem..??
Following error also received while executing "sudo apt-get update" before "sudo apt-get upgrade"

```<code>   W: The repository 'http://ppa.launchpad.net/fkrull/deadsnakes -
   python2.7/ubuntu xenial Release' does not have a Release file.
   N: Data from such a repository can't be authenticated and is
   therefore potentially dangerous to use.
   N: See apt-secure(8) manpage for repository creation and user
   configuration details.
   E: Failed to fetch http://ppa.launchpad.net/fkrull/deadsnakes  -
   python2.7/ubuntu/dists/xenial/main/binary-amd64/Packages  404  Not
   Found
   E: Some index files failed to download. They have been ignored, or
   old ones used instead.
</code>```

答:
Did you try 'update' begore 'upgrade'?

If not, try sudo apt-get update then sudo apt-get upgrade

This will update the list of available packages before upgrading it.

ContentLicense: CC BY-SA 3.0

Body:
I have used this command to upgrade "sudo apt-get upgrade" and I have received this following error. I am new to Linux...
Any help would be appreciated..??

Here is the output from the terminal
$ sudo apt-get upgrade

 Reading package lists... Done
 Building dependency tree
 Reading state information... Done
 Calculating upgrade... Done
 The following packages will be upgraded: apport
 1 to upgrade, 0 to newly install, 0 to remove and 0 not to upgrade.
 34 not fully installed or removed.
 Need to get 0 B/120 kB of archives.
 After this operation, 0 B of additional disk space will be used.
 Do you want to continue? [Y/n] y
 (Reading database ... 565317 files and directories currently
 installed.)
 Preparing to unpack .../apport_2.20.1-0ubuntu2.12_all.deb ...
 Traceback (most recent call last):
 File "/usr/bin/pyclean", line 24, in <module>
 import logging
 File "/usr/lib/python2.7/logging/__init__.py", line 26, in <module>
 import sys, os, time, cStringIO, traceback, warnings, weakref,
 collections
 File "/usr/lib/python2.7/collections.py", line 9, in <module>
 from operator import itemgetter as _itemgetter, eq as _eq
 ImportError: /usr/lib/python2.7/lib-dynload/operator.so: undefined s
 symbol: _PyUnicodeUCS4_AsDefaultEncodedString
 dpkg: warning: subprocess old pre-removal script returned error exit
 status 1
 dpkg: trying script from the new package instead ...
 Traceback (most recent call last):
 File "/usr/bin/pyclean", line 24, in <module>
 import logging
 File "/usr/lib/python2.7/logging/__init__.py", line 26, in <module>
 import sys, os, time, cStringIO, traceback, warnings, weakref,
 collections
 File "/usr/lib/python2.7/collections.py", line 9, in <module>
 from operator import itemgetter as _itemgetter, eq as _eq
 ImportError: /usr/lib/python2.7/lib-dynload/operator.so: undefined
 symbol: _PyUnicodeUCS4_AsDefaultEncodedString
 dpkg: error processing archive /var/cache/apt/archives/apport_2.20.1-
 0ubuntu2.12_all.deb (--unpack):
 subprocess new pre-removal script returned error exit status 1
 Traceback (most recent call last):
 File "/usr/bin/pycompile", line 26, in <module>
 import logging
 File "/usr/lib/python2.7/logging/__init__.py", line 26, in <module>
 import sys, os, time, cStringIO, traceback, warnings, weakref,
 collections
 File "/usr/lib/python2.7/collections.py", line 9, in <module>
 from operator import itemgetter as _itemgetter, eq as _eq
 ImportError: /usr/lib/python2.7/lib-dynload/operator.so: undefined
 symbol: _PyUnicodeUCS4_AsDefaultEncodedString
 dpkg: error while cleaning up:
 subprocess installed post-installation script returned error exit
 status 1
 Errors were encountered while processing:
 /var/cache/apt/archives/apport_2.20.1-0ubuntu2.12_all.deb
 E: Sub-process /usr/bin/dpkg returned an error code (1)

How can I rectify this problem..??
Following error also received while executing "sudo apt-get update" before "sudo apt-get upgrade"

   W: The repository 'http://ppa.launchpad.net/fkrull/deadsnakes -
   python2.7/ubuntu xenial Release' does not have a Release file.
   N: Data from such a repository can't be authenticated and is
   therefore potentially dangerous to use.
   N: See apt-secure(8) manpage for repository creation and user
   configuration details.
   E: Failed to fetch http://ppa.launchpad.net/fkrull/deadsnakes  -
   python2.7/ubuntu/dists/xenial/main/binary-amd64/Packages  404  Not
   Found
   E: Some index files failed to download. They have been ignored, or
   old ones used instead.


问:
Android Studio Keyboard Shortcut for full screen mode
I want to enter full screen mode in Android Studio. Is there any Keyboard Shortcut for doing it. What Is the Keyboard Shortcut key for enter and exit full screen mode in Android Studio?

答: It's easy. Press ctrl+alt+s or open File > Settings > Keymap and open Keymaps select box the default one. Below the select box, type full screen in the search box and right click on the result to set your shortcut. That's it.


问:
Detect death of parent process from `setuid` process
I write C application that calls fork() to create child processes. The application runs as root. In the parent process, I use wait() for waiting terminated child processes. In child processes, I use prctl() with PR_SET_PDEATHSIG option to detect the death of the parent. It works fine. To reduce the risk of security issues, child processes call setuid() to change UID. The problem is: child processes can not detect the death of the parent one any more.

I have searched around to find the answer and found some useful links, but it does not help:

Detect death of parent process

Enforcing process hierarchies (prctl related) : although this link contains a clear answer, there is no solution.

How to do that correctly?

答:
I just stumbled upon the same issue, the kernel resets the PDEATH signal on credential change:

https://github.com/torvalds/linux/blob/master/kernel/cred.c#L450

This can be verified with the following code and strace -f:

```<code>#include <sys/prctl.h>
#include <unistd.h>
#include <signal.h>

int main(int argc, char *argv[])
{
        if (fork() == 0) {
                // This works as expected
                setgid(1000);
                setuid(1000);

                prctl(PR_SET_PDEATHSIG, SIGTERM);

                // This doesn't work since pdeath_signal will be reset
                // setgid(1000);
                // setuid(1000);

                pause();
        }
        sleep(1);
        kill(getpid(), SIGTERM);
        return (0);
}
</code>```

Body:
I just stumbled upon the same issue, the kernel resets the PDEATH signal on credential change:

https://github.com/torvalds/linux/blob/master/kernel/cred.c#L450

This can be verified with the following code and strace -f:

#include <sys/prctl.h>
#include <unistd.h>
#include <signal.h>

int main(int argc, char *argv[])
{
        if (fork() == 0) {
                // This works as expected
                setgid(1000);
                setuid(1000);

                prctl(PR_SET_PDEATHSIG, SIGTERM);

                // This doesn't work since pdeath_signal will be reset
                // setgid(1000);
                // setuid(1000);

                pause();
        }
        sleep(1);
        kill(getpid(), SIGTERM);
        return (0);
}


问:
java imagej dialog don't show
Hello that is very curious but in a macro when I type:

```<code>run("my plugin");
</code>```

it's working the dialog is showing but and that is my problem when I type

```<code>run("my plugin", "5");
</code>```

For example, my dialog don't appear anymore and I find pretty curious and that's a problem because I wanted to pass argument to my plugin and get it via Macro.getoptions() in my plugin code.

Any suggestion?

答:
It seems like, you are mixing two methods run(String arg) method from ij.plugin.Plugin and the ImageJ macro command run("command"\[, "options"\]), from IJ.run(String command, String options).

If you read carefully the documentation of ij.plugin.Plugin#run(String arg), it states:

This method is called when the plugin is loaded. 'arg', which may be blank, is the argument specified for this plugin in IJ_Props.txt.

In this case, arg is an optional argument that you can use in IJ_Props.txt or in the plugins.config file of your plugin to assign different menu commands to different functions of your plug-in (see also the excellent documentation on the Fiji wiki).

To make use of the options parameter when running your plugin from macro code, you should use a GenericDialog to get the options, or (as you apparently learned the hard way) use the helper function Macro.getOptions().

Title: java imagej dialog don't show

Body:
Hello that is very curious but in a macro when I type:

run("my plugin");

it's working the dialog is showing but and that is my problem when I type

run("my plugin", "5");

For example, my dialog don't appear anymore and I find pretty curious and that's a problem because I wanted to pass argument to my plugin and get it via Macro.getoptions() in my plugin code.

Any suggestion?


问:
ReactJS - Lifting state up vs keeping a local state
At my company we're migrating the front-end of a web application to ReactJS.
We are working with create-react-app (updated to v16), without Redux.
Now I'm stuck on a page which structure can be simplified by the following image:

The data displayed by the three components (SearchableList, SelectableList and Map) is retrieved with the same backend request in the componentDidMount() method of MainContainer. The result of this request is then stored in the state of MainContainer and has a structure more or less like this:

```<code>state.allData = {
  left: {
    data: [ ... ]
  },
  right: {
    data: [ ... ],
    pins: [ ... ]
  }
}
</code>```

LeftContainer receives as prop state.allData.left from MainContainer and passes props.left.data to SearchableList, once again as prop.

RightContainer receives as prop state.allData.right from MainContainer and passes props.right.data to SelectableList and props.right.pins to Map.

SelectableList displays a checkbox to allow actions on its items. Whenever an action occur on an item of SelectableList component it may have side effects on Map pins.

I've decided to store in the state of RightContainer a list that keeps all the ids of items displayed by SelectableList; this list is passed as props to both SelectableList and Map. Then I pass to SelectableList a callback, that whenever a selection is made updates the list of ids inside RightContainer; new props arrive in both SelectableList and Map, and so render() is called in both components.

It works fine and helps to keep everything that may happen to SelectableList and Map inside RightContainer, but I'm asking if this is correct for the lifting-state-up and single-source-of-truth concepts.

As feasible alternative I thought of adding a _selected property to each item in state.right.data in MainContainer and pass the select callback three levels down to SelectableList, handling all the possible actions in MainContainer. But as soon as a selection event occurs this will eventually force the loading of LeftContainer and RightContainer, introducing the need of implementing logics like shouldComponentUpdate() to avoid useless render() especially in LeftContainer.

Which is / could be the best solution to optimise this page from an architectural and performance point of view?

Below you have an extract of my components to help you understand the situation.

MainContainer.js

```<code>class MainContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      allData: {}
    };
  }

  componentDidMount() {
    fetch( ... )
      .then((res) => {
        this.setState({
          allData: res
        });
      });
  }

  render() {
    return (
      <div className="main-container">
        <LeftContainer left={state.allData.left} />
        <RightContainer right={state.allData.right} />
      </div>
    );
  }
}

export default MainContainer;
</code>```

RightContainer.js

```<code>class RightContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedItems: [ ... ]
    };
  }

  onDataSelection(e) {
    const itemId = e.target.id;
    // ... handle itemId and selectedItems ...
  }

  render() {
    return (
      <div className="main-container">
        <SelectableList
          data={props.right.data}
          onDataSelection={e => this.onDataSelection(e)}
          selectedItems={this.state.selectedItems}
        />
        <Map
          pins={props.right.pins}
          selectedItems={this.state.selectedItems}
        />
      </div>
    );
  }
}

export default RightContainer;
</code>```

Thanks in advance!

答:
As React docs state

Often, several components need to reflect the same changing data. We
  recommend lifting the shared state up to their closest common
  ancestor.

There should be a single “source of truth” for any data that changes
  in a React application. Usually, the state is first added to the
  component that needs it for rendering. Then, if other components also
  need it, you can lift it up to their closest common ancestor. Instead
  of trying to sync the state between different components, you should
  rely on the top-down data flow.

Lifting state involves writing more “boilerplate” code than two-way
  binding approaches, but as a benefit, it takes less work to find and
  isolate bugs. Since any state “lives” in some component and that
  component alone can change it, the surface area for bugs is greatly
  reduced. Additionally, you can implement any custom logic to reject or
  transform user input.

So essentially you need to lift those state up the tree that are being used up the Siblings component as well. So you first implementation where you store the selectedItems as a state in the RightContainer is completely justified and a good approach, since the parent doesn't need to know about and this data is being shared by the two child components of RightContainer and those two now have a single source of truth.

As per your question:

As feasible alternative I thought of adding a _selected property to
  each item in state.right.data in MainContainer and pass the select
  callback three levels down to SelectableList, handling all the
  possible actions in MainContainer

I wouldn't agree that this is a better approach than the first one, since you MainContainer doesn't need to know the selectedItems or handler any of the updates. MainContainer isn't doing anything about those states and is just passing it down.

Consider to optimise on performance, you yourself talk about implementing a shouldComponentUpdate, but you can avoid that by creating your components by extending React.PureComponent which essentially implements the shouldComponentUpdate with a shallow comparison of state and props.

According to the docs:

If your React component’s render() function renders the same result
  given the same props and state, you can use React.PureComponent for a
  performance boost in some cases.

However if multiple deeply nested components are making use of the same data, it makes sense to make use of redux and store that data in the redux-state. In this way it is globally accessible to the entire App and can be shared between components that are not directly related.

For example consider the following case

```<code>const App = () => {
    <Router>
         <Route path="/" component={Home}/>
         <Route path="/mypage" component={MyComp}/>
    </Router>
}
</code>```

Now here if both Home and MyComp want to access the same data. You could pass the data as props from App by calling them through render prop. However it would easily be done by connecting both of these components to Redux state using a connect function like

```<code>const mapStateToProps = (state) => {
   return {
      data: state.data
   }
}

export connect(mapStateToProps)(Home);
</code>```

and similarly for MyComp. Also its easy to configure actions for updating relevant informations

Also its particularly easy to configure Redux for your application and you would be able to store data related to the same things in the individual reducers. In this way you would be able to modularise your application data as well

Body:
At my company we're migrating the front-end of a web application to ReactJS.
We are working with create-react-app (updated to v16), without Redux.
Now I'm stuck on a page which structure can be simplified by the following image:

The data displayed by the three components (SearchableList, SelectableList and Map) is retrieved with the same backend request in the componentDidMount() method of MainContainer. The result of this request is then stored in the state of MainContainer and has a structure more or less like this:

state.allData = {
  left: {
    data: [ ... ]
  },
  right: {
    data: [ ... ],
    pins: [ ... ]
  }
}

LeftContainer receives as prop state.allData.left from MainContainer and passes props.left.data to SearchableList, once again as prop.

RightContainer receives as prop state.allData.right from MainContainer and passes props.right.data to SelectableList and props.right.pins to Map.

SelectableList displays a checkbox to allow actions on its items. Whenever an action occur on an item of SelectableList component it may have side effects on Map pins.

I've decided to store in the state of RightContainer a list that keeps all the ids of items displayed by SelectableList; this list is passed as props to both SelectableList and Map. Then I pass to SelectableList a callback, that whenever a selection is made updates the list of ids inside RightContainer; new props arrive in both SelectableList and Map, and so render() is called in both components.

It works fine and helps to keep everything that may happen to SelectableList and Map inside RightContainer, but I'm asking if this is correct for the lifting-state-up and single-source-of-truth concepts.

As feasible alternative I thought of adding a _selected property to each item in state.right.data in MainContainer and pass the select callback three levels down to SelectableList, handling all the possible actions in MainContainer. But as soon as a selection event occurs this will eventually force the loading of LeftContainer and RightContainer, introducing the need of implementing logics like shouldComponentUpdate() to avoid useless render() especially in LeftContainer.

Which is / could be the best solution to optimise this page from an architectural and performance point of view?

Below you have an extract of my components to help you understand the situation.

MainContainer.js

class MainContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      allData: {}
    };
  }

  componentDidMount() {
    fetch( ... )
      .then((res) => {
        this.setState({
          allData: res
        });
      });
  }

  render() {
    return (

        <LeftContainer left={state.allData.left} />
        <RightContainer right={state.allData.right} />

    );
  }
}

export default MainContainer;

RightContainer.js

class RightContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedItems: [ ... ]
    };
  }

  onDataSelection(e) {
    const itemId = e.target.id;
    // ... handle itemId and selectedItems ...
  }

  render() {
    return (

        <SelectableList
          data={props.right.data}
          onDataSelection={e => this.onDataSelection(e)}
          selectedItems={this.state.selectedItems}
        />
        <Map
          pins={props.right.pins}
          selectedItems={this.state.selectedItems}
        />

    );
  }
}

export default RightContainer;

Thanks in advance!

Body:
As React docs state

Often, several components need to reflect the same changing data. We
  recommend lifting the shared state up to their closest common
  ancestor.

There should be a single “source of truth” for any data that changes
  in a React application. Usually, the state is first added to the
  component that needs it for rendering. Then, if other components also
  need it, you can lift it up to their closest common ancestor. Instead
  of trying to sync the state between different components, you should
  rely on the top-down data flow.

Lifting state involves writing more “boilerplate” code than two-way
  binding approaches, but as a benefit, it takes less work to find and
  isolate bugs. Since any state “lives” in some component and that
  component alone can change it, the surface area for bugs is greatly
  reduced. Additionally, you can implement any custom logic to reject or
  transform user input.

So essentially you need to lift those state up the tree that are being used up the Siblings component as well. So you first implementation where you store the selectedItems as a state in the RightContainer is completely justified and a good approach, since the parent doesn't need to know about and this data is being shared by the two child components of RightContainer and those two now have a single source of truth.

As per your question:

As feasible alternative I thought of adding a _selected property to
  each item in state.right.data in MainContainer and pass the select
  callback three levels down to SelectableList, handling all the
  possible actions in MainContainer

I wouldn't agree that this is a better approach than the first one, since you MainContainer doesn't need to know the selectedItems or handler any of the updates. MainContainer isn't doing anything about those states and is just passing it down.

Consider to optimise on performance, you yourself talk about implementing a shouldComponentUpdate, but you can avoid that by creating your components by extending React.PureComponent which essentially implements the shouldComponentUpdate with a shallow comparison of state and props.

According to the docs:

If your React component’s render() function renders the same result
  given the same props and state, you can use React.PureComponent for a
  performance boost in some cases.

However if multiple deeply nested components are making use of the same data, it makes sense to make use of redux and store that data in the redux-state. In this way it is globally accessible to the entire App and can be shared between components that are not directly related.

For example consider the following case

const App = () => {
    <Router>
         <Route path="/" component={Home}/>
         <Route path="/mypage" component={MyComp}/>
    </Router>
}

Now here if both Home and MyComp want to access the same data. You could pass the data as props from App by calling them through render prop. However it would easily be done by connecting both of these components to Redux state using a connect function like

const mapStateToProps = (state) => {
   return {
      data: state.data
   }
}

export connect(mapStateToProps)(Home);

and similarly for MyComp. Also its easy to configure actions for updating relevant informations

Also its particularly easy to configure Redux for your application and you would be able to store data related to the same things in the individual reducers. In this way you would be able to modularise your application data as well


问:
Pyqt5 QtableWidget and integrated combobox fails to call a function when combobox items change
I have the below code :

```<code>import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

class tabdemo(QMainWindow):
    def __init__(self):
        super(tabdemo, self).__init__()
        self.setGeometry(50,50,500,500)
        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)
        self.table()
        self.mainHBOX_param_scene = QHBoxLayout()
        self.mainHBOX_param_scene.addWidget(self.tableWidget)
        self.centralWidget.setLayout(self.mainHBOX_param_scene)

    def table(self):

        self.tableWidget = QTableWidget()
        self.tableWidget.setColumnCount(2)
        self.tableWidget.setRowCount(5)

        attr = ['one', 'two', 'three', 'four', 'five']
        i = 0
        for j in attr:
            self.tableWidget.setItem(i, 0, QTableWidgetItem(j))
            combobox = QComboBox()
            for txt in ["Sinus","Triangle","Square"]:
                combobox.addItem(txt)
            self.tableWidget.setCellWidget(i, 1, combobox)
            i += 1

        self.tableWidget.itemChanged.connect(self.Table_itemchanged)

    def Table_itemchanged(self):
        print('Changed')

def main():
   app = QApplication(sys.argv)
   ex = tabdemo()
   ex.show()
   sys.exit(app.exec_())

if __name__ == '__main__':
   main()
</code>```

It just puts a Qtablewidget with one column being labels and another column being comboboxes.
What I'm trying to do is when I modify the value of whatever combobox, I want call a function which, in this case, print 'changed' in the console.
the signal connection self.tableWidget.itemChanged.connect(self.Table_itemchanged) works fine when I edit the label part of the QtableWidget but it fails when I modify the combobox item.

Does anyone could explain me why and if it exists a solution to my issue.
Thank you all.

答:
Use the currentIndexChanged signal of the combobox.

You can set a property on the combobox to store and recover which row (and column if you want) it belongs to.

```<code>    for j in attr:
        self.tableWidget.setItem(i, 0, QTableWidgetItem(j))
        combobox = QComboBox()
        for txt in ["Sinus","Triangle","Square"]:
            combobox.addItem(txt)
        combobox.setProperty('row', i)
        combobox.currentIndexChanged.connect(self.Combo_indexchanged)
        self.tableWidget.setCellWidget(i, 1, combobox)
        i += 1
</code>```

and add a new slot:

```<code>def Combo_indexchanged(self):
    combo = self.sender()
    row = combo.property('row')
    index = combo.currentIndex()
    print('combo row %d indexChanged to %d' % (row, index))
</code>```

Body:
I have the below code :

import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

class tabdemo(QMainWindow):
    def __init__(self):
        super(tabdemo, self).__init__()
        self.setGeometry(50,50,500,500)
        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)
        self.table()
        self.mainHBOX_param_scene = QHBoxLayout()
        self.mainHBOX_param_scene.addWidget(self.tableWidget)
        self.centralWidget.setLayout(self.mainHBOX_param_scene)

    def table(self):

        self.tableWidget = QTableWidget()
        self.tableWidget.setColumnCount(2)
        self.tableWidget.setRowCount(5)

        attr = ['one', 'two', 'three', 'four', 'five']
        i = 0
        for j in attr:
            self.tableWidget.setItem(i, 0, QTableWidgetItem(j))
            combobox = QComboBox()
            for txt in ["Sinus","Triangle","Square"]:
                combobox.addItem(txt)
            self.tableWidget.setCellWidget(i, 1, combobox)
            i += 1

        self.tableWidget.itemChanged.connect(self.Table_itemchanged)

    def Table_itemchanged(self):
        print('Changed')

def main():
   app = QApplication(sys.argv)
   ex = tabdemo()
   ex.show()
   sys.exit(app.exec_())

if __name__ == '__main__':
   main()

It just puts a Qtablewidget with one column being labels and another column being comboboxes.
What I'm trying to do is when I modify the value of whatever combobox, I want call a function which, in this case, print 'changed' in the console.
the signal connection self.tableWidget.itemChanged.connect(self.Table_itemchanged) works fine when I edit the label part of the QtableWidget but it fails when I modify the combobox item.

Does anyone could explain me why and if it exists a solution to my issue.
Thank you all.

Body:
Use the currentIndexChanged signal of the combobox.

You can set a property on the combobox to store and recover which row (and column if you want) it belongs to.

    for j in attr:
        self.tableWidget.setItem(i, 0, QTableWidgetItem(j))
        combobox = QComboBox()
        for txt in ["Sinus","Triangle","Square"]:
            combobox.addItem(txt)
        combobox.setProperty('row', i)
        combobox.currentIndexChanged.connect(self.Combo_indexchanged)
        self.tableWidget.setCellWidget(i, 1, combobox)
        i += 1

and add a new slot:

def Combo_indexchanged(self):
    combo = self.sender()
    row = combo.property('row')
    index = combo.currentIndex()
    print('combo row %d indexChanged to %d' % (row, index))


问:
MYSQL Add to existing value using two columns
I would like to add a value to every row in a table. Using a fixed value would give me the following query

```<code>UPDATE your_table SET displayorder = displayorder + C
</code>```

What would be the right way to run a similar query such that

```<code> UPDATE your_table SET displayorder = displayorder + X(C)
</code>```

Whereby C is a constant and X is the value of another column of the same row ? How do I get X which is the value of another column and how do I multiply it by C then add to an existing value ?

答:
You would just multiply them together:

```<code>UPDATE your_table
    SET displayorder = displayorder + X * C;
</code>```

In most programming languages, * is used for multiplication.  Parentheses are just used to group expressions.

Body:
I would like to add a value to every row in a table. Using a fixed value would give me the following query

UPDATE your_table SET displayorder = displayorder + C

What would be the right way to run a similar query such that

 UPDATE your_table SET displayorder = displayorder + X(C)

Whereby C is a constant and X is the value of another column of the same row ? How do I get X which is the value of another column and how do I multiply it by C then add to an existing value ?

Body:
You would just multiply them together:

UPDATE your_table
    SET displayorder = displayorder + X * C;

In most programming languages, * is used for multiplication.  Parentheses are just used to group expressions.


问:
HTTP Status 404-Not Found
Yo, im building my first Spring Web App.
When i try to run it (On server) this is the response

TTP Status 404 – Not Found

Type Status Report

Message /HelloWorld/

Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

hierarchy

web.xml

dispatcher-servlet.xml

helloworld.jsp

Controller

答:
the page you're requesting from browser is not found, so you need to add url in below pattern:
 localhost:(Port number) /project name/(request mapping at controller) /(request mapping at method)</p>

Title: HTTP Status 404-Not Found


问:
Quote needed: Preprocessor usage is bad OO practice
I believe, that the usage of preprocessor directives like #if UsingNetwork is bad OO practice - other coworkers do not.
I think, when using an IoC container (e.g. Spring), components can be easily configured if programmed accordingly. In this context either a propery IsUsingNetwork can be set by the IoC container or, if the "using network" implementation behaves differently, another implementation of that interface should be implemented and injected (e.g.: IService, ServiceImplementation, NetworkingServiceImplementation).

Can somebody please provide citations of OO-Gurus or references in books which basically reads "Preprocessor usage is bad OO practice if you try to configure behaviour which should be configured via an IoC container"?

I need this citations to convince coworkers to refactor...

Edit: I do know and agree that using preprocessor directives to change targetplatform specific code during compilation is fine and that is what preprocessor directives are made for. However, I think that runtime-configuration should be used rather than compiletime-configuration to get good designed and testable classes and components. In other words: Using #defines and #if's beyond what they are meant for will lead to difficult to test code and badly designed classes.

Has anybody read something along these lines and can give me so I can refer to?

答:
The support of preprocessing in C# is highly minimal.... verging on useless. Is that Evil?

Is the Preprocessor anything to do with OO? Surely it's for build configuration.

For instance I have a lite version and a pro-version of my app. I might want to exclude some code on the lite withour having to resort to building very similar versions of the code.

I might not want to ship a lite version which is the pro version with different runtime flags.

Tony

OwnerDisplayName: tobsen

LastEditorDisplayName: tobsen

OwnerDisplayName: Lambert

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Lambert


问:
Oracle setup required for heavy-ish load
I am trying to make a comparison between a system setup using Hadoop and HBase and achieving the same using Oracle DB as back end. I lack knowledge on the Oracle side of things so come to a fair comparison.

The work load and non-functional requirements are roughly this:

A) 12M transactions on two tables with one simple relation and multiple (non-text) indexes within 4 hours. That amounts to 833 transactions per second (TPS), sustained. This needs to be done every 8 hours.

B) Make sure that all writes are durable (so a running transaction survives a machine failure in case of a clustered setup) and have a decent level of availability? With a decent level of availability, I mean that regular failures such as disk and a single network interface / tcp connection drop should not require human intervention. Rare failures, may require intervention, but should be solved by just firing up a cold standby that can take over quickly.

C) Additionally add another 300 TPS, but have these happen almost continuously 24/7 across many tables (but all in pairs of two with the same simple relation and multiple indexes)?

Some context: this workload is 24/7 and the system needs to hold 10 years worth of historical data available for live querying. Query performance can be a bit worse than sub-second, but must be lively enough to consider for day-to-day usage. The ETL jobs are setup in such a way that there is little churn. Also in a relational setup, this workload would lead to little lock contention. I would expect index updates to be the major pain. To make a comparison as fair as possible, I would expect the loosest consistency level that Oracle provides.

I have no intention of bashing Oracle. I think it is a great database for many uses. I am trying to get a feeling for the tradeoff there is between going open source (and NoSQL) like we do and using a commercially supported, proven setup.

答:
Nobody can answer this definitively.

When you go buy a car you can sensibly expect that its top speed, acceleration and fuel consumption will be within a few percent of values from independent testing. The same does not apply to software in general nor to databases in particular.

Even if you had provided exact details of the hardware, OS and data structures, along with full details of the amount of data stored as well as transactions, the performance could easily vary by a factor of 100 times depending on the pattern of usage (due to development of hot spots of record caching, disk fragmentation).

However, having said that there are a few pointers I can give:

1) invariably a nosql database will outperform a conventional DBMS - the reason d'etre for nosql databases is performance and parallelization. That does not mean that conventional DBMS's are redundant - they provide much greater flexibility for interacting with data

2) for small to mid range data volumes, Oracle is relatively slow in my experience compared with other relational databases. I'm not overly impressed with Oracle RAC as a scalable solution either.

3) I suspect that the workload would require a mid-range server for consistent results (something in the region of $8k+) running Oracle

4) While having a hot standby is a quick way to cover all sorts of outages, in a lot of cases, the risk/cost/benefit favours approaches such as RAID, multiple network cards, UPS rather than the problems of maintaining a synchronized cluster.

5) Support - have you ever bothered to ask the developers of an open source software package if they'll provide paid for support? IME, the SLAs / EULAs for commercial software are more about protecting the vendor than the customer.

So if you think its worthwhile considering, and cost is not a big issue, then the best answer would be to try it out for yourself.


问:
How to set a radio button in Android
I have an app that uses radio buttons. The default for this button is set in the main.xml file, ie:

```<code>android:id="@+id/rb_sat1E"
android:checked="true"
</code>```

In the Java file I have:

```<code>final RadioButton radio1 = (RadioButton)findViewById(R.id.rb_sat1E);
</code>```

I have also created a 'Reset' button in the main Java file and can use the following code to reset TextView information ie.

```<code>pos1_deg.setText("0.0");
</code>```

But how do I reset a radio button? I would have thought it to be something like

```<code>radio1.setBoolean("TRUE");
</code>```

But that does not work at all.

Any help greatly appreciated. Thanks.

答:
I have multiple RadioButtons without Group and setChecked(true) works, but setChecked(false) don't works. But this code works:

```<code>RadioButton switcher = (RadioButton) view.findViewById(R.id.active);
                        switcher.setOnClickListener(new RadioButton.OnClickListener(){
                            @Override
                            public void onClick(View v) {
                                if(((RadioButton)v).isSelected()){
                                    ((RadioButton)v).setChecked(false);
                                    ((RadioButton)v).setSelected(false);
                                } else {
                                    ((RadioButton)v).setChecked(true);
                                    ((RadioButton)v).setSelected(true);
                                }
                            }

                        });
</code>```

Title: How to set a radio button in Android

Body:
I have an app that uses radio buttons. The default for this button is set in the main.xml file, ie:

android:id="@+id/rb_sat1E"
android:checked="true"

In the Java file I have:

final RadioButton radio1 = (RadioButton)findViewById(R.id.rb_sat1E);

I have also created a 'Reset' button in the main Java file and can use the following code to reset TextView information ie.

pos1_deg.setText("0.0");

But how do I reset a radio button? I would have thought it to be something like

radio1.setBoolean("TRUE");

But that does not work at all.

Any help greatly appreciated. Thanks.

Body:
I have multiple RadioButtons without Group and setChecked(true) works, but setChecked(false) don't works. But this code works:

RadioButton switcher = (RadioButton) view.findViewById(R.id.active);
                        switcher.setOnClickListener(new RadioButton.OnClickListener(){
                            @Override
                            public void onClick(View v) {
                                if(((RadioButton)v).isSelected()){
                                    ((RadioButton)v).setChecked(false);
                                    ((RadioButton)v).setSelected(false);
                                } else {
                                    ((RadioButton)v).setChecked(true);
                                    ((RadioButton)v).setSelected(true);
                                }
                            }

                        });


问:
How to validate array of inputs using validate plugin jquery
Am new to jquery validation plugin but i would like to know how do we validate array of input boxes using validation plugin..

Below is html code.

```<code><form id="transport-form">
  <input type="text" name="qty[]" id="qty1">
  <input type="text" name="qty[]" id="qty2" >
  <input type="text" name="qty[]" id="qty3">
  <input type="text" name="qty[]" id="qty4">
  <input type="submit value="submit">
</form>
</code>```

and jquery code is below

```<code>jQuery("#transport-form").validate({
        rules: {
            'qty[]': {
                required: true
            }
        },
    });
</code>```

But everytime i click submit it is validating only the first value. rest all the values of same name are not validated. Please help.

答:
jQuery Form Validator is a feature rich and multilingual jQuery plugin that makes it easy to validate user input while keeping your HTML markup clean from javascript code. Even though this plugin has a wide range of validation functions it's designed to require as little jQuery network traffic as possible. This is achieved by grouping together validation functions in "modules", making it possible to load only those functions that's needed to validate a particular form.</p>

```<code><form action="" id="registration-form">
  <p>
    E-mail
    <input name="email" data-validation="email">
  </p>
  <p>
    User name
    <input name="user" data-validation="length alphanumeric"
         data-validation-length="3-12"
         data-validation-error-msg="User name has to be an alphanumeric value (3-12 chars)">
  </p>
  <p>
    Password
    <input name="pass_confirmation" data-validation="strength"
         data-validation-strength="2">
  </p>
  <p>
    Repeat password
    <input name="pass" data-validation="confirmation">
  </p>
  <p>
    Birth date
    <input name="birth" data-validation="birthdate"
         data-validation-help="yyyy-mm-dd">
  </p>
  <p>
    Country
    <input name="country" id="country" data-validation="country">
  </p>
  <p>
    Profile image
    <input name="image" type="file" data-validation="mime size required"
         data-validation-allowing="jpg, png"
         data-validation-max-size="300kb"
         data-validation-error-msg-required="No image selected">
  </p>
  <p>
    User Presentation (<span id="pres-max-length">100</span> characters left)
    <textarea name="presentation" id="presentation"></textarea>
  </p>
  <p>
    <input type="checkbox" data-validation="required"
         data-validation-error-msg="You have to agree to our terms">
    I agree to the <a href="..." target="_blank">terms of service</a>
  </p>
  <p>
    <input type="submit" value="Validate">
    <input type="reset" value="Reset form">
  </p>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>
<script>

  $.validate({
    modules : 'location, date, security, file',
    onModulesLoaded : function() {
      $('#country').suggestCountry();
    }
  });

  // Restrict presentation length
  $('#presentation').restrictLength( $('#pres-max-length') );

</script>
...
</code>```

Body:
Am new to jquery validation plugin but i would like to know how do we validate array of input boxes using validation plugin..

Below is html code.

<form id="transport-form">
  <input type="text" name="qty[]" id="qty1">
  <input type="text" name="qty[]" id="qty2" >
  <input type="text" name="qty[]" id="qty3">
  <input type="text" name="qty[]" id="qty4">
  <input type="submit value="submit">
</form>

and jquery code is below

jQuery("#transport-form").validate({
        rules: {
            'qty[]': {
                required: true
            }
        },
    });

But everytime i click submit it is validating only the first value. rest all the values of same name are not validated. Please help.

Body:
jQuery Form Validator is a feature rich and multilingual jQuery plugin that makes it easy to validate user input while keeping your HTML markup clean from javascript code. Even though this plugin has a wide range of validation functions it's designed to require as little jQuery network traffic as possible. This is achieved by grouping together validation functions in "modules", making it possible to load only those functions that's needed to validate a particular form.

<form action="" id="registration-form">
  <p>
    E-mail
    <input name="email" data-validation="email">
  </p>
  <p>
    User name
    <input name="user" data-validation="length alphanumeric"
         data-validation-length="3-12"
         data-validation-error-msg="User name has to be an alphanumeric value (3-12 chars)">
  </p>
  <p>
    Password
    <input name="pass_confirmation" data-validation="strength"
         data-validation-strength="2">
  </p>
  <p>
    Repeat password
    <input name="pass" data-validation="confirmation">
  </p>
  <p>
    Birth date
    <input name="birth" data-validation="birthdate"
         data-validation-help="yyyy-mm-dd">
  </p>
  <p>
    Country
    <input name="country" id="country" data-validation="country">
  </p>
  <p>
    Profile image
    <input name="image" type="file" data-validation="mime size required"
         data-validation-allowing="jpg, png"
         data-validation-max-size="300kb"
         data-validation-error-msg-required="No image selected">
  </p>
  <p>
    User Presentation (<span id="pres-max-length">100</span> characters left)
    <textarea name="presentation" id="presentation"></textarea>
  </p>
  <p>
    <input type="checkbox" data-validation="required"
         data-validation-error-msg="You have to agree to our terms">
    I agree to the <a href="..." target="_blank">terms of service</a>
  </p>
  <p>
    <input type="submit" value="Validate">
    <input type="reset" value="Reset form">
  </p>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>
<script>

  $.validate({
    modules : 'location, date, security, file',
    onModulesLoaded : function() {
      $('#country').suggestCountry();
    }
  });

  // Restrict presentation length
  $('#presentation').restrictLength( $('#pres-max-length') );

</script>
...


问:
Can I split a Mercurial repository?
I have a largish Mercurial repository that I've decided would be better as several smaller repositories.  Is there a way that I can split the repository and have each piece retain its revision history?</p>

答:
I found a detailed guide here:

Create a file map new-repo.filemap such as

```<code>include vendor/FooBackend
rename vendor/FooBackend .
</code>```

Create another file map rewrite-old-repo.filemap:

```<code>exclude vendor/FooBackend
</code>```

Create the new repository:

```<code>hg convert /path/to/current/repo /path/to/new/repo --filemap new-repo.filemap
</code>```

The new repository is now finished. The directory is empty, but a hg update will bring its contents up to speed.

Create the modified repository:

```<code>hg convert /path/to/current/repo /path/to/rewritten/repo --filemap rewrite-old-repo.filemap
</code>```

OwnerDisplayName: James Sulak

Title: Can I split a Mercurial repository?

Body:
I found a detailed guide here:

Create a file map new-repo.filemap such as

include vendor/FooBackend
rename vendor/FooBackend .

Create another file map rewrite-old-repo.filemap:

exclude vendor/FooBackend

Create the new repository:

hg convert /path/to/current/repo /path/to/new/repo --filemap new-repo.filemap

The new repository is now finished. The directory is empty, but a hg update will bring its contents up to speed.

Create the modified repository:

hg convert /path/to/current/repo /path/to/rewritten/repo --filemap rewrite-old-repo.filemap


问:
How to pass variable as property name to access value of other object in angular 2 interpolation operator?
I want to pass variable as property of other object and access the value of that property in angular 2 interpolation operator.

I have two objects as below:

```<code>obj1 = { "abc":"123", "xyz":"456", "pqr":"789"}
obj2 = { "123":"name1", "456":"name2", "789":"name3"}
</code>```

And I want to display name1, name2 and name3 based on obj1 property names so I tried below solution but value is not getting displayed in HTML.

```<code>{{obj2["'+obj1.abc+'"]}}
</code>```

How can I achieve this?

Body:
I want to pass variable as property of other object and access the value of that property in angular 2 interpolation operator.

I have two objects as below:

obj1 = { "abc":"123", "xyz":"456", "pqr":"789"}
obj2 = { "123":"name1", "456":"name2", "789":"name3"}

And I want to display name1, name2 and name3 based on obj1 property names so I tried below solution but value is not getting displayed in HTML.

{{obj2["'+obj1.abc+'"]}}

How can I achieve this?

Body:
<!doctype html>
<html >
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
    <script>
    var myApp = angular.module('myApp', []);

myApp.controller('myController', ['$scope', function($scope){
    // Here the array would be your response.text:
     $scope.obj1 = { "abc":"123", "xyz":"456", "pqr":"789"};
    $scope.obj2 = { "123":"name1", "456":"name2", "789":"name3"};

}]);

    </script>
  </head>
  <body >
    <div ng-app="myApp" ng-controller="myController">
    <ul>
        <li ng-repeat="x in obj1">
            {{x}} | {{obj2[x]}}
        </li>
    </ul>
</div>
  </body>
</html>


问:
ipad/iphone, Secure app Distribution
i have developed a ipad static presentation application, here i doesnt want to submit it to the app store.
this app users not even exceed 100.

here my requirement is if user is connected to the internet means app should hit the apple developer site and it should check whether the connected device id is added to current provisioning profile. if device id is there means it should execute the application further else it should not execute.

is there any way to implement this...

is apple is providing any API's to perform these things...?..

any suggestion pls..?

答:
The method you propose is not possible, but close.

When you sign the application for ad-hoc distribution, you sign it with a provisioning profile. This profile contains the ID:s of the devices that the application will run on. It will not even install on other devices.

Take a look at how to do ad-hoc distribution. For less than 100 devices, it is possible to accomplish exactly what you need. The app can then be distributed wirelessly (from a web page) to the authorized devices.

Title: ipad/iphone, Secure app Distribution


问:
RXJava Ignore Error and continue in chain
I have a RXJava chain where an error can be thrown.
I would like the chain to continue and ignore the error and reach the subscribe, for only some specific errors.

For example in this code

```<code>authDataManager
                    .getUserAccessToken(username, password)
                    .subscribeOn(Schedulers.io())
                    .doOnNext({
                        authDataManager.saveUserAccessToken(it)
                    })
                    .flatMap {
                        appDataManager.getStations()
                    }
                    .doOnNext({
                        appDataManager.persistStations(it)
                    })
                    .flatMap {
                        appDataManager.getDriverInformation()
                    }
                    .doOnNext({
                        appDataManager.persistDriverInformation(it)
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(
                            {
                                onLoginSuccess()
                            },
                            {
                                onLoginFailure(it)
                            }
                    )
</code>```

if appDataManager.getStations() throws an error, I still want to continue and reach the onLoginSuccess() method.

However if getUserAccessToken(username, password) fails, onLoginFailure should be called.

I have tried to add onErrorResumeNext() and onExceptionResumeNext() after the flatmaps and inside them, but if I do that, the chain just exits and doesn't continue and reach the subscribe

答:
I think you can use onErrorResumeNext operator.

```<code>              authDataManager
                    .getUserAccessToken(username, password)
                    .subscribeOn(Schedulers.io())
                    .doOnNext({
                        authDataManager.saveUserAccessToken(it)
                    })
                    .flatMap {
                        appDataManager.getStations()
                             .onErrorResumeNext(Observable.empty())
                    }
                    .doOnNext({
                        appDataManager.persistStations(it)
                    })
                    .flatMap {
                        appDataManager.getDriverInformation()
                    }
                    .doOnNext({
                        appDataManager.persistDriverInformation(it)
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(
                            {
                                onLoginSuccess()
                            },
                            {
                                onLoginFailure(it)
                            }
                    )
</code>```

Body:
I have a RXJava chain where an error can be thrown.
I would like the chain to continue and ignore the error and reach the subscribe, for only some specific errors.

For example in this code

authDataManager
                    .getUserAccessToken(username, password)
                    .subscribeOn(Schedulers.io())
                    .doOnNext({
                        authDataManager.saveUserAccessToken(it)
                    })
                    .flatMap {
                        appDataManager.getStations()
                    }
                    .doOnNext({
                        appDataManager.persistStations(it)
                    })
                    .flatMap {
                        appDataManager.getDriverInformation()
                    }
                    .doOnNext({
                        appDataManager.persistDriverInformation(it)
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(
                            {
                                onLoginSuccess()
                            },
                            {
                                onLoginFailure(it)
                            }
                    )

if appDataManager.getStations() throws an error, I still want to continue and reach the onLoginSuccess() method.

However if getUserAccessToken(username, password) fails, onLoginFailure should be called.

I have tried to add onErrorResumeNext() and onExceptionResumeNext() after the flatmaps and inside them, but if I do that, the chain just exits and doesn't continue and reach the subscribe

Body:
I think you can use onErrorResumeNext operator.

              authDataManager
                    .getUserAccessToken(username, password)
                    .subscribeOn(Schedulers.io())
                    .doOnNext({
                        authDataManager.saveUserAccessToken(it)
                    })
                    .flatMap {
                        appDataManager.getStations()
                             .onErrorResumeNext(Observable.empty())
                    }
                    .doOnNext({
                        appDataManager.persistStations(it)
                    })
                    .flatMap {
                        appDataManager.getDriverInformation()
                    }
                    .doOnNext({
                        appDataManager.persistDriverInformation(it)
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(
                            {
                                onLoginSuccess()
                            },
                            {
                                onLoginFailure(it)
                            }
                    )


问:
NoHostAvailable:, In elassandra on insert query with Network Topology Strategy
In elassandra on insert query with Network Topology Strategy it show's 'no host available'.

```<code>cqlsh>CREATE KEYSPACE IF NOT EXISTS twitter WITH replication={ 'class':'NetworkTopologyStrategy', 'dc1':'1' };

cqlsh>CREATE TABLE twitter.user (
   name text,
   attrs map<text,text>,
   PRIMARY KEY (name)
);

cqlsh>INSERT INTO twitter.user (name,attrs) VALUES ('bob',{'email':'bob@gmail.com','firstname':'bob'});
</code>```

nodetool status

another keyspace using same dc, show's this

答: 'dc1' at the time of creating the keyspace should be the Datacenter name when you use nodetool status

Body:
In elassandra on insert query with Network Topology Strategy it show's 'no host available'.

cqlsh>CREATE KEYSPACE IF NOT EXISTS twitter WITH replication={ 'class':'NetworkTopologyStrategy', 'dc1':'1' };

cqlsh>CREATE TABLE twitter.user (
   name text,
   attrs map<text,text>,
   PRIMARY KEY (name)
);

cqlsh>INSERT INTO twitter.user (name,attrs) VALUES ('bob',{'email':'bob@gmail.com','firstname':'bob'});

nodetool status

another keyspace using same dc, show's this


问:
Routing, Views, AngularJs problems ?
i ma having a little problem with my the routing technique in AngularJs, i followed a tutorial and i believe i did not make a mistake, so I am hoping you will prove me wrong and show me the mistake.

here is my routing file :

```<code>app.config(["$routeProvider",
function ($routeProvider) {
    $routeProvider
        .when("/story-1",{
            templateUrl: "views/view.html"
        })

        .when("/story-2",{
            templateUrl: "views/view.html"
        })

        .when("/story-3",{
            templateUrl: "views/view.html"
        })

        .when("/story-4",{
            templateUrl: "views/view.html"
        })

        .when("/story-5",{
            templateUrl: "views/view.html"
        })
}])
</code>```

My app declaration (app.js):

```<code>var app = angular.module("App",["ngRoute"])
</code>```

My html File :

```<code><section id="application">
<div class="un-tiers">
    <div class="routes">
        <div class="route">
            <a href="#!/story-1">Jacline</a>
        </div>
        <div class="route">
            <a href="#!/story-2">The Worst Doctor</a>
        </div>
        <div class="route">
            <a href="#!/story-3">Mr Client</a>
        </div>
        <div class="route">
            <a href="#!/story-4">Monsieur Garnier</a>
        </div>
        <div class="route">
            <a href="#!/story-5">Il était une fois</a>
        </div>
    </div>
</div>
<div class="deux-tiers" ng-view>
</div>
</section>
</code>```

My app is declared in the body :

```<code><body ng-app="App">
</code>```

My imported files needed :

```<code><script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="bower_components/angular-animate/angular-animate.js"></script>

<script src="app.js"></script>
<script src="Routing.js"></script>
</code>```

Thank you for your help

答:
If you are having route in different file, you need to inject that into your main module.

if your router file add

angular.module('myApp.routes', [])

```<code>.config(["$routeProvider",function ($routeProvider) {
    $routeProvider
        .otherwise({
            redirectTo: "your fallback route"
        })
</code>```

}])

Inside your app.js file

var app = angular.module("App",["ngRoute", "myApp.routes"])

Title: Routing, Views, AngularJs problems ?

Body:
i ma having a little problem with my the routing technique in AngularJs, i followed a tutorial and i believe i did not make a mistake, so I am hoping you will prove me wrong and show me the mistake.

here is my routing file :

app.config(["$routeProvider",
function ($routeProvider) {
    $routeProvider
        .when("/story-1",{
            templateUrl: "views/view.html"
        })

        .when("/story-2",{
            templateUrl: "views/view.html"
        })

        .when("/story-3",{
            templateUrl: "views/view.html"
        })

        .when("/story-4",{
            templateUrl: "views/view.html"
        })

        .when("/story-5",{
            templateUrl: "views/view.html"
        })
}])

My app declaration (app.js):

var app = angular.module("App",["ngRoute"])

My html File :

            Jacline

            The Worst Doctor

            Mr Client

            Monsieur Garnier

            Il était une fois

My app is declared in the body :

My imported files needed :

Thank you for your help

Body:
If you are having route in different file, you need to inject that into your main module.

if your router file add

angular.module('myApp.routes', [])

.config(["$routeProvider",function ($routeProvider) {
    $routeProvider
        .otherwise({
            redirectTo: "your fallback route"
        })

}])

Inside your app.js file

var app = angular.module("App",["ngRoute", "myApp.routes"])


问:
Very slow migrations
I have a (KVM) Debian 8 VM server it's running MySQL 5.5.58 and PHP7.1 locally I have a similar machine (Vagrant VM, Debian 8, VirtualBox). Locally my migrations run < 20 seconds if I dump them into a SQL file and import the SQL file it takes about 2-3 seconds.

However on the (KVM) Debian 8 VM server migrations run between 10-20minutes. I have tried increasing CPU count and RAM to no avail.

There are however two things that greately improve performance but still not really usable:

Convert migration files into raw SQL and run that takes about 20-50 seconds.

Set innodb_flush_log_at_trx_commit=0 and run migrations this reduces migration run time down to about 4-5 minutes which is still not usable.

my.cnf

```<code>[mysqld]
sync_binlog = 0
federated = 1
innodb_use_sys_malloc = 0
innodb_file_per_table = 1
innodb_stats_on_metadata = 0
innodb_buffer_pool_instances = 1
query_cache_type = 0
innodb_buffer_pool_size = 1G
innodb_log_file_size = 768M
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT
user        = mysql
pid-file    = /var/run/mysqld/mysqld.pid
socket      = /var/run/mysqld/mysqld.sock
port        = 3306
basedir     = /usr
datadir     = /var/lib/mysql
tmpdir      = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
bind-address        = 127.0.0.1
key_buffer      = 16M
max_allowed_packet  = 16M
thread_stack        = 192K
thread_cache_size       = 8
myisam-recover         = BACKUP
#max_connections        = 100
#table_cache            = 64
#thread_concurrency     = 10
query_cache_limit   = 1M
query_cache_size        = 16M
</code>```

Filesystem:

```<code>Filesystem      Size  Used Avail Use% Mounted on
/dev/vda         32G  6.0G   25G  20% /
udev             11M     0   11M   0% /dev
tmpfs           422M   17M  406M   4% /run
tmpfs           1.1G     0  1.1G   0% /dev/shm
tmpfs           5.3M     0  5.3M   0% /run/lock
tmpfs           1.1G     0  1.1G   0% /sys/fs/cgroup
tmpfs           211M     0  211M   0% /run/user/2031
</code>```

What I have tested and checked:

Made sure I'm using same version of everything as locally myqsl, php, composer packages no discrepencies here.

Tested VM's disk FIO speeds to make sure there is no bottleneck here tried writing/reading single large file as well as tousands of small files getting high speeds across the board (disk is SSD and healthy).

Added extra cores and monitored CPU usage during migration it's pretty small.

Timed execution of Laravel getUp method from Migrator. Specifically timed reading migration file from disk, creating a new class and executing the query all seems to be executing < 1s per migration used microtime(true).

Checked mysql slow queries for any slow queries nothing was found, migrations are really very basic CREATE TABLE statements.

Tried installing MySQL 5.7 there was no improvement.

Tried increasing MySQL pool and log RAM size.

Made sure I'm using InnoDB.

Note: This happens in all ways of using MySQL I tested with MySQL installed on host. I installed docker mysql same issue. I installed vagrant instance and mysql inside that same issue.

This innodb_flush_log_at_trx_comit seems to make the most difference indicating I messed up something with mysql just not sure why. Migrations each runs as it's own transaction seems something is causing wait time here not sure what else to check.

答:
Your raw SQL most likely has a mess of INSERT queries in it.

Edit The SQL generated by MySQLDump certainly does have lots of inserts in it. Populating a test dbms is often done from a version-controlled SQL file. Here's some q&a about doing it in docker.

Wrap each series of 100 queries or so (the actual number doesn't matter very much) in  transactions by putting START TRANSACTION; at the beginning and COMMIT; at the end. That will get rid of the churning that goes with autocommit.  You'll have a SQL file looking something like this:

```<code>START TRANSACTION;
INSERT ...;
... (more inserts)
INSERT ...;
COMMIT;
START TRANSACTION;
INSERT ...;
... (more inserts)
INSERT ...;
COMMIT;
START TRANSACTION;
INSERT ...;
... (more inserts)
INSERT ...;
COMMIT;
</code>```

Avoid horsing around with innodb parameters; the defaults are generally pretty good, and only need to be changed for large dynamic loads.

And don't expect your VMs to perform as well as your laptop. The days when servers were faster than laptops are gone (for most of us).

Title: Very slow migrations

Body:
I have a (KVM) Debian 8 VM server it's running MySQL 5.5.58 and PHP7.1 locally I have a similar machine (Vagrant VM, Debian 8, VirtualBox). Locally my migrations run < 20 seconds if I dump them into a SQL file and import the SQL file it takes about 2-3 seconds.

However on the (KVM) Debian 8 VM server migrations run between 10-20minutes. I have tried increasing CPU count and RAM to no avail.

There are however two things that greately improve performance but still not really usable:

Convert migration files into raw SQL and run that takes about 20-50 seconds.

Set innodb_flush_log_at_trx_commit=0 and run migrations this reduces migration run time down to about 4-5 minutes which is still not usable.

my.cnf

[mysqld]
sync_binlog = 0
federated = 1
innodb_use_sys_malloc = 0
innodb_file_per_table = 1
innodb_stats_on_metadata = 0
innodb_buffer_pool_instances = 1
query_cache_type = 0
innodb_buffer_pool_size = 1G
innodb_log_file_size = 768M
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT
user        = mysql
pid-file    = /var/run/mysqld/mysqld.pid
socket      = /var/run/mysqld/mysqld.sock
port        = 3306
basedir     = /usr
datadir     = /var/lib/mysql
tmpdir      = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
bind-address        = 127.0.0.1
key_buffer      = 16M
max_allowed_packet  = 16M
thread_stack        = 192K
thread_cache_size       = 8
myisam-recover         = BACKUP
#max_connections        = 100
#table_cache            = 64
#thread_concurrency     = 10
query_cache_limit   = 1M
query_cache_size        = 16M

Filesystem:

Filesystem      Size  Used Avail Use% Mounted on
/dev/vda         32G  6.0G   25G  20% /
udev             11M     0   11M   0% /dev
tmpfs           422M   17M  406M   4% /run
tmpfs           1.1G     0  1.1G   0% /dev/shm
tmpfs           5.3M     0  5.3M   0% /run/lock
tmpfs           1.1G     0  1.1G   0% /sys/fs/cgroup
tmpfs           211M     0  211M   0% /run/user/2031

What I have tested and checked:

Made sure I'm using same version of everything as locally myqsl, php, composer packages no discrepencies here.

Tested VM's disk FIO speeds to make sure there is no bottleneck here tried writing/reading single large file as well as tousands of small files getting high speeds across the board (disk is SSD and healthy).

Added extra cores and monitored CPU usage during migration it's pretty small.

Timed execution of Laravel getUp method from Migrator. Specifically timed reading migration file from disk, creating a new class and executing the query all seems to be executing < 1s per migration used microtime(true).

Checked mysql slow queries for any slow queries nothing was found, migrations are really very basic CREATE TABLE statements.

Tried installing MySQL 5.7 there was no improvement.

Tried increasing MySQL pool and log RAM size.

Made sure I'm using InnoDB.

Note: This happens in all ways of using MySQL I tested with MySQL installed on host. I installed docker mysql same issue. I installed vagrant instance and mysql inside that same issue.

This innodb_flush_log_at_trx_comit seems to make the most difference indicating I messed up something with mysql just not sure why. Migrations each runs as it's own transaction seems something is causing wait time here not sure what else to check.

Body:
Your raw SQL most likely has a mess of INSERT queries in it.

Edit The SQL generated by MySQLDump certainly does have lots of inserts in it. Populating a test dbms is often done from a version-controlled SQL file. Here's some q&a about doing it in docker.

Wrap each series of 100 queries or so (the actual number doesn't matter very much) in  transactions by putting START TRANSACTION; at the beginning and COMMIT; at the end. That will get rid of the churning that goes with autocommit.  You'll have a SQL file looking something like this:

START TRANSACTION;
INSERT ...;
... (more inserts)
INSERT ...;
COMMIT;
START TRANSACTION;
INSERT ...;
... (more inserts)
INSERT ...;
COMMIT;
START TRANSACTION;
INSERT ...;
... (more inserts)
INSERT ...;
COMMIT;

Avoid horsing around with innodb parameters; the defaults are generally pretty good, and only need to be changed for large dynamic loads.

And don't expect your VMs to perform as well as your laptop. The days when servers were faster than laptops are gone (for most of us).


问:
Glassfish - can't log in to admin console
I'm facing strange error. I use Glassfish 3.1.1 withn jdk7 and since some time I can't login to admin console via web (localhost:4848), I keep getting message Authentication Failed Re-enter your username and password here are logs:

[#|2012-01-16T11:15:37.415+0100|INFO|glassfish3.1.1|javax.enterprise.system.tools.admin.com.sun.enterprise.container.common|_ThreadID=110;_ThreadName=Thread-2;|User
  [admin] from host 127.0.0.1 does not have administration access|#]

[#|2012-01-16T11:15:37.446+0100|INFO|glassfish3.1.1|javax.enterprise.system.tools.admin.com.sun.enterprise.container.common|_ThreadID=101;_ThreadName=Thread-2;|User
  [admin] from host 127.0.0.1 does not have administration access|#]

[#|2012-01-16T11:16:07.008+0100|SEVERE|glassfish3.1.1|org.glassfish.admin.rest.resources.GeneratorResource|_ThreadID=100;_ThreadName=Thread-2;|The
  log message is null. java.lang.RuntimeException: Cannot find
  annotation org.glassfish.config.support.Create with value
  _register-instance on method public abstract com.sun.enterprise.config.serverbeans.Server
  com.sun.enterprise.config.serverbeans.Servers.getServer(java.lang.String)
    at
  org.glassfish.config.support.GenericCrudCommand.getAnnotation(GenericCrudCommand.java:196)
    at
  org.glassfish.config.support.GenericCreateCommand.postConstruct(GenericCreateCommand.java:90)
    at
  com.sun.hk2.component.AbstractCreatorImpl.inject(AbstractCreatorImpl.java:131)
    at
  com.sun.hk2.component.ConstructorCreator.initialize(ConstructorCreator.java:91)
    at
  com.sun.hk2.component.AbstractCreatorImpl.get(AbstractCreatorImpl.java:82)
    at
  com.sun.hk2.component.EventPublishingInhabitant.get(EventPublishingInhabitant.java:139)
    at
  com.sun.hk2.component.AbstractInhabitantImpl.get(AbstractInhabitantImpl.java:76)  at org.jvnet.hk2.component.Habitat.getComponent(Habitat.java:796)   at
  com.sun.enterprise.v3.admin.CommandRunnerImpl.getModel(CommandRunnerImpl.java:150)
    at
  org.glassfish.admin.rest.generator.ResourcesGeneratorBase.commandIsPresent(ResourcesGeneratorBase.java:315)
    at
  org.glassfish.admin.rest.generator.ResourcesGeneratorBase.generateCommandResources(ResourcesGeneratorBase.java:296)
    at
  org.glassfish.admin.rest.generator.ResourcesGeneratorBase.generateSingle(ResourcesGeneratorBase.java:100)
    at
  org.glassfish.admin.rest.LazyJerseyInit.generateASM(LazyJerseyInit.java:311)
    at
  org.glassfish.admin.rest.LazyJerseyInit.getResourcesConfigForManagement(LazyJerseyInit.java:255)
    at
  org.glassfish.admin.rest.adapter.RestManagementAdapter.getResourcesConfig(RestManagementAdapter.java:62)
    at
  org.glassfish.admin.rest.adapter.RestAdapter.exposeContext(RestAdapter.java:455)
    at
  org.glassfish.admin.rest.adapter.RestAdapter.service(RestAdapter.java:177)
    at
  com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:168)
    at
  com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117)
    at
  com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:238)
    at
  com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
    at
  com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
    at
  com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
    at
  com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
    at
  com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at
  com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at
  com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at
  com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at
  com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at
  com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)     at
  com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at
  com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:722) |#]

[#|2012-01-16T11:16:07.008+0100|SEVERE|glassfish3.1.1|org.glassfish.admin.rest.LazyJerseyInit|_ThreadID=100;_ThreadName=Thread-2;|The
  log message is null. java.lang.ClassNotFoundException:
  org.glassfish.admin.rest.resources.generatedASM.DomainResource not
  found by org.glassfish.admin.rest-service [164]   at
  org.apache.felix.framework.ModuleImpl.findClassOrResourceByDelegation(ModuleImpl.java:787)
    at
  org.apache.felix.framework.ModuleImpl.access$400(ModuleImpl.java:71)
    at
  org.apache.felix.framework.ModuleImpl$ModuleClassLoader.loadClass(ModuleImpl.java:1768)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)    at
  java.lang.Class.forName0(Native Method)   at
  java.lang.Class.forName(Class.java:186)   at
  org.glassfish.admin.rest.LazyJerseyInit.getResourcesConfigForManagement(LazyJerseyInit.java:257)
    at
  org.glassfish.admin.rest.adapter.RestManagementAdapter.getResourcesConfig(RestManagementAdapter.java:62)
    at
  org.glassfish.admin.rest.adapter.RestAdapter.exposeContext(RestAdapter.java:455)
    at
  org.glassfish.admin.rest.adapter.RestAdapter.service(RestAdapter.java:177)
    at
  com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:168)
    at
  com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117)
    at
  com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:238)
    at
  com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
    at
  com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
    at
  com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
    at
  com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
    at
  com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at
  com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at
  com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at
  com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at
  com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at
  com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)     at
  com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at
  com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:722) |#]

[#|2012-01-16T11:16:07.071+0100|INFO|glassfish3.1.1|com.sun.jersey.server.impl.application.WebApplicationImpl|_ThreadID=100;_ThreadName=Thread-2;|Initiating
  Jersey application, version 'Jersey: 1.8 06/24/2011 12:17 PM'|#]

[#|2012-01-16T11:16:07.086+0100|WARNING|glassfish3.1.1|org.apache.catalina.connector.Request|_ThreadID=111;_ThreadName=Thread-2;|PWC4011:
  Unable to set request character encoding to UTF-8 from context ,
  because request parameters have already been read, or
  ServletRequest.getReader() has already been called|#]

Username and password are 100% correct, I have no problem login via asadmin cmd.

答:
I also faced the same problem with 4.0 and 4.1.1.

However, 4.1.2. appears to fix the issue. I installed it (from here), and no login details are requested.


问:
double quotes inside double quotes
i am writing the following connection string into web.config
but it giving me error.what is the correct way to write it?</p>

```<code><add name="stargaze_stargazeConnectionString1" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename="D:\Work At DS\19th Jan\myastrolove.com_new\App_Data\dbName.mdf";Integrated Security=True;User Instance=True"/>
</code>```

答:
Inside the string, replace " with \" to properly escape it.

That means that your string should look like this:

```<code>"<add name=\"stargaze_stargazeConnectionString1\" connectionString=\"Data Source=.\SQLEXPRESS;AttachDbFilename=\"D:\Work At DS\19th Jan\myastrolove.com_new\App_Data\dbName.mdf\";Integrated Security=True;User Instance=True\"/>"
</code>```

Title: double quotes inside double quotes

Body:
i am writing the following connection string into web.config
but it giving me error.what is the correct way to write it?

<add name="stargaze_stargazeConnectionString1" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename="D:\Work At DS\19th Jan\myastrolove.com_new\App_Data\dbName.mdf";Integrated Security=True;User Instance=True"/>

Body:
Inside the string, replace " with \" to properly escape it.

That means that your string should look like this:

"<add name=\"stargaze_stargazeConnectionString1\" connectionString=\"Data Source=.\SQLEXPRESS;AttachDbFilename=\"D:\Work At DS\19th Jan\myastrolove.com_new\App_Data\dbName.mdf\";Integrated Security=True;User Instance=True\"/>"


问:
How to write query with outer joins and multiple OR criteria?
In this query we perform outer joins from a large table release to two tables release_event and release_barcode. These must be outer joins, because in the results we want to return releases which don't have entries in either table:

```<code>SELECT r.source_uri AS su_on_r, r.title AS t_on_r, release_event.cat, release_barcode.barcode
FROM   release r
    left join release_event event ON r.source_uri = event.source_uri
    left join release_barcode barcode ON r.source_uri = barcode.source_uri
WHERE  ( event.cat IN ( '3145422912' ) AND event.label_name = 'UTV Records' )
    OR barcode.barcode IN ( '731454229128' )
</code>```

When analysed, this performs a sequential scan on the release table:

```<code>|   ->  Sort  (cost=2169219.61..2169219.65 rows=13 width=66)                                                                                |
|         Sort Key: r.source_uri                                                                                |
|         ->  Hash Left Join  (cost=721970.94..2169219.37 rows=13 width=66)                                                                                |
|               Hash Cond: ((r.source_uri)::text = (barcode.source_uri)::text)                                                                                |
|               Filter: ((((event.cat)::text = '3145422912'::text) AND ((event.label_name)::text = 'UTV Records'::text)) OR ((barcode.barcode)::text = '731454229128'::text)) |
|               ->  Hash Right Join  (cost=589927.01..1568193.22 rows=11405330 width=88)                                                                                |
|                     Hash Cond: ((event.source_uri)::text = (r.source_uri)::text)                                                                                |
|                     ->  Seq Scan on release_event event  (cost=0.00..283078.30 rows=11405330 width=65)                                                                      |
|                     ->  Hash  (cost=324393.56..324393.56 rows=10963956 width=66)                                                                                |
|                           ->  Seq Scan on release r  (cost=0.00..324393.56 rows=10963956 width=66)                                                                          |
|               ->  Hash  (cost=63125.97..63125.97 rows=2965197 width=60)                                                                                |
|                     ->  Seq Scan on release_barcode barcode  (cost=0.00..63125.97 rows=2965197 width=6
</code>```

If I have just one of the above criteria, the query planner (Postgresql) understands this, using the indexes to limit results from release:

```<code>|   ->  Sort  (cost=42.26..42.27 rows=3 width=66)                                                                               |
|         Sort Key: r.source_uri                                                                                |
|         ->  Nested Loop  (cost=0.99..42.24 rows=3 width=66)                                                                   |
|               ->  Index Scan using release_barcode_barcode_idx on release_barcode barcode  (cost=0.43..16.47 rows=3 width=47) |
|                     Index Cond: ((barcode)::text = '731454229128'::text)                                                      |
|               ->  Index Scan using release_pkey on release r  (cost=0.56..8.58 rows=1 width=66)                               |
|                     Index Cond: ((source_uri)::text = (barcode.source_uri)::text)
</code>```

How can I rewrite queries with outer joins and multiple OR'd criteria to first limit the joined tables and only lookup the release table for any of those rows that match?

答:
Filter before joining:</p>

```<code>select
    source_uri as su_on_r,
    r.title as t_on_r,
    event.cat,
    barcode.barcode
from
    release r
    left join (
        select *
        from release_event
        where cat in ('3145422912') and label_name = 'utv records'
    ) event using (source_uri)
    left join (
        select *
        from release_barcode
        where barcode in ('731454229128')
    ) barcode using (source_uri)
</code>```

Body:
In this query we perform outer joins from a large table release to two tables release_event and release_barcode. These must be outer joins, because in the results we want to return releases which don't have entries in either table:

SELECT r.source_uri AS su_on_r, r.title AS t_on_r, release_event.cat, release_barcode.barcode
FROM   release r
    left join release_event event ON r.source_uri = event.source_uri
    left join release_barcode barcode ON r.source_uri = barcode.source_uri
WHERE  ( event.cat IN ( '3145422912' ) AND event.label_name = 'UTV Records' )
    OR barcode.barcode IN ( '731454229128' )

When analysed, this performs a sequential scan on the release table:

|   ->  Sort  (cost=2169219.61..2169219.65 rows=13 width=66)                                                                                |
|         Sort Key: r.source_uri                                                                                |
|         ->  Hash Left Join  (cost=721970.94..2169219.37 rows=13 width=66)                                                                                |
|               Hash Cond: ((r.source_uri)::text = (barcode.source_uri)::text)                                                                                |
|               Filter: ((((event.cat)::text = '3145422912'::text) AND ((event.label_name)::text = 'UTV Records'::text)) OR ((barcode.barcode)::text = '731454229128'::text)) |
|               ->  Hash Right Join  (cost=589927.01..1568193.22 rows=11405330 width=88)                                                                                |
|                     Hash Cond: ((event.source_uri)::text = (r.source_uri)::text)                                                                                |
|                     ->  Seq Scan on release_event event  (cost=0.00..283078.30 rows=11405330 width=65)                                                                      |
|                     ->  Hash  (cost=324393.56..324393.56 rows=10963956 width=66)                                                                                |
|                           ->  Seq Scan on release r  (cost=0.00..324393.56 rows=10963956 width=66)                                                                          |
|               ->  Hash  (cost=63125.97..63125.97 rows=2965197 width=60)                                                                                |
|                     ->  Seq Scan on release_barcode barcode  (cost=0.00..63125.97 rows=2965197 width=6

If I have just one of the above criteria, the query planner (Postgresql) understands this, using the indexes to limit results from release:

|   ->  Sort  (cost=42.26..42.27 rows=3 width=66)                                                                               |
|         Sort Key: r.source_uri                                                                                |
|         ->  Nested Loop  (cost=0.99..42.24 rows=3 width=66)                                                                   |
|               ->  Index Scan using release_barcode_barcode_idx on release_barcode barcode  (cost=0.43..16.47 rows=3 width=47) |
|                     Index Cond: ((barcode)::text = '731454229128'::text)                                                      |
|               ->  Index Scan using release_pkey on release r  (cost=0.56..8.58 rows=1 width=66)                               |
|                     Index Cond: ((source_uri)::text = (barcode.source_uri)::text)

How can I rewrite queries with outer joins and multiple OR'd criteria to first limit the joined tables and only lookup the release table for any of those rows that match?

Body:
Filter before joining:

select
    source_uri as su_on_r,
    r.title as t_on_r,
    event.cat,
    barcode.barcode
from
    release r
    left join (
        select *
        from release_event
        where cat in ('3145422912') and label_name = 'utv records'
    ) event using (source_uri)
    left join (
        select *
        from release_barcode
        where barcode in ('731454229128')
    ) barcode using (source_uri)


问:
Modified Gram Schmidt in Python for complex vectors
I wrote some code to implement the modified Gram Schmidt process. When
I tested it on real matrices, it is correct. However, when I tested it
on complex matrices, it went wrong.

I believe my code is correct by doing a step by step check. Therefore,
I wonder if there are numerical reasons why the modified Gram Schmidt
process fails on complex vectors.

Following is the code:

import numpy as np

def modifiedGramSchmidt(A):
    """
    Gives a orthonormal matrix, using modified Gram Schmidt Procedure
    :param A: a matrix of column vectors
    :return: a matrix of orthonormal column vectors
    """
    # assuming A is a square matrix
    dim = A.shape[0]
    Q = np.zeros(A.shape, dtype=A.dtype)
    for j in range(0, dim):
        q = A[:,j]
        for i in range(0, j):
            rij = np.vdot(q, Q[:,i])
            q = q - rij*Q[:,i]
        rjj = np.linalg.norm(q, ord=2)
        if np.isclose(rjj,0.0):
            raise ValueError("invalid input matrix")
        else:
            Q[:,j] = q/rjj
    return Q
```

<p>Following is the test code:</p>

<pre class="lang-python prettyprint-override"><code>import numpy as np

# If testing on random matrices:
# X = np.random.rand(dim,dim)*10  + np.random.rand(dim,dim)*5 *1j
# If testing on some good one
v1 = np.array([1, 0, 1j]).reshape((3,1))
v2 = np.array([-1, 1j, 1]).reshape((3,1))
v3 = np.array([0, -1, 1j+1]).reshape((3,1))
X = np.hstack([v1,v2,v3])
Y = modifiedGramSchmidt(X)
Y3 = np.linalg.qr(X, mode="complete")[0]
if np.isclose(Y3.conj().T.dot(Y3), np.eye(dim, dtype=complex)).all():
    print("The QR-complete gives orthonormal vectors")
if np.isclose(Y.conj().T.dot(Y), np.eye(dim, dtype=complex)).all():
    print("The Gram Schmidt process is tested against a random matrix")
else:
    print("But My modified GS goes wrong!")
    print(Y.conj().T.dot(Y))
</code>```

Update

The problem is that I implemented a algorithm designed for inner product linear in first argument

whereas I thought it were linear in second argument.

Thanks @landogardner

答:
Your problem is to do with how numpy.vdot handles complex numbers — the complex conjugate of the first argument is used for the calculation (ref). So you're calculating rij as q*.Q[:,i] instead of q.Q[:,i]*. Just swap the order of the args:

```<code>rij = np.vdot(Q[:,i], q)
</code>```

This got the test code working for me.

Body:
I wrote some code to implement the modified Gram Schmidt process. When
I tested it on real matrices, it is correct. However, when I tested it
on complex matrices, it went wrong.

I believe my code is correct by doing a step by step check. Therefore,
I wonder if there are numerical reasons why the modified Gram Schmidt
process fails on complex vectors.

Following is the code:

import numpy as np

def modifiedGramSchmidt(A):
    """
    Gives a orthonormal matrix, using modified Gram Schmidt Procedure
    :param A: a matrix of column vectors
    :return: a matrix of orthonormal column vectors
    """
    # assuming A is a square matrix
    dim = A.shape[0]
    Q = np.zeros(A.shape, dtype=A.dtype)
    for j in range(0, dim):
        q = A[:,j]
        for i in range(0, j):
            rij = np.vdot(q, Q[:,i])
            q = q - rij*Q[:,i]
        rjj = np.linalg.norm(q, ord=2)
        if np.isclose(rjj,0.0):
            raise ValueError("invalid input matrix")
        else:
            Q[:,j] = q/rjj
    return Q

Following is the test code:

import numpy as np

# If testing on random matrices:
# X = np.random.rand(dim,dim)*10  + np.random.rand(dim,dim)*5 *1j
# If testing on some good one
v1 = np.array([1, 0, 1j]).reshape((3,1))
v2 = np.array([-1, 1j, 1]).reshape((3,1))
v3 = np.array([0, -1, 1j+1]).reshape((3,1))
X = np.hstack([v1,v2,v3])
Y = modifiedGramSchmidt(X)
Y3 = np.linalg.qr(X, mode="complete")[0]
if np.isclose(Y3.conj().T.dot(Y3), np.eye(dim, dtype=complex)).all():
    print("The QR-complete gives orthonormal vectors")
if np.isclose(Y.conj().T.dot(Y), np.eye(dim, dtype=complex)).all():
    print("The Gram Schmidt process is tested against a random matrix")
else:
    print("But My modified GS goes wrong!")
    print(Y.conj().T.dot(Y))

Update

The problem is that I implemented a algorithm designed for inner product linear in first argument

whereas I thought it were linear in second argument.

Thanks @landogardner

Body:
Your problem is to do with how numpy.vdot handles complex numbers — the complex conjugate of the first argument is used for the calculation (ref). So you're calculating rij as q*.Q[:,i] instead of q.Q[:,i]*. Just swap the order of the args:

rij = np.vdot(Q[:,i], q)

This got the test code working for me.


答:
This is a bit of a shot in the dark, but what if you moved your where conditions inside the left join and then tested to see if either/or record was successful in the join:

```<code>SELECT
  r.source_uri AS su_on_r, r.title AS t_on_r, release_event.cat, release_barcode.barcode
FROM
  release r
  left join release_event event ON
    r.source_uri = event.source_uri  and
    event.cat IN ( '3145422912' ) AND
    event.label_name = 'UTV Records'
  left join release_barcode barcode ON
     r.source_uri = barcode.source_uri and
     barcode.barcode IN ( '731454229128' )
WHERE
  event.source_uri is not null or
  barcode.source_uri is not null
</code>```

@a_horse_with_no_name made a comment about how your construct actually becomes an inner join, and I think this would overcome that.  Whether it gets the results (and performance you seek), I'm not certain.

Title: How to write query with outer joins and multiple OR criteria?

Body:
This is a bit of a shot in the dark, but what if you moved your where conditions inside the left join and then tested to see if either/or record was successful in the join:

SELECT
  r.source_uri AS su_on_r, r.title AS t_on_r, release_event.cat, release_barcode.barcode
FROM
  release r
  left join release_event event ON
    r.source_uri = event.source_uri  and
    event.cat IN ( '3145422912' ) AND
    event.label_name = 'UTV Records'
  left join release_barcode barcode ON
     r.source_uri = barcode.source_uri and
     barcode.barcode IN ( '731454229128' )
WHERE
  event.source_uri is not null or
  barcode.source_uri is not null

@a_horse_with_no_name made a comment about how your construct actually becomes an inner join, and I think this would overcome that.  Whether it gets the results (and performance you seek), I'm not certain.


问:
Magento2 installtion stuck at 51%
I am installing Magento2 using Xampp in windows 10. I have changed max_execution_time memory_limit but it is stucked at 51% everytime.

答:
If You are installing magento with sample data then try magento2 latest version without sample data and after successful installation you can upload sample data by </p>

```<code>php <your Magento install dir>/bin/magento sampledata:deploy
</code>```

Title: Magento2 installtion stuck at 51%

Body:
If You are installing magento with sample data then try magento2 latest version without sample data and after successful installation you can upload sample data by

php <your Magento install dir>/bin/magento sampledata:deploy