问:
Error while Running MIDP 2 applications in netbeans
I am trying to run(emulate) a simple midp2 j2me application in netbeans(6.8) in ubuntu 10.04. It is building fine , with no errors, but when i choose run , it  gives "http server is not running.start it first" error.
I am able to successfully build and run it using  the java wireless toolkit. But  using Netbeans would be easier. </p>

答: I think in your coding u make use of server/servlet,etc.So before executing ur application run the server then execute the application .Then it works.</p>

ContentLicense: CC BY-SA 2.5


来源: stackexchange

问:
cannot find symbol“_mm256_max_epu8” when I want to use AVX2 instruction in visual studio 2010
Environment: Win10, Intel Core i7 5500U CPU, Visual Studio 2010 Ultimate

Now I want to use "_mm256_max_epu8" Intel SIMD instruction which is in AVX2,but the Visual Studio 2010 tells me that:

1>..\svCore\svGrayMorph.cpp(838): error C3861: “_mm256_max_epu8”: 找不到标识符

I have found that AVX2 instructions should be declared in file:

...\Microsoft Visual Studio 10.0\VC\include\immintrin.h

However, the file only have AVX instructions, the "_mm256_max_epu8" and other instructions are not in that file.

While the immintrin.h file of Visual Studio 2013 include the AVX2 instruction.

Do SomeOne Know What I can Do to compile this code in Visual Studio 2010 ?

Thank you so much.

答:
As it was written earlier Visual Studio 2010 doesn't support AVX2 and you have to use Visual Studio 2013.

But if you want to use universal code which will be compilable in both versions of Visual Studio you have to use conditional compilation with using of macros.

There is an example:

```<code>#if defined(_MSC_VER) && _MSC_VER >= 1700 //Visual Studio 2013
#define AVX2_ENABLE
#endif

#ifdef AVX2_ENABLE
void func()
{
     //code with AVX2
}
#else
void func()
{
     //code without AVX2
}
#endif
</code>```

Here you can find more examples how to use different SIMD extensions in the one project.

ContentLicense: CC BY-SA 3.0

Body:
As it was written earlier Visual Studio 2010 doesn't support AVX2 and you have to use Visual Studio 2013.

But if you want to use universal code which will be compilable in both versions of Visual Studio you have to use conditional compilation with using of macros.

There is an example:

#if defined(_MSC_VER) && _MSC_VER >= 1700 //Visual Studio 2013
#define AVX2_ENABLE
#endif

#ifdef AVX2_ENABLE
void func()
{
     //code with AVX2
}
#else
void func()
{
     //code without AVX2
}
#endif

Here you can find more examples how to use different SIMD extensions in the one project.


问:
ArtifactTransferException: Failure to transfer org.springframework.data:spring-data-jpa:jar:1.7.0.RELEASE
Iam getting the following compile time error in pom file

```<code>ArtifactTransferException: Failure to transfer org.springframework.data:spring-data-jpa:jar:1.7.0.RELEASE from http://repo.maven.apache.org/maven2 was cached in the local
 repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer artifact
 org.springframework.data:spring-data-jpa:jar:1.7.0.RELEASE from/to central (http://repo.maven.apache.org/maven2): Access denied to http://repo.maven.apache.org/maven2/org/
 springframework/data/spring-data-jpa/1.7.0.RELEASE/spring-data-jpa-1.7.0.RELEASE.jar. Error code 403, Forbidden
</code>```

My POM file is:

```<code>    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.technicalkeeda</groupId>
    <artifactId>com.technicalkeeda</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>HibernateExamples</name>
    <properties>
        <hibernate.version>4.3.5.Final</hibernate.version>
        <spring.version>4.1.0.RELEASE</spring.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>asm</groupId>
            <artifactId>asm</artifactId>
            <version>3.1</version>
        </dependency>

        <dependency>
            <groupId>javax.transaction</groupId>
            <artifactId>jta</artifactId>
            <version>1.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache -->
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>2.10.3</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- JavaConfig need this library -->
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2.2</version>
        </dependency>

        <!-- Spring AOP + AspectJ -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.7.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/aopalliance/aopalliance -->
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>1.5.2.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.7.0.RELEASE</version>
        </dependency>

    </dependencies>
    <build>
        <finalName>HibernateExamples</finalName>
    </build>
</project>
</code>```

Solutions I have tried:

Checked the proxy settings "setttings.xml" file

Deleted the repository and updated the maven project again.

Using:
Maven 3.3.1
Java 7

答: Delete the jars only where errors occurred from .m2 repository. Then in eclipse right click -> Maven -> Update Project, click everything except offline and click OK.</p>

Body:
Iam getting the following compile time error in pom file

ArtifactTransferException: Failure to transfer org.springframework.data:spring-data-jpa:jar:1.7.0.RELEASE from http://repo.maven.apache.org/maven2 was cached in the local
 repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer artifact
 org.springframework.data:spring-data-jpa:jar:1.7.0.RELEASE from/to central (http://repo.maven.apache.org/maven2): Access denied to http://repo.maven.apache.org/maven2/org/
 springframework/data/spring-data-jpa/1.7.0.RELEASE/spring-data-jpa-1.7.0.RELEASE.jar. Error code 403, Forbidden

My POM file is:

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.technicalkeeda</groupId>
    <artifactId>com.technicalkeeda</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>HibernateExamples</name>
    <properties>
        <hibernate.version>4.3.5.Final</hibernate.version>
        <spring.version>4.1.0.RELEASE</spring.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>asm</groupId>
            <artifactId>asm</artifactId>
            <version>3.1</version>
        </dependency>

        <dependency>
            <groupId>javax.transaction</groupId>
            <artifactId>jta</artifactId>
            <version>1.1</version>
        </dependency>

        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>2.10.3</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.7.4</version>
        </dependency>

        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>1.5.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.7.0.RELEASE</version>
        </dependency>

    </dependencies>
    <build>
        <finalName>HibernateExamples</finalName>
    </build>
</project>

Solutions I have tried:

Checked the proxy settings "setttings.xml" file

Deleted the repository and updated the maven project again.

Using:
Maven 3.3.1
Java 7


问:
SQLAlchemy Metadata Relationship with Multiple Foreign Keys
I'm new to SQLAlchemy and trying to set up an ORM for an existing database. I'm setting up the tables using metadata and specifying the foreign keys myself. The table setup looks like this:

```<code>class User(Base):
    __table__ = Table('users', metadata,
                      Column('user_id', Integer, primary_key=True),
                      autoload=True)

class Transaction(Base):
    __table__ = Table('transaction', metadata,
                      Column('transaction_id', Integer, primary_key=True),
                      Column('seller_id', Integer, ForeignKey('users.user_id')),
                      Column('buyer_id', Integer, ForeignKey('users.user_id')),
                      autoload=True)
    seller = relationship('User', foreign_keys=[seller_id])
    buyer = relationship('User', foreign_keys=[buyer_id])
</code>```

This doesn't run, with the error:

```<code>NameError: name 'seller_id' is not defined
</code>```

Any idea what's wrong?

答:
To understand why you get the error you should refresh your understanding on class construction in Python:

When a class definition is entered, a new namespace is created, and used as the local scope — thus, all assignments to local variables go into this new namespace. In particular, function definitions bind the name of the new function here.

In your example you have no assignments to seller_id that would introduce the name, and so an attempt to use that name during class construction raises the NameError. What you do have available in the current namespace during class construction is the __table__ that you assigned. In fact this exact use case is documented under "Using a Hybrid Approach with __table__":

Note that when the __table__ approach is used, the object is immediately usable as a plain Table within the class declaration body itself, as a Python class is only another syntactical block.

In other words access the columns through the Table object bound to the name __table__:

```<code>class Transaction(Base):
    __table__ = Table('transaction', metadata,
                      Column('transaction_id', Integer, primary_key=True),
                      Column('seller_id', Integer, ForeignKey('users.user_id')),
                      Column('buyer_id', Integer, ForeignKey('users.user_id')),
                      autoload=True)
    seller = relationship('User', foreign_keys=[__table__.c.seller_id])
    buyer = relationship('User', foreign_keys=[__table__.c.buyer_id])
</code>```

Body:
I'm new to SQLAlchemy and trying to set up an ORM for an existing database. I'm setting up the tables using metadata and specifying the foreign keys myself. The table setup looks like this:

class User(Base):
    __table__ = Table('users', metadata,
                      Column('user_id', Integer, primary_key=True),
                      autoload=True)

class Transaction(Base):
    __table__ = Table('transaction', metadata,
                      Column('transaction_id', Integer, primary_key=True),
                      Column('seller_id', Integer, ForeignKey('users.user_id')),
                      Column('buyer_id', Integer, ForeignKey('users.user_id')),
                      autoload=True)
    seller = relationship('User', foreign_keys=[seller_id])
    buyer = relationship('User', foreign_keys=[buyer_id])

This doesn't run, with the error:

NameError: name 'seller_id' is not defined

Any idea what's wrong?

Body:
To understand why you get the error you should refresh your understanding on class construction in Python:

When a class definition is entered, a new namespace is created, and used as the local scope — thus, all assignments to local variables go into this new namespace. In particular, function definitions bind the name of the new function here.

In your example you have no assignments to seller_id that would introduce the name, and so an attempt to use that name during class construction raises the NameError. What you do have available in the current namespace during class construction is the __table__ that you assigned. In fact this exact use case is documented under "Using a Hybrid Approach with __table__":

Note that when the __table__ approach is used, the object is immediately usable as a plain Table within the class declaration body itself, as a Python class is only another syntactical block.

In other words access the columns through the Table object bound to the name __table__:

class Transaction(Base):
    __table__ = Table('transaction', metadata,
                      Column('transaction_id', Integer, primary_key=True),
                      Column('seller_id', Integer, ForeignKey('users.user_id')),
                      Column('buyer_id', Integer, ForeignKey('users.user_id')),
                      autoload=True)
    seller = relationship('User', foreign_keys=[__table__.c.seller_id])
    buyer = relationship('User', foreign_keys=[__table__.c.buyer_id])


问:
TableViewCell is not clickable with one finger tap, but it is with two fingers
I created a table view and the tableViewCell is not clickable with one finger, but when I try to click the tableViewCell with two fingers the click event takes place. I don't know why this occurres. I created a custom cell in tableView.

InviteVC

```<code>import UIKit

class InvitePeopleVC: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource {

    var nameArray = ["Alwin Lazar", "Ajith Ramesh CR", "Ebrahim KK", "Vishnu Prakash"]
    var emailArray = ["alwin@xeoscript.com", "ajith@xeoscript.com", "ebrahim@xeoscript.com", "vishnu@xeoscript.com"]

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var doneImg: UIImageView!
    @IBOutlet weak var nameTextFld: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        delegates()
        uiModifications()
        gestureRecognizers()
    }

    func delegates() {
        tableView.dataSource = self
        tableView.delegate = self
        nameTextFld.delegate = self
    }

    func uiModifications() {
        nameTextFld.attributedPlaceholder = NSAttributedString(string: "Name or email address", attributes: [NSForegroundColorAttributeName: UIColor.white])
    }

    func gestureRecognizers() {
        self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(InvitePeopleVC.dismissKeyboard)))
        self.doneImg.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(InvitePeopleVC.doneImgPressed)))
    }

    func dismissKeyboard() {
        nameTextFld.resignFirstResponder()
    }

    func doneImgPressed() {
        print("done Image tapped")

    }

    func inviteBtnPressed() {
        print("invite button pressed")
    }

    // UITextFieldDelegate method
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {

        if textField == self.nameTextFld {

            self.nameTextFld.resignFirstResponder()

        }
        return true

    }

    // TableView DataSource methods
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return nameArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "InviteCell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! InviteCell

        cell.nameLbl.text = nameArray[indexPath.row]
        cell.emailLbl.text = emailArray[indexPath.row]

        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }

    // TableView Delegate methods
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("selected row is \(indexPath.row)")
    }

    @IBAction func backBtnPressed(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
}
</code>```

#InviteCell

```<code>import UIKit

class InviteCell: UITableViewCell {

    @IBOutlet weak var nameLbl: UILabel!
    @IBOutlet weak var emailLbl: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()

    }

}
</code>```

UIViewController Images

TableView Attributes Inspector

InviteCell Atribute Inspector

In the code above, I'm trying to select a cell with one finger, but the selection does not happen.

Thanks in advance...

答:
The Tap gesture you have added in the code is causing the issue. Tapgesture recogniser is listening to the user tap actions in the view. The cell select listner is being blocked by the added Tap gesture.

As @Fahim said, if you remove the tap gesture from your code, then cell selection will work smoothly.

Body:
I created a table view and the tableViewCell is not clickable with one finger, but when I try to click the tableViewCell with two fingers the click event takes place. I don't know why this occurres. I created a custom cell in tableView.

InviteVC

import UIKit

class InvitePeopleVC: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource {

    var nameArray = ["Alwin Lazar", "Ajith Ramesh CR", "Ebrahim KK", "Vishnu Prakash"]
    var emailArray = ["alwin@xeoscript.com", "ajith@xeoscript.com", "ebrahim@xeoscript.com", "vishnu@xeoscript.com"]

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var doneImg: UIImageView!
    @IBOutlet weak var nameTextFld: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        delegates()
        uiModifications()
        gestureRecognizers()
    }

    func delegates() {
        tableView.dataSource = self
        tableView.delegate = self
        nameTextFld.delegate = self
    }

    func uiModifications() {
        nameTextFld.attributedPlaceholder = NSAttributedString(string: "Name or email address", attributes: [NSForegroundColorAttributeName: UIColor.white])
    }

    func gestureRecognizers() {
        self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(InvitePeopleVC.dismissKeyboard)))
        self.doneImg.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(InvitePeopleVC.doneImgPressed)))
    }

    func dismissKeyboard() {
        nameTextFld.resignFirstResponder()
    }

    func doneImgPressed() {
        print("done Image tapped")

    }

    func inviteBtnPressed() {
        print("invite button pressed")
    }

    // UITextFieldDelegate method
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {

        if textField == self.nameTextFld {

            self.nameTextFld.resignFirstResponder()

        }
        return true

    }

    // TableView DataSource methods
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return nameArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "InviteCell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! InviteCell

        cell.nameLbl.text = nameArray[indexPath.row]
        cell.emailLbl.text = emailArray[indexPath.row]

        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }

    // TableView Delegate methods
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("selected row is \(indexPath.row)")
    }

    @IBAction func backBtnPressed(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
}

#InviteCell

import UIKit

class InviteCell: UITableViewCell {

    @IBOutlet weak var nameLbl: UILabel!
    @IBOutlet weak var emailLbl: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()

    }

}

UIViewController Images

TableView Attributes Inspector

InviteCell Atribute Inspector

In the code above, I'm trying to select a cell with one finger, but the selection does not happen.

Thanks in advance...


问:
How to remove all special characters in Linux text

How to remove the special characters shown as blue color in the picture 1 like: ^M, ^A, ^@, ^[. In my understanding, ^M is a windows newline character, I can use sed -i '/^M//g' to remove it, but it doesn't work to remove others. The command dos2unix doesn't work, neither. Are there exist any ways that I can use to remove them both?

答:
Try this inside vi or vim:

[in ESC mode] type: :%s/^M//g

or:

```<code>sed -e "s/^M//" filename > newfilename
</code>```

Important: To enter ^M, type CTRL-V, then CTRL-M

Body:
Try this inside vi or vim:

[in ESC mode] type: :%s/^M//g

or:

sed -e "s/^M//" filename > newfilename

Important: To enter ^M, type CTRL-V, then CTRL-M


问:
Pycharm Error - No module named MySQLdb
I have installed MySqldb as shown below:-

```<code>jab-MacBook-Pro-4:silkroute deb$ pip install MySQL-python
Collecting MySQL-python
Installing collected packages: MySQL-python
Successfully installed MySQL-python-1.2.5
</code>```

But still I am getting the error:-

```<code>python --version
Python 2.7.11
</code>```

I am using version 2.7.10 in PyCharm

I have also installed MySQLDB as shown below:-

```<code>jab-MacBook-Pro-4:silkroute deb$ pip2.7 install MySQL-python
Requirement already satisfied: MySQL-python in /usr/local/lib/python2.7/site-packages
</code>```

Can someone let me know how can I get rid of this error?

答:
You may have multiple Python versions installed.

Use pip2.7 to see if this installs on the right python version.

Check this post: pip: dealing with multiple Python versions?

Title: Pycharm Error - No module named MySQLdb

Body:
I have installed MySqldb as shown below:-

jab-MacBook-Pro-4:silkroute deb$ pip install MySQL-python
Collecting MySQL-python
Installing collected packages: MySQL-python
Successfully installed MySQL-python-1.2.5

But still I am getting the error:-

python --version
Python 2.7.11

I am using version 2.7.10 in PyCharm

I have also installed MySQLDB as shown below:-

jab-MacBook-Pro-4:silkroute deb$ pip2.7 install MySQL-python
Requirement already satisfied: MySQL-python in /usr/local/lib/python2.7/site-packages

Can someone let me know how can I get rid of this error?


问:
Android Firebase Analytics not working correcty
I want to track which button is clicked using Google Firebase Analytics.

Code I tried:

```<code>public class MainActivity extends AppCompatActivity {
private FirebaseAnalytics mFirebaseAnalytics;
  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
  }

  public void onClick(View view) {
    int btn_id = view.getId();
    if (view.getId() == R.id.Btn1) {
        //Some content
    } else if (view.getId() == R.id.Btn2 {
        //Some content
    } else if (view.getId() == R.id.Btn3) {
        //Some content
    }
        Bundle params = new Bundle();
        params.putString(FirebaseAnalytics.Param.ITEM_ID, String.valueOf(btn_id));
        mFirebaseAnalytics.logEvent("homebtn_event", params);
  }
}
</code>```

The above code tracks clicks on buttons but does not returns btn_id or which button is clicked in Firebase Analytics data

答:
Firebase analytics event will be visible on Dashboard after 24 hours

But

You can enable verbose logging to monitor logging of events by the SDK
  to help verify that events are being logged properly. This includes
  both automatically and manually logged events.

You can enable verbose logging with a series of adb commands:

```<code>adb shell setprop log.tag.FA VERBOSE
adb shell setprop log.tag.FA-SVC VERBOSE
adb logcat -v time -s FA FA-SVC
</code>```

This command displays your events in the Android Studio logcat,
  helping you immediately verify that events are being sent.

Reference

Body:
I want to track which button is clicked using Google Firebase Analytics.

Code I tried:

public class MainActivity extends AppCompatActivity {
private FirebaseAnalytics mFirebaseAnalytics;
  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
  }

  public void onClick(View view) {
    int btn_id = view.getId();
    if (view.getId() == R.id.Btn1) {
        //Some content
    } else if (view.getId() == R.id.Btn2 {
        //Some content
    } else if (view.getId() == R.id.Btn3) {
        //Some content
    }
        Bundle params = new Bundle();
        params.putString(FirebaseAnalytics.Param.ITEM_ID, String.valueOf(btn_id));
        mFirebaseAnalytics.logEvent("homebtn_event", params);
  }
}

The above code tracks clicks on buttons but does not returns btn_id or which button is clicked in Firebase Analytics data

Body:
Firebase analytics event will be visible on Dashboard after 24 hours

But

You can enable verbose logging to monitor logging of events by the SDK
  to help verify that events are being logged properly. This includes
  both automatically and manually logged events.

You can enable verbose logging with a series of adb commands:

adb shell setprop log.tag.FA VERBOSE
adb shell setprop log.tag.FA-SVC VERBOSE
adb logcat -v time -s FA FA-SVC

This command displays your events in the Android Studio logcat,
  helping you immediately verify that events are being sent.

Reference


问:
compass:server not found when running `grunt server`

The problem

grunt server outputs this:

```<code>Warning: Task "compass:server" not found.
</code>```

I uploaded Gruntfile.js here: https://gist.github.com/ComFreek/7289648

That's the default file I got after creating a new Yeoman project.

Details

I am reading Building Web Apps With Yeoman And Polymer and following the described console commands to run.

My system:

Windows 8.1 Pro 64-bit

NodeJS 0.10.21

NPM 1.3.11

I've already executed these commands:

```<code>npm install -g yo
npm install generator-polymer -g

yo polymer
</code>```

grunt server told me that I had to install Ruby and Compass.

I installed Ruby from here:
http://rubyinstaller.org/

After installing, I also successfully whether Ruby has really been registered in the PATH.

I used NPM for installing Compass:

```<code>npm install grunt-contrib-compass --save-dev -g
</code>```

(I tried a local and global install of Compass. Neither of them worked.)

This is the exact output of grunt:

```<code>D:\test>grunt server
Running "server" task
Warning: Task "compass:server" not found. Use --force to continue.

Aborted due to warnings.

Elapsed time
server  4ms
Total   4ms
</code>```

It works now...

Unfortunately, I still don't know the exact cause. I went through all of my instructions above again, and it just worked out of the box.

In any case, I recommend updating all packages. My version numbers are (last edited: 02.02.14):

```<code>[NodeJS v.0.10.24]
[NPM 1.3.21]
[grunt-cli v0.1.11]
[grunt v0.4.2]
</code>```

答:
I had the same problem but it was fixed after I've installed Ruby's compass:

```<code># gem install compass
</code>```

Hint: gem is the package manager for Ruby, so Ruby should be existing  in the system.

For Redhat's based linux systems, you can use the following to install Ruby and gem:

```<code># yum install gcc ruby-devel rubygems
# gem install compass
</code>```

For Debian's based linux systems, you can check this

Body:
The problem

grunt server outputs this:

Warning: Task "compass:server" not found.

I uploaded Gruntfile.js here: https://gist.github.com/ComFreek/7289648

That's the default file I got after creating a new Yeoman project.

Details

I am reading Building Web Apps With Yeoman And Polymer and following the described console commands to run.

My system:

Windows 8.1 Pro 64-bit

NodeJS 0.10.21

NPM 1.3.11

I've already executed these commands:

npm install -g yo
npm install generator-polymer -g

yo polymer

grunt server told me that I had to install Ruby and Compass.

I installed Ruby from here:
http://rubyinstaller.org/

After installing, I also successfully whether Ruby has really been registered in the PATH.

I used NPM for installing Compass:

npm install grunt-contrib-compass --save-dev -g

(I tried a local and global install of Compass. Neither of them worked.)

This is the exact output of grunt:

D:\test>grunt server
Running "server" task
Warning: Task "compass:server" not found. Use --force to continue.

Aborted due to warnings.

Elapsed time
server  4ms
Total   4ms

It works now...

Unfortunately, I still don't know the exact cause. I went through all of my instructions above again, and it just worked out of the box.

In any case, I recommend updating all packages. My version numbers are (last edited: 02.02.14):

[NodeJS v.0.10.24]
[NPM 1.3.21]
[grunt-cli v0.1.11]
[grunt v0.4.2]

Body:
I had the same problem but it was fixed after I've installed Ruby's compass:

# gem install compass

Hint: gem is the package manager for Ruby, so Ruby should be existing  in the system.

For Redhat's based linux systems, you can use the following to install Ruby and gem:

# yum install gcc ruby-devel rubygems
# gem install compass

For Debian's based linux systems, you can check this


问:
Getting a blank file when accessing JIRA on SSL
I'm stuck on a SSL problem with JIRA. I've followed the instructions to setup Jira+SSL on Ubuntu but am getting a blank file when accessing http://domain.com:8443/

In the blank file I can see these

1503 0300 0202 0a

I'm not sure what I can do the catalina logs don't report any problems.

答:
How to add SSL Certificate to secure JIRA installation:

Assumptions:

JIRA is running on port 8080 or some other open port, on Linux Machine

JIRA is using tomcat server and is indepedent from Apache HTTP Server

You have already a valid CA signed root certificate and certificate chain, after generating CSR and key.

No reverse proxy setting is enabled in Apache HTTP Server configuration

You will see little bit similar configuration in /conf/server.xml

```<code><Service name="Catalina">
    <!-- HTTP Connector with values for scheme, proxyName and proxyPort -->
    <Connector port="8080"
               acceptCount="100"
               scheme="http"
               maxThreads="150"
               minSpareThreads="25"
               connectionTimeout="20000"
               enableLookups="false"
               maxHttpHeaderSize="8192"
               protocol="HTTP/1.1"
               useBodyEncodingForURI="true"
               disableUploadTimeout="true"/>
    <Engine name="Catalina" defaultHost="localhost">
        <Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true">
            <Context path="" docBase="${catalina.home}/atlassian-jira" reloadable="false" useHttpOnly="true">
                <Resource name="UserTransaction" auth="Container" type="javax.transaction.UserTransaction"
                          factory="org.objectweb.jotm.UserTransactionFactory" jotm.timeout="60"/>
                <Manager pathname=""/>
            </Context>

        </Host>

        <Valve className="org.apache.catalina.valves.AccessLogValve"
               pattern="%a %{jira.request.id}r %{jira.request.username}r %t "%m %U%q %H" %s %b %D "%{Referer}i" "%{User-Agent}i" "%{jira.request.assession.id}r""/>

    </Engine>
</Service>
</code>```

To Add SSL certificate you first need to include your key and root certificate in a single entity using keytool java executable. This is present in /bin/ folder.

The main thing to note here if you use keytool to import the root certificate or chain certificate without key, the browser may give SSL overlap or some different SSL related error. So the first requirement is to
import the certificates with domain key.

Another thing we need to convert key and root .crt files into pkcs12 compatible so that java keytool can read it in its own format. Otherwise you will again face SSL errors on browsers.

Now combine key and certificate in pkcs format using openssl on you Linux Machine, say you are in /bin/ folder.

root@mail bin]# openssl pkcs12 -export -in /opt/certificate_store/root.crt -inkey /home/certificate_store/domain.key -out server.p12 -name jira_alias -CAfile /home/certificate/gd_bundle.crt -caname root

Enter Export Password:

Verifying - Enter Export Password:

This command will create a file server.p12 (u can give it any name). Dont forget alias name (U can give any alias name, which is an identifier to get information about certifcate from a list, if any)

[root@mail bin]# ls

java  jjs  keytool  orbd  pack200  policytool  rmid  rmiregistry  server.p12  servertool  tnameserv  unpack200

Now use keytool to convert it to java readable

[root@mail bin]# keytool -importkeystore -deststorepass  -destkeypass  -destkeystore server.keystore -srckeystore server.p12 -srcstoretype PKCS12 -srcstorepass  -alias jira_aliased

(For symmetry, U can try same password every where, this password is required to be given in server.xml further)

Above command will create a file server.keystore using given options

[root@mail bin]# ls

java  jjs  keytool  orbd  pack200  policytool  rmid  rmiregistry  server.keystore  server.p12  servertool  tnameserv  unpack20

Now your certificate keystore is ready to secure JIRA.

Open /conf/server.xml and Add following new connector after old connector

```<code>    <!-- Standard HTTPS Connector  -->
    <Connector
            acceptCount="100"
            SSLEnabled="true"
            connectionTimeout="20000"
            disableUploadTimeout="true"
            enableLookups="false"
            maxHttpHeaderSize="8192"
            maxThreads="150"
            minSpareThreads="25"
            maxSpareThreads="75"
            port="<PORT_NUMBER_ON_WHICH_YOU_WANT_TO_RUN_JIRA_ON_SSL>"
            protocol="org.apache.coyote.http11.Http11NioProtocol"
            scheme="https"
            secure="true"
            clientAuth="false"
            keystoreType="JKS"
            keystoreFile="/opt/atlassian/jira/jre/bin/server.keystore"
            keystorePass="same password here that you had given in keytool"
            useBodyEncodingForURI="true"/>
</code>```

Comment out old HTTP connector, Save server.xml file now and restart jira. Open your jira site on specified port number like : http(s)://domain.com:, check its working or not.
Alternatively on linux console you can try following command to check if SSL working on that port.

$openssl s_client -connect localhost:

It will produce all certificate chain , if working properly otherwise will not show any certifcate and error will be thrown.

If you still want to access JIRA on both HTTP and HTTPS, open server.xml file , uncomment old HTTP connector and put a forwader from HTTP to HTTPS. say your HTTP connector is listening on 8080 and HTTPS connector is listening
on port number 9000, then your server.xml connectors should look like this.

```<code>    <!-- HTTP Connector with values for scheme, proxyName and proxyPort -->
    <!--<Connector port="8080"
               acceptCount="100"
               scheme="http"
               maxThreads="150"
               minSpareThreads="25"
               connectionTimeout="20000"
               enableLookups="false"
               maxHttpHeaderSize="8192"
               protocol="HTTP/1.1"
               useBodyEncodingForURI="true"
               redirectPort="9000"
               disableUploadTimeout="true"/>-->

    <!-- Standard HTTPS Connector  -->
    <Connector
            acceptCount="100"
            SSLEnabled="true"
            connectionTimeout="20000"
            disableUploadTimeout="true"
            enableLookups="false"
            maxHttpHeaderSize="8192"
            maxThreads="150"
            minSpareThreads="25"
            maxSpareThreads="75"
            port="9000"
            protocol="org.apache.coyote.http11.Http11NioProtocol"
            scheme="https"
            secure="true"
            clientAuth="false"
            keystoreType="JKS"
            keystoreFile="/opt/atlassian/jira/jre/bin/server.keystore"
            keystorePass="<PASSWORD_HERE>"
            useBodyEncodingForURI="true"/>
</code>```

Enjoy  SSL !!

Don't Forget to add following lines in /atlassian-jira/WEB-INF/web.xml

```<code><security-constraint>
    <web-resource-collection>
        <web-resource-name>all-except-attachments</web-resource-name>
        <url-pattern>*.jsp</url-pattern>
        <url-pattern>*.jspa</url-pattern>
        <url-pattern>/browse/*</url-pattern>
        <url-pattern>/issues/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>
</code>```

Body:
How to add SSL Certificate to secure JIRA installation:

Assumptions:

JIRA is running on port 8080 or some other open port, on Linux Machine

JIRA is using tomcat server and is indepedent from Apache HTTP Server

You have already a valid CA signed root certificate and certificate chain, after generating CSR and key.

No reverse proxy setting is enabled in Apache HTTP Server configuration

You will see little bit similar configuration in /conf/server.xml

<Service name="Catalina">
    <!-- HTTP Connector with values for scheme, proxyName and proxyPort -->
    <Connector port="8080"
               acceptCount="100"
               scheme="http"
               maxThreads="150"
               minSpareThreads="25"
               connectionTimeout="20000"
               enableLookups="false"
               maxHttpHeaderSize="8192"
               protocol="HTTP/1.1"
               useBodyEncodingForURI="true"
               disableUploadTimeout="true"/>
    <Engine name="Catalina" defaultHost="localhost">
        <Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true">
            <Context path="" docBase="${catalina.home}/atlassian-jira" reloadable="false" useHttpOnly="true">
                <Resource name="UserTransaction" auth="Container" type="javax.transaction.UserTransaction"
                          factory="org.objectweb.jotm.UserTransactionFactory" jotm.timeout="60"/>
                <Manager pathname=""/>
            </Context>

        </Host>

        <Valve className="org.apache.catalina.valves.AccessLogValve"
               pattern="%a %{jira.request.id}r %{jira.request.username}r %t &quot;%m %U%q %H&quot; %s %b %D &quot;%{Referer}i&quot; &quot;%{User-Agent}i&quot; &quot;%{jira.request.assession.id}r&quot;"/>

    </Engine>
</Service>

To Add SSL certificate you first need to include your key and root certificate in a single entity using keytool java executable. This is present in /bin/ folder.

The main thing to note here if you use keytool to import the root certificate or chain certificate without key, the browser may give SSL overlap or some different SSL related error. So the first requirement is to
import the certificates with domain key.

Another thing we need to convert key and root .crt files into pkcs12 compatible so that java keytool can read it in its own format. Otherwise you will again face SSL errors on browsers.

Now combine key and certificate in pkcs format using openssl on you Linux Machine, say you are in /bin/ folder.

root@mail bin]# openssl pkcs12 -export -in /opt/certificate_store/root.crt -inkey /home/certificate_store/domain.key -out server.p12 -name jira_alias -CAfile /home/certificate/gd_bundle.crt -caname root

Enter Export Password:

Verifying - Enter Export Password:

This command will create a file server.p12 (u can give it any name). Dont forget alias name (U can give any alias name, which is an identifier to get information about certifcate from a list, if any)

[root@mail bin]# ls

java  jjs  keytool  orbd  pack200  policytool  rmid  rmiregistry  server.p12  servertool  tnameserv  unpack200

Now use keytool to convert it to java readable

[root@mail bin]# keytool -importkeystore -deststorepass  -destkeypass  -destkeystore server.keystore -srckeystore server.p12 -srcstoretype PKCS12 -srcstorepass  -alias jira_aliased

(For symmetry, U can try same password every where, this password is required to be given in server.xml further)

Above command will create a file server.keystore using given options

[root@mail bin]# ls

java  jjs  keytool  orbd  pack200  policytool  rmid  rmiregistry  server.keystore  server.p12  servertool  tnameserv  unpack20

Now your certificate keystore is ready to secure JIRA.

Open /conf/server.xml and Add following new connector after old connector

    <!-- Standard HTTPS Connector  -->
    <Connector
            acceptCount="100"
            SSLEnabled="true"
            connectionTimeout="20000"
            disableUploadTimeout="true"
            enableLookups="false"
            maxHttpHeaderSize="8192"
            maxThreads="150"
            minSpareThreads="25"
            maxSpareThreads="75"
            port="<PORT_NUMBER_ON_WHICH_YOU_WANT_TO_RUN_JIRA_ON_SSL>"
            protocol="org.apache.coyote.http11.Http11NioProtocol"
            scheme="https"
            secure="true"
            clientAuth="false"
            keystoreType="JKS"
            keystoreFile="/opt/atlassian/jira/jre/bin/server.keystore"
            keystorePass="same password here that you had given in keytool"
            useBodyEncodingForURI="true"/>

Comment out old HTTP connector, Save server.xml file now and restart jira. Open your jira site on specified port number like : http(s)://domain.com:, check its working or not.
Alternatively on linux console you can try following command to check if SSL working on that port.

$openssl s_client -connect localhost:

It will produce all certificate chain , if working properly otherwise will not show any certifcate and error will be thrown.

If you still want to access JIRA on both HTTP and HTTPS, open server.xml file , uncomment old HTTP connector and put a forwader from HTTP to HTTPS. say your HTTP connector is listening on 8080 and HTTPS connector is listening
on port number 9000, then your server.xml connectors should look like this.

    <!-- HTTP Connector with values for scheme, proxyName and proxyPort -->
    <!--<Connector port="8080"
               acceptCount="100"
               scheme="http"
               maxThreads="150"
               minSpareThreads="25"
               connectionTimeout="20000"
               enableLookups="false"
               maxHttpHeaderSize="8192"
               protocol="HTTP/1.1"
               useBodyEncodingForURI="true"
               redirectPort="9000"
               disableUploadTimeout="true"/>-->

    <!-- Standard HTTPS Connector  -->
    <Connector
            acceptCount="100"
            SSLEnabled="true"
            connectionTimeout="20000"
            disableUploadTimeout="true"
            enableLookups="false"
            maxHttpHeaderSize="8192"
            maxThreads="150"
            minSpareThreads="25"
            maxSpareThreads="75"
            port="9000"
            protocol="org.apache.coyote.http11.Http11NioProtocol"
            scheme="https"
            secure="true"
            clientAuth="false"
            keystoreType="JKS"
            keystoreFile="/opt/atlassian/jira/jre/bin/server.keystore"
            keystorePass="<PASSWORD_HERE>"
            useBodyEncodingForURI="true"/>

Enjoy  SSL !!

Don't Forget to add following lines in /atlassian-jira/WEB-INF/web.xml

<security-constraint>
    <web-resource-collection>
        <web-resource-name>all-except-attachments</web-resource-name>
        <url-pattern>*.jsp</url-pattern>
        <url-pattern>*.jspa</url-pattern>
        <url-pattern>/browse/*</url-pattern>
        <url-pattern>/issues/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>


问:
svn asking to upgrade working copy after updating to MacOS Sierra
So I upgraded to MacOS Sierra and now whenever I try to do anything in my working copy I get the error that it

"is too old (format 29) to work with client version '1.9.4 (r1740329)' (expects format 31). You need to upgrade the working copy first."

When I run svn upgrade, as it suggests it says
"Can't open file /.svn/entries: No such file or directory"

Any suggestions will be greatly appreciated!

答:
Open Terminal

go to error folder. ex : cd svn/project/game

command write only "svn upgrade"


问:
Slow query over large collection
I'm working on an audit log which saves sessions in RavenDB. Initially, the website for querying the audit logs was responsive enough but as the amount of logged data has increased, the search page became unusable (it times out before returning using default settings - regardless of the query used). Right now we have about 45mil sessions in the table that gets queried but steady state is expected to be around 150mil documents.

The problem is that with this much live data, playing around to test things has become impractical. I hope some one can give me some ideas what would be the most productive areas to investigate.

The index looks like this:

```<code>public AuditSessions_WithSearchParameters()
{
    Map = sessions => from session in sessions
                      select new Result
                      {
                          ApplicationName = session.ApplicationName,
                          SessionId = session.SessionId,
                          StartedUtc = session.StartedUtc,
                          User_Cpr = session.User.Cpr,
                          User_CprPersonId = session.User.CprPersonId,
                          User_ApplicationUserId = session.User.ApplicationUserId
                      };

    Store(r => r.ApplicationName, FieldStorage.Yes);
    Store(r => r.StartedUtc, FieldStorage.Yes);
    Store(r => r.User_Cpr, FieldStorage.Yes);
    Store(r => r.User_CprPersonId, FieldStorage.Yes);
    Store(r => r.User_ApplicationUserId, FieldStorage.Yes);
}
</code>```

The essense of the query is this bit:

```<code>// Query input paramters
var fromDateUtc = fromDate.ToUniversalTime();
var toDateUtc = toDate.ToUniversalTime();

sessionQuery = sessionQuery
        .Where(s =>
            s.ApplicationName == applicationName &&
            s.StartedUtc >= fromDateUtc &&
            s.StartedUtc <= toDateUtc
        );

var totalItems = Count(sessionQuery);
var sessionData =
    sessionQuery
    .OrderByDescending(s => s.StartedUtc)
    .Skip((page - 1) * PageSize)
    .Take(PageSize)
    .ProjectFromIndexFieldsInto<AuditSessions_WithSearchParameters.ResultWithAuditSession>()
    .Select(s => new
    {
        s.SessionId,
        s.SessionGroupId,
        s.ApplicationName,
        s.StartedUtc,
        s.Type,
        s.ResourceUri,
        s.User,
        s.ImpersonatingUser
    })
    .ToList();
</code>```

First, to determine the number of pages of results, I count the number of results in my query using this method:

```<code>private static int Count<T>(IRavenQueryable<T> results)
{
    RavenQueryStatistics stats;
    results.Statistics(out stats).Take(0).ToArray();
    return stats.TotalResults;
}
</code>```

This turns out to be very expensive in itself, so optimizations are relevant both here and in the rest of the query.

The query time is not related to the amount of result items in any relevant way. If I use a different value for the applicationName parameter than any of the results, it is just as slow.

One area of improvement could be to use sequential IDs for the sessions. For reasons not relevant to this post, I found it most practical to use guid based ids. I'm not sure if I can easily change IDs of the existing values (with this much data) and I would prefer not to drop the data (but might if the expected impact is large enough). I understand that sequential ids result in better behaving b-trees for the indexes, but I have no idea how significant the impact is.

Another approach could be to include a timestamp in the id and query for documents with ids starting with the string matching enough of the time to filter the result. An example id could be AuditSessions/2017-12-31-24-31-42/bc835d6c-2fba-4591-af92-7aab96339d84. This also requires me to update or drop all the existing data. This of course also has the benefits of mostly sequential ids.

A third approach could be to move old data into a different collection over time, in recognition of the fact that you would most often look at the most recent data. This requires a background job and support for querying across collection time boundaries. It also has the issue that the collection with the old sessions is still slow if you need to access it.

I'm hoping there is something simpler than these solutions, such as modifying the query or the indexed fields in a way that avoids a lot of work.

答:
At a glance, it is probably related to the range query on the StartedUtc.
I'm assuming that you are using exact numbers, so you have a LOT of distinct values there.
If you can, you can dramatically reduce the cost by changing the index to index on a second / minute granularity (which is usually what you are querying on), and then use Ticks, which allow us to use numeric range query.

```<code>                      StartedUtcTicks = new Datetime(session.StartedUtc.Year, session.StartedUtc.Month, session.StartedUtc.Day, session.StartedUtc.Hour, session.StartedUtc.Minute, session.StartedUtc.Second).Ticks,
</code>```

And then query by the date ticks.

Title: Slow query over large collection

Body:
I'm working on an audit log which saves sessions in RavenDB. Initially, the website for querying the audit logs was responsive enough but as the amount of logged data has increased, the search page became unusable (it times out before returning using default settings - regardless of the query used). Right now we have about 45mil sessions in the table that gets queried but steady state is expected to be around 150mil documents.

The problem is that with this much live data, playing around to test things has become impractical. I hope some one can give me some ideas what would be the most productive areas to investigate.

The index looks like this:

public AuditSessions_WithSearchParameters()
{
    Map = sessions => from session in sessions
                      select new Result
                      {
                          ApplicationName = session.ApplicationName,
                          SessionId = session.SessionId,
                          StartedUtc = session.StartedUtc,
                          User_Cpr = session.User.Cpr,
                          User_CprPersonId = session.User.CprPersonId,
                          User_ApplicationUserId = session.User.ApplicationUserId
                      };

    Store(r => r.ApplicationName, FieldStorage.Yes);
    Store(r => r.StartedUtc, FieldStorage.Yes);
    Store(r => r.User_Cpr, FieldStorage.Yes);
    Store(r => r.User_CprPersonId, FieldStorage.Yes);
    Store(r => r.User_ApplicationUserId, FieldStorage.Yes);
}

The essense of the query is this bit:

// Query input paramters
var fromDateUtc = fromDate.ToUniversalTime();
var toDateUtc = toDate.ToUniversalTime();

sessionQuery = sessionQuery
        .Where(s =>
            s.ApplicationName == applicationName &&
            s.StartedUtc >= fromDateUtc &&
            s.StartedUtc <= toDateUtc
        );

var totalItems = Count(sessionQuery);
var sessionData =
    sessionQuery
    .OrderByDescending(s => s.StartedUtc)
    .Skip((page - 1) * PageSize)
    .Take(PageSize)
    .ProjectFromIndexFieldsInto<AuditSessions_WithSearchParameters.ResultWithAuditSession>()
    .Select(s => new
    {
        s.SessionId,
        s.SessionGroupId,
        s.ApplicationName,
        s.StartedUtc,
        s.Type,
        s.ResourceUri,
        s.User,
        s.ImpersonatingUser
    })
    .ToList();

First, to determine the number of pages of results, I count the number of results in my query using this method:

private static int Count<T>(IRavenQueryable<T> results)
{
    RavenQueryStatistics stats;
    results.Statistics(out stats).Take(0).ToArray();
    return stats.TotalResults;
}

This turns out to be very expensive in itself, so optimizations are relevant both here and in the rest of the query.

The query time is not related to the amount of result items in any relevant way. If I use a different value for the applicationName parameter than any of the results, it is just as slow.

One area of improvement could be to use sequential IDs for the sessions. For reasons not relevant to this post, I found it most practical to use guid based ids. I'm not sure if I can easily change IDs of the existing values (with this much data) and I would prefer not to drop the data (but might if the expected impact is large enough). I understand that sequential ids result in better behaving b-trees for the indexes, but I have no idea how significant the impact is.

Another approach could be to include a timestamp in the id and query for documents with ids starting with the string matching enough of the time to filter the result. An example id could be AuditSessions/2017-12-31-24-31-42/bc835d6c-2fba-4591-af92-7aab96339d84. This also requires me to update or drop all the existing data. This of course also has the benefits of mostly sequential ids.

A third approach could be to move old data into a different collection over time, in recognition of the fact that you would most often look at the most recent data. This requires a background job and support for querying across collection time boundaries. It also has the issue that the collection with the old sessions is still slow if you need to access it.

I'm hoping there is something simpler than these solutions, such as modifying the query or the indexed fields in a way that avoids a lot of work.

Body:
At a glance, it is probably related to the range query on the StartedUtc.
I'm assuming that you are using exact numbers, so you have a LOT of distinct values there.
If you can, you can dramatically reduce the cost by changing the index to index on a second / minute granularity (which is usually what you are querying on), and then use Ticks, which allow us to use numeric range query.

                      StartedUtcTicks = new Datetime(session.StartedUtc.Year, session.StartedUtc.Month, session.StartedUtc.Day, session.StartedUtc.Hour, session.StartedUtc.Minute, session.StartedUtc.Second).Ticks,

And then query by the date ticks.


问:
response.json is not a function. AngularFire
So I'm building an app using AngularFire2, This is in a service but when the function search gets ran it calls the error response.json is not a function. Firebase returns an observable and I'm not sure why this snippet wouldn't work.</p>

```<code>import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Article } from '../models/index';

  search(term: string): Observable<Article[]> {
    return this.af.database
      .list('/articles/', {
        query: {
          orderByChild: "title",
          equalTo: term,
          limitToFirst: 10
        }
      })
      .map(response => response.json().data as Article[]);
  }
</code>```

答:
AngularFire2's list observable does not emit a HTTP response object. It emits an array of anonymous objects that represent the items that match the query.

If Article is an interface, you can remove the map operator and cast the observable itself:

import { Observable } from 'rxjs/Observable';
import { Article } from '../models/index';

search(term: string): Observable
 {
  return this.af.database
    .list('/articles/', {
      query: {
        orderByChild: 'title',
        equalTo: term,
        limitToFirst: 10
      }
    }) as Observable
;
}
```

<p>If <code>Article</code> is a class, you should use the <code>map</code> operator to create actual <code>Article</code> instances (using a suitable constructor):</p>

<pre class="lang-ts prettyprint-override"><code>import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Article } from '../models/index';

search(term: string): Observable<Article[]> {
  return this.af.database
    .list('/articles/', {
      query: {
        orderByChild: 'title',
        equalTo: term,
        limitToFirst: 10
      }
    })
    .map(list => list.map(item => new Article(item));
}
</code>```

Body:
So I'm building an app using AngularFire2, This is in a service but when the function search gets ran it calls the error response.json is not a function. Firebase returns an observable and I'm not sure why this snippet wouldn't work.

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Article } from '../models/index';

  search(term: string): Observable
 {
    return this.af.database
      .list('/articles/', {
        query: {
          orderByChild: "title",
          equalTo: term,
          limitToFirst: 10
        }
      })
      .map(response => response.json().data as Article[]);
  }

Body:
AngularFire2's list observable does not emit a HTTP response object. It emits an array of anonymous objects that represent the items that match the query.

If Article is an interface, you can remove the map operator and cast the observable itself:

import { Observable } from 'rxjs/Observable';
import { Article } from '../models/index';

search(term: string): Observable<Article[]> {
  return this.af.database
    .list('/articles/', {
      query: {
        orderByChild: 'title',
        equalTo: term,
        limitToFirst: 10
      }
    }) as Observable<Article[]>;
}

If Article is a class, you should use the map operator to create actual Article instances (using a suitable constructor):

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Article } from '../models/index';

search(term: string): Observable<Article[]> {
  return this.af.database
    .list('/articles/', {
      query: {
        orderByChild: 'title',
        equalTo: term,
        limitToFirst: 10
      }
    })
    .map(list => list.map(item => new Article(item));
}


问:
Create groupings using GroupBY
I have a list of objects. I want to split this list into a list of objects based on specific property. Any object whose that specific property's value is some value should end up in one list and the rest in the other. I want to use one LINQ query that can achieve that.

Some pseudo code below:

```<code>class A {
   string X {get; set;}
}

var list = listOfAs;
List<A> listOfAWithXEqualAA;
List<A> listOfAWithXNotEqualAA;

var query = one LINQ query to populate above declared lists.
</code>```

Please suggest me such a query.

答:
```<code>var groups = listOfAs.Select(a=>new {a, IsX = a.X == "AA"}).GroupBy(arg=>arg.IsX);

List<A> listOfAWithXEqualAA  = groups.Where (g=>g.Key)
                                     .SelectMany(g=>g.Select(o=>o.a).ToList();
List<A> listOfAWithXNotEqualAA = groups.Where (g=>!g.Key)
                                       .SelectMany(g=>g.Select(o=>o.a).ToList();
</code>```

This will give you two IGrouping with the relavent info.

Otherwise, you can create a list, and then use except to get the other list:

```<code>List<A> listOfAWithXEqualAA  = listofAs.Where (a=>a.X=="AA").ToList();
List<A> listOfAWithXNotEqualAA = listofAs.Except(listOfAWithXEqualAA);
</code>```

Title: Create groupings using GroupBY

Body:
I have a list of objects. I want to split this list into a list of objects based on specific property. Any object whose that specific property's value is some value should end up in one list and the rest in the other. I want to use one LINQ query that can achieve that.

Some pseudo code below:

class A {
   string X {get; set;}
}

var list = listOfAs;
List listOfAWithXEqualAA;
List listOfAWithXNotEqualAA;

var query = one LINQ query to populate above declared lists.

Please suggest me such a query.

Body:
var groups = listOfAs.Select(a=>new {a, IsX = a.X == "AA"}).GroupBy(arg=>arg.IsX);

List<A> listOfAWithXEqualAA  = groups.Where (g=>g.Key)
                                     .SelectMany(g=>g.Select(o=>o.a).ToList();
List<A> listOfAWithXNotEqualAA = groups.Where (g=>!g.Key)
                                       .SelectMany(g=>g.Select(o=>o.a).ToList();

This will give you two IGrouping with the relavent info.

Otherwise, you can create a list, and then use except to get the other list:

List<A> listOfAWithXEqualAA  = listofAs.Where (a=>a.X=="AA").ToList();
List<A> listOfAWithXNotEqualAA = listofAs.Except(listOfAWithXEqualAA);


问:
How to change the database for the meteor users collection?
I Basically have this, which is working fine:

```<code>Ideas = new Mongo.Collection('ideas', {_driver: companyDb});
</code>```

CompanyDb above is defined as:

```<code>companyDbString = 'mongodb://127.0.0.1:27017/demo';
companyDb = new MongoInternals.RemoteCollectionDriver(companyDbString);
</code>```

However, how would i change the driver for the Meteor users collection. I've tried this:

```<code>Meteor.users = new Mongo.Collection('users', {_driver: companyDb});
</code>```

But it gives the expected 'Error: There is already a collection named "users"' error.

I know this sounds like a strange use case, but 'companyDb' changes as the subdomain changes in my application. So I basically need a separate mongo database per sub domain

答:
Try this

```<code>AnotherUsersCollection = new Mongo.Collection(“users”, { _driver: companyDb });
</code>```

or

```<code>var remote = 'mongoURL';
database = new MongoInternals.RemoteCollectionDriver(remote);

You can perform database operations with your database object, like so.

database.mongo.findOne('users', "selector_object")

An example might be

database.mongo.findOne('users', {emails : {$elemMatch : {address : "email_string"} } } )
</code>```

courtsey Dan crescimano
https://forums.meteor.com/t/remote-database-has-the-same-collection-name/7157/3

Body:
I Basically have this, which is working fine:

Ideas = new Mongo.Collection('ideas', {_driver: companyDb});

CompanyDb above is defined as:

companyDbString = 'mongodb://127.0.0.1:27017/demo';
companyDb = new MongoInternals.RemoteCollectionDriver(companyDbString);

However, how would i change the driver for the Meteor users collection. I've tried this:

Meteor.users = new Mongo.Collection('users', {_driver: companyDb});

But it gives the expected 'Error: There is already a collection named "users"' error.

I know this sounds like a strange use case, but 'companyDb' changes as the subdomain changes in my application. So I basically need a separate mongo database per sub domain

Body:
Try this

AnotherUsersCollection = new Mongo.Collection(“users”, { _driver: companyDb });

or

var remote = 'mongoURL';
database = new MongoInternals.RemoteCollectionDriver(remote);

You can perform database operations with your database object, like so.

database.mongo.findOne('users', "selector_object")

An example might be

database.mongo.findOne('users', {emails : {$elemMatch : {address : "email_string"} } } )

courtsey Dan crescimano
https://forums.meteor.com/t/remote-database-has-the-same-collection-name/7157/3


问:
Unable to route in ruby on rails as I encounter specific error

I'm using rails 5.0 and I get the

PostsController#index is missing a template for this request format and variant. request.formats: ["text/html"] request.variant: []

NOTE! For XHR/Ajax or API requests while trying to input my url/posts.

my routing.rb file is below:

```<code>Rails.application.routes.draw do
    get 'posts/index' => 'posts#index'
    resources: posts
end
</code>```

my posts_controller.rb looks like below:

```<code>class PostsController < ApplicationController
    def index

    end
end
</code>```

I want to know specifically what I'm doing wrong. I've just started to learning Ruby on Rails.

答: Rename the file index.html.erb.txt to index.html.erb

Body:
I'm using rails 5.0 and I get the

PostsController#index is missing a template for this request format and variant. request.formats: ["text/html"] request.variant: []

NOTE! For XHR/Ajax or API requests while trying to input my url/posts.

my routing.rb file is below:

Rails.application.routes.draw do
    get 'posts/index' => 'posts#index'
    resources: posts
end

my posts_controller.rb looks like below:

class PostsController < ApplicationController
    def index

    end
end

I want to know specifically what I'm doing wrong. I've just started to learning Ruby on Rails.


问:
print last '\n' char using print method in python
Imagine I have the following code in file test.py:

```<code>for x in range(1,11):
     print x
</code>```

This will print:

```<code>$myuser: python test.py
1
2
3
4
5
6
7
8
9
10
$myuser:
</code>```

However, I want it to print:

```<code>$myuser: python test.py
1
2
3
4
5
6
7
8
9
10

$myuser:
</code>```

Notice the last '\n' char, that is missing in the normal case. How do I get this last newline char?

答: Just put a bare print after the loop.

Body:
Imagine I have the following code in file test.py:

for x in range(1,11):
     print x

This will print:

$myuser: python test.py
1
2
3
4
5
6
7
8
9
10
$myuser:

However, I want it to print:

$myuser: python test.py
1
2
3
4
5
6
7
8
9
10

$myuser:

Notice the last '\n' char, that is missing in the normal case. How do I get this last newline char?

Body: Just put a bare print after the loop.


问:
Reference a .NET Standard 1.6 library from a .net 4.6.2 library
I have a home grown nuget package that targets netstandard1.6 published to a private feed. When I try to install it into a package that targets .NET Framework 4.6.2, nuget tells me:

You are trying to install this package into a project that targets '.NETFramework,Version=v4.6.2', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

The dependency list for the package looks like:

I'm using Visual Studio 2017, March 28 2017 release.

I thought this was the whole point of the .NET Standard library? What am I missing?

答:
The plan is that this will work with netstandard2.0 tooling, I believe - but it doesn't work at the moment due to some oddities around net46x.

There are two docs for the mappings between netstandard and .NET framework versions:

Aspirational .NET Standard 2.0 tooling

Current tooling

As you can see, in "current", only "vNext" supports netstandard1.6. You should be okay targeting a netstandard1.5 library from .NET 4.6.2 though - do you actually need your package to target netstandard1.6? (There's not a lot in 1.6 that's not in 1.5.)


问:
How much space do I need for Git vs SVN?
We are currently using Subversion as our source code repository. We are in the planning phase of converting to Git. Our Subversion repository is currently 19Gb. How does a Git repository compare to Subversion on disk space requirements? What will my 19Gb svn repository translate to in a Git repository. </p>

答:
As git keeps the whole repo on each machine, it also stores the full history and if you have added and then deleted  a large file, you will notice that actually the disk space hasn't been decreased. If you are completely sure you want to permanently delete file, you need to run special commands in git.

```<code>git filter-branch -f --index-filter 'git rm -r --cached --ignore-unmatch "filename"' --prune-empty HEAD
rm -rf .git/refs/original/ && git reflog expire --expire=now --all && git gc --aggressive --prune=now
</code>```

Today I moved one of my svn repos to git using the git svn command, which allows you to move not only current data but also history. And here is what I've got.

The current svn repo size on my pc is 1.27 GB, the newly created git repo is 3.24 GB. This is because git repo contains the whole history, the deleted files are not actually deleted in git, until you do it explicitly like I mentioned above.
If you find any problems while moving to git you may look for answers here

Body:
As git keeps the whole repo on each machine, it also stores the full history and if you have added and then deleted  a large file, you will notice that actually the disk space hasn't been decreased. If you are completely sure you want to permanently delete file, you need to run special commands in git.

git filter-branch -f --index-filter 'git rm -r --cached --ignore-unmatch "filename"' --prune-empty HEAD
rm -rf .git/refs/original/ && git reflog expire --expire=now --all && git gc --aggressive --prune=now

Today I moved one of my svn repos to git using the git svn command, which allows you to move not only current data but also history. And here is what I've got.

The current svn repo size on my pc is 1.27 GB, the newly created git repo is 3.24 GB. This is because git repo contains the whole history, the deleted files are not actually deleted in git, until you do it explicitly like I mentioned above.
If you find any problems while moving to git you may look for answers here


问:
Parent child relationship sql
how can I design my database with the following requirements below?

I have a table named "Application"

For each record on the "Application" table, one application record could be a parent of multiple application record on application table.

I am thinking to create a new table "Application relation", with fields parent_app_id and child_app_id, both referencing to application_id? can I do that?

Any help or ideas will be much appreciated

答:
As @SloanThrashe stated on his comment to be clear

```<code> CREATE TABLE Application(
    application_id int NOT NULL AUTO_INCREMENT,
    application_name varchar(50)  NOT NULL,
    fk_application_id int NULL,
    PRIMARY KEY (ID)
 );

 Insert into Application(application_id, application_name, fk_application_id)
    values (1, 'HR', null), (2, 'Timesheet',1), (3,'Leave Request', 1);
</code>```

Select Statement

```<code> Select p.application_id PID
        , p.application_name Parent_App
        , c.application_name Child_App
 From Application p
 Inner join Application c on p.application_id = c.fk_application_id
</code>```

SQL Result

```<code> PID   Parent_App   Child_App
 1     HR           Timesheet
 1     HR           Leave Request
</code>```

Title: Parent child relationship sql

Body:
As @SloanThrashe stated on his comment to be clear

 CREATE TABLE Application(
    application_id int NOT NULL AUTO_INCREMENT,
    application_name varchar(50)  NOT NULL,
    fk_application_id int NULL,
    PRIMARY KEY (ID)
 );

 Insert into Application(application_id, application_name, fk_application_id)
    values (1, 'HR', null), (2, 'Timesheet',1), (3,'Leave Request', 1);

Select Statement

 Select p.application_id PID
        , p.application_name Parent_App
        , c.application_name Child_App
 From Application p
 Inner join Application c on p.application_id = c.fk_application_id

SQL Result

 PID   Parent_App   Child_App
 1     HR           Timesheet
 1     HR           Leave Request


问:
I'm getting NoSuchElement exception error
I have shared the below code please let me know the correction

```<code>import org.openqa.selenium.By;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class MyClass {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        /*System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.get("https://www.google.com");

        WebDriverWait driverWait = new WebDriverWait(driver,50);

        driverWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='lst-ib']"))).click();
        driver.findElementByXPath("//*[@id='lst-ib']").sendKeys("Make My Trip");
        driver.findElementById("_fZl").click();
        driverWait.until(ExpectedConditions.elementToBeClickable(By.linkText("MakeMyTrip, India's No 1 Travel Site | Book Hotels, Flights, Holiday ..."))).click();
        Screenshot S1 = new Screenshot();
        S1.Takescreen();*/
        String username = null;
        String password = null;
        MyClass C1 = new MyClass();
        C1.URLs(username, password);
    }

    public void URLs  (String username, String password) throws InterruptedException
    {

        System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://google.com");
        driver.findElement(By.className("lst lst-tbb sbibps")).sendKeys("irctc");
        driver.findElement(By.id("_fZl")).click();
        Thread.sleep(10000);
        driver.findElement(By.linkText("IRCTC Next Generation eTicketing System")).click();
        username = driver.findElement(By.id("usernameId")).getTagName();
        password = driver.findElement(By.className("loginPassword")).getTagName();
        System.out.println(username);
        System.out.println(password);
    }
}
</code>```

Error :

Exception in thread "main" org.openqa.selenium.NoSuchElementException:
  Unable to find element with class name == lst lst-tbb sbibps (WARNING:
  The server did not provide any stacktrace information) Command
  duration or timeout: 10.45 seconds

答:
Please use following code, hope it works.</p>

```<code>driver.findElement(By.className("gsfi")).sendKeys("irctc");
</code>```

Body:
I have shared the below code please let me know the correction

import org.openqa.selenium.By;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class MyClass {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        /*System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.get("https://www.google.com");

        WebDriverWait driverWait = new WebDriverWait(driver,50);

        driverWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='lst-ib']"))).click();
        driver.findElementByXPath("//*[@id='lst-ib']").sendKeys("Make My Trip");
        driver.findElementById("_fZl").click();
        driverWait.until(ExpectedConditions.elementToBeClickable(By.linkText("MakeMyTrip, India's No 1 Travel Site | Book Hotels, Flights, Holiday ..."))).click();
        Screenshot S1 = new Screenshot();
        S1.Takescreen();*/
        String username = null;
        String password = null;
        MyClass C1 = new MyClass();
        C1.URLs(username, password);
    }

    public void URLs  (String username, String password) throws InterruptedException
    {

        System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://google.com");
        driver.findElement(By.className("lst lst-tbb sbibps")).sendKeys("irctc");
        driver.findElement(By.id("_fZl")).click();
        Thread.sleep(10000);
        driver.findElement(By.linkText("IRCTC Next Generation eTicketing System")).click();
        username = driver.findElement(By.id("usernameId")).getTagName();
        password = driver.findElement(By.className("loginPassword")).getTagName();
        System.out.println(username);
        System.out.println(password);
    }
}

Error :

Exception in thread "main" org.openqa.selenium.NoSuchElementException:
  Unable to find element with class name == lst lst-tbb sbibps (WARNING:
  The server did not provide any stacktrace information) Command
  duration or timeout: 10.45 seconds

Body:
Please use following code, hope it works.

driver.findElement(By.className("gsfi")).sendKeys("irctc");


问:
Why does this *ptr NOT give the actual value stored at the memory address contained in ptr variable?
Here is a basic C program about pointers:

```<code>#include <stdio.h>

int main() {
    int variable = 20;
    int *pointerToVariable;

    pointerToVariable = &variable;

    printf("Address of variable: %x\n", &variable);
    printf("Address of variable: %x\n", pointerToVariable);
    printf("Address of variable: %x\n", *pointerToVariable); // * is the DEREFERENCING OPERATOR/INDIRECTION OPERATOR in C.
                                                                //It gives the value stored at the memory address
                                                                //stored in the variable which is its operand.
    getchar();
    return 0;
}
</code>```

This produces the following output:

```<code>Address of variable: 8ffbe4
Address of variable: 8ffbe4
Address of variable: 14
</code>```

But *pointerToVariable should print 20, shouldn't it? Because * gives the actual value stored at the memory address stored in its operand, right?
What am I missing?

答:
First of all,

```<code>printf("Address of variable: %x\n", &variable);
printf("Address of variable: %x\n", pointerToVariable);
</code>```

are wrong, because you used wrong format specifier which  causes undefined behavior.

To print an address, you need to

use %p format specifier

cast the corresponding argument to (void *)

Then, for

```<code>printf("Address of variable: %x\n", *pointerToVariable);
</code>```

statement, the %x format specifier prints the hexadecimal representation of the supplied integer value, so you've got the correct output there.

Body:
Here is a basic C program about pointers:

#include <stdio.h>

int main() {
    int variable = 20;
    int *pointerToVariable;

    pointerToVariable = &variable;

    printf("Address of variable: %x\n", &variable);
    printf("Address of variable: %x\n", pointerToVariable);
    printf("Address of variable: %x\n", *pointerToVariable); // * is the DEREFERENCING OPERATOR/INDIRECTION OPERATOR in C.
                                                                //It gives the value stored at the memory address
                                                                //stored in the variable which is its operand.
    getchar();
    return 0;
}

This produces the following output:

Address of variable: 8ffbe4
Address of variable: 8ffbe4
Address of variable: 14

But *pointerToVariable should print 20, shouldn't it? Because * gives the actual value stored at the memory address stored in its operand, right?
What am I missing?

Body:
First of all,

printf("Address of variable: %x\n", &variable);
printf("Address of variable: %x\n", pointerToVariable);

are wrong, because you used wrong format specifier which  causes undefined behavior.

To print an address, you need to

use %p format specifier

cast the corresponding argument to (void *)

Then, for

printf("Address of variable: %x\n", *pointerToVariable);

statement, the %x format specifier prints the hexadecimal representation of the supplied integer value, so you've got the correct output there.


问:
Javascript slideshow that changes background img of an element
trying to make a slideshow that utilizes background-image: property. Here is what I have so far.

```<code><div id="headerContent">
        <div id="rightArrow"></div><!-- end of rightArrow-->
        <div id="leftArrow"></div><!-- end of leftArrow-->
    </div><!-- end of headerContent-->

document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-1.png) no-repeat !important');

document.getElementById("rightArrow").addEventListener("click", changeImageRight);

function changeImageRight () {
    var i = 0;

    if(i == 0) {
        document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-1.png) no-repeat !important');
        i++;
    }
    else if (i == 1)
     {
        document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-2.png) no-repeat !important');
        i++;
    }
    else if (i == 2) {
        document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-3.png) no-repeat !important');
        i++;
    }
    else {
        document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-1.png) no-repeat !important');
        i++;
    }

}
</code>```

as you can see I increment i++ to change the background image. However, as it stands this doesn't do anything, and no image is displayed. And I included the !important attribute because it's the only way I can get the placeholder img to show at the start.

答:
You just need to declare variable i globally.

like this:

```<code><html>
<head>
<script>
    //GLOBAL DECLARATION
    var i = 0;

    document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-1.png) no-repeat !important');

    document.getElementById("rightArrow").addEventListener("click", changeImageRight);

    function changeImageRight () {

        if(i == 0) {
            document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-1.png) no-repeat !important');
            i++;
        }
        else if (i == 1)
         {
            document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-2.png) no-repeat !important');
            i++;
        }
        else if (i == 2) {
            document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-3.png) no-repeat !important');
            i++;
        }
        else {
            document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-1.png) no-repeat !important');
            i++;
        }

    }
</script>
</head>
<body>
    <div id="headerContent">
            <div id="rightArrow"></div><!-- end of rightArrow-->
            <div id="leftArrow"></div><!-- end of leftArrow-->
    </div><!-- end of headerContent-->
</body>
</html>
</code>```

I used used internal JavaScript. You can place this JavaScript in your external JS file if you have.

Body:
trying to make a slideshow that utilizes background-image: property. Here is what I have so far.

document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-1.png) no-repeat !important');

document.getElementById("rightArrow").addEventListener("click", changeImageRight);

function changeImageRight () {
    var i = 0;

    if(i == 0) {
        document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-1.png) no-repeat !important');
        i++;
    }
    else if (i == 1)
     {
        document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-2.png) no-repeat !important');
        i++;
    }
    else if (i == 2) {
        document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-3.png) no-repeat !important');
        i++;
    }
    else {
        document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-1.png) no-repeat !important');
        i++;
    }

}

as you can see I increment i++ to change the background image. However, as it stands this doesn't do anything, and no image is displayed. And I included the !important attribute because it's the only way I can get the placeholder img to show at the start.

Body:
You just need to declare variable i globally.

like this:

<html>
<head>
<script>
    //GLOBAL DECLARATION
    var i = 0;

    document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-1.png) no-repeat !important');

    document.getElementById("rightArrow").addEventListener("click", changeImageRight);

    function changeImageRight () {

        if(i == 0) {
            document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-1.png) no-repeat !important');
            i++;
        }
        else if (i == 1)
         {
            document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-2.png) no-repeat !important');
            i++;
        }
        else if (i == 2) {
            document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-3.png) no-repeat !important');
            i++;
        }
        else {
            document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-1.png) no-repeat !important');
            i++;
        }

    }
</script>
</head>
<body>
    <div id="headerContent">
            <div id="rightArrow"></div><!-- end of rightArrow-->
            <div id="leftArrow"></div><!-- end of leftArrow-->
    </div><!-- end of headerContent-->
</body>
</html>

I used used internal JavaScript. You can place this JavaScript in your external JS file if you have.


问:
Route to different services based on URL template
I'm working on Backward Compatible project. In which, a WCF service supports OData v1-v3. I'm building ASP .NET Web API which support OData v4.

I have to call them as shows here:

http://localhost:17505/api/v4/Products should call ASP .NET Web API service.
http://localhost:17505/api/v3/Products should call WCF service

Where should the routing take place?

答:
I found and implemented the answer finally. It seems http.sys handles everything we need. Only the routing template should differ.

Had initiateApis method which calls Start methods of both WebAPI and WCF classes with parameter as the uri.

In WebAPI class - WebApi.cs

```<code>WebApp.Start<WebApi>(uri);
</code>```

In WCF class - WcfService.cs

```<code>_serviceHost = new DataServiceHost(typeof(WcfService), new Uri[0]);
_serviceHost.AddServiceEndpoint(typeof(IRequestHandler), httpBinding, uri);
</code>```

So whenever passing the url,

```<code>WebApi.Start("http://localhost:17505/api/v4/");
WcfService.Start("http://localhost:17505/api/v3/");
</code>```

Happy Coding :)

Body:
I found and implemented the answer finally. It seems http.sys handles everything we need. Only the routing template should differ.

Had initiateApis method which calls Start methods of both WebAPI and WCF classes with parameter as the uri.

In WebAPI class - WebApi.cs

WebApp.Start<WebApi>(uri);

In WCF class - WcfService.cs

_serviceHost = new DataServiceHost(typeof(WcfService), new Uri[0]);
_serviceHost.AddServiceEndpoint(typeof(IRequestHandler), httpBinding, uri);

So whenever passing the url,

WebApi.Start("http://localhost:17505/api/v4/");
WcfService.Start("http://localhost:17505/api/v3/");

Happy Coding :)


问:
How to save Signup form data in database(mysql) using reactjs and nodejs?
I have made signup form using Reactjs and want to be save emailid, password, name, address in my database(mysql) who user enter at time of signup.

I have made connection using mysql & working fine but unable to store data of signup form.

```<code>var express    = require("express");
var mysql      = require('mysql');
var connection = mysql.createConnection({
host     : 'localhost',
user     : 'root',
password : 'root',
database : 'myform'
});

var app = express();

connection.connect(function(err){
if(!err) {
    console.log("Database connection successful !!!");
} else {
  console.log("Database connection failure !!!");
}
});
app.listen(8080);
console.log('App listening at port:8080');
</code>```

答:
Try following

Nodejs

```<code>      var mysql = require('mysql');

      var connection = mysql.createConnection({
        host: 'cccc.net',
        user: 'xxxxx_usr',
        password: 'xxxxxxx',
        database: 'name of your database goes here …'
      });

     // api here
     app.post('/addUser', function(req, res) {
      var post = {
        srcUserID: req.body.userSrcID,
        destUserID: req.body.userid,
        messageContent: req.body.txt,
        messageSendDate: req.body.sendDate
      };

      connection.query('INSERT INTO messages VALUES ?', post, function(err, result) {
        // send response here
        res.json({msg:'success'});
      });

    });
</code>```

you can make change in parameters

Body:
I have made signup form using Reactjs and want to be save emailid, password, name, address in my database(mysql) who user enter at time of signup.

I have made connection using mysql & working fine but unable to store data of signup form.

var express    = require("express");
var mysql      = require('mysql');
var connection = mysql.createConnection({
host     : 'localhost',
user     : 'root',
password : 'root',
database : 'myform'
});

var app = express();

connection.connect(function(err){
if(!err) {
    console.log("Database connection successful !!!");
} else {
  console.log("Database connection failure !!!");
}
});
app.listen(8080);
console.log('App listening at port:8080');

Body:
Try following

Nodejs

      var mysql = require('mysql');

      var connection = mysql.createConnection({
        host: 'cccc.net',
        user: 'xxxxx_usr',
        password: 'xxxxxxx',
        database: 'name of your database goes here …'
      });

     // api here
     app.post('/addUser', function(req, res) {
      var post = {
        srcUserID: req.body.userSrcID,
        destUserID: req.body.userid,
        messageContent: req.body.txt,
        messageSendDate: req.body.sendDate
      };

      connection.query('INSERT INTO messages VALUES ?', post, function(err, result) {
        // send response here
        res.json({msg:'success'});
      });

    });

you can make change in parameters