问:
MySQL - Duplicate entry error when trying to add new column
I have a MySQL database with a table that has 2 million rows using innodb engine. I want to add another column, but I keep getting the following error:

```<code>Error 1062: Duplicate entry '' for key 'PRIMARY' SQL Statement: ALTER TABLE `mydb`.`table`  ADD COLUMN `country` VARCHAR(35) NULL DEFAULT NULL AFTER `email`
</code>```

How can I add the column without getting this error?

EDIT: Table definition

```<code>id int(11) NOT NULL AUTO_INCREMENT,
user_id varchar(45) NOT NULL,
first_name varchar(150) DEFAULT NULL,
last_name varchar(150) DEFAULT NULL,
gender varchar(10) DEFAULT NULL,
email varchar(100) DEFAULT NULL,
created_at bigint(20) DEFAULT NULL,
updated_at bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`,`user_id`),
UNIQUE KEY `user_id_UNIQUE` (`user_id`),
KEY `first_name` (`first_name`),
KEY `last_name` (`last_name`)
</code>```

EDIT #2: SHOW INDEXES output

```<code>Table       Non_unique  Key_name        Seq_in_index  Column_name     Collation  Cardinality Index_type
table       0           PRIMARY         1             id              A          3516446     BTREE
table       0           PRIMARY         2             user_id         A          3516446     BTREE
table       0           user_id_UNIQUE  1             user_id         A          3516446     BTREE
table       1           first_name      1             first_name      A          390716      BTREE
table       1           last_name       1             last_name       A          439555      BTREE
</code>```

答:
it solution will lock table on write, but often suitable for solving the problem if table is not very big</p>

```<code>LOCK TABLES my_table WRITE;

ALTER TABLE my_table
ADD COLUMN `ts` DATETIME NULL AFTER `id`;

UNLOCK TABLES;
</code>```

Body:
I have a MySQL database with a table that has 2 million rows using innodb engine. I want to add another column, but I keep getting the following error:

Error 1062: Duplicate entry '' for key 'PRIMARY' SQL Statement: ALTER TABLE `mydb`.`table`  ADD COLUMN `country` VARCHAR(35) NULL DEFAULT NULL AFTER `email`

How can I add the column without getting this error?

EDIT: Table definition

id int(11) NOT NULL AUTO_INCREMENT,
user_id varchar(45) NOT NULL,
first_name varchar(150) DEFAULT NULL,
last_name varchar(150) DEFAULT NULL,
gender varchar(10) DEFAULT NULL,
email varchar(100) DEFAULT NULL,
created_at bigint(20) DEFAULT NULL,
updated_at bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`,`user_id`),
UNIQUE KEY `user_id_UNIQUE` (`user_id`),
KEY `first_name` (`first_name`),
KEY `last_name` (`last_name`)

EDIT #2: SHOW INDEXES output

Table       Non_unique  Key_name        Seq_in_index  Column_name     Collation  Cardinality Index_type
table       0           PRIMARY         1             id              A          3516446     BTREE
table       0           PRIMARY         2             user_id         A          3516446     BTREE
table       0           user_id_UNIQUE  1             user_id         A          3516446     BTREE
table       1           first_name      1             first_name      A          390716      BTREE
table       1           last_name       1             last_name       A          439555      BTREE

Body:
it solution will lock table on write, but often suitable for solving the problem if table is not very big

LOCK TABLES my_table WRITE;

ALTER TABLE my_table
ADD COLUMN `ts` DATETIME NULL AFTER `id`;

UNLOCK TABLES;

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Progress Dialog over partial screen
I have a fragment with three tabs. On one of the tabs I have a dialog that spins when a background sync going on. But I need to be able to continue work on other parts when the background sync is going on.

I am currently use dialog.setCancelable(false) to go out of the dialog so that I can use the rest of the app. But that gives me an emoty screen on the fragment where the sync is going on.

Is there any way to have the dialog only overlay over part of the screen(only the fragment where the sync is going on)?. In other words a dialog that does not take the entire screen so that I can move to the other tabs without cancelling the dialog?

Implementation of dialog in java code:

```<code>    dialog = new Dialog(getActivity());
    dialog.requestWindowFeature(Window.FEATURE_PROGRESS);
    dialog.setCancelable(true);
    dialog.setContentView(R.layout.dialog_progress_bar);
    dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
</code>```

dialog.xml:

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ProgressBar
        android:id="@+id/dialogProgressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>

</LinearLayout>
</code>```

答:
No, you can't achieve this behavior with Dialog.

#. As you are using Fragment and want to show progress of syncing, so I think you can add a ProgressBar in your Fragment layout XML instead of using Dialog and show/hide ProgressBar as per sync state.

STATE:

when sync is going on, show ProgressBar only and hide others Views .

when sync completed, hide ProgressBar and show others Views as per your needs.

#. You can also use SwipeRefreshLayout in your Fragment layout XML to show that the progress is going on. It will show a circular ProgressBar when sync is going on and hide automatically when sync complete.

Here is a good tutorial: Android Swipe Down to Refresh ListView Tutorial

Hope this will help~

ContentLicense: CC BY-SA 3.0

Title: Progress Dialog over partial screen

Body:
I have a fragment with three tabs. On one of the tabs I have a dialog that spins when a background sync going on. But I need to be able to continue work on other parts when the background sync is going on.

I am currently use dialog.setCancelable(false) to go out of the dialog so that I can use the rest of the app. But that gives me an emoty screen on the fragment where the sync is going on.

Is there any way to have the dialog only overlay over part of the screen(only the fragment where the sync is going on)?. In other words a dialog that does not take the entire screen so that I can move to the other tabs without cancelling the dialog?

Implementation of dialog in java code:

    dialog = new Dialog(getActivity());
    dialog.requestWindowFeature(Window.FEATURE_PROGRESS);
    dialog.setCancelable(true);
    dialog.setContentView(R.layout.dialog_progress_bar);
    dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);

dialog.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ProgressBar
        android:id="@+id/dialogProgressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>

</LinearLayout>


问:
How can I resolve an Internal Administrator Issue in Atlassian Confluence Server?
I'm having an old issue that I would like to fix, once and for all, with Confluence Server.  When I started integrating it with JIRA a while back.  I simply cannot figure out what the hell went wrong with the administrative access to the internal directory.

I often will perform a Health Check, and will always see this:

So I made sure that I had the access needed, and made sure I assigned myself to the necessary groups:

I believed, at first, that I made the mistake of adding an Atlassian Crowd directory settings.  However, I'm not running Crowd (which, according to many threads I've read, is accessible from a specific port with '/crowd/'.)  It does synchronize though, for some odd reason, so maybe it's similar to the JIRA directory you can setup (as opposed to Crowd.)  Either way, it doesn't make sense that this would affect access to the internal directory (especially where I have the same user and group setting on JIRA, as well.)

If I've already attempted a fix that's recommended, then I'll let you know.  Hopefully, I'm overlooking the obvious.  The Users I have setup in Confluence are myself and two colleagues.  The only thing I may have done in the past was delete a user that was automatically given the name of "admin" or something similar.  However, I am an admin, so other than the name - I would belong to the same groups (as seen above).

答:
That error clearly mentioned that you don't have an Administrator User in Confluence Internal Directory. It doesn't mean that you don't have administrator account and it only means that you don't have them in Internal Directory.

That Remote JIRA Directory, means you are using JIRA as an external user directory. In Atlassian Applications JIRA and Crowd are both using embedded Crowd Directory for authentication with Confluence. Thus, that shouldn't be a big deal. The point here is you do have an external user directory on higher position.

Technically, position of the user directories are really important for Confluence. Because during user creation and authentication, Confluence checks the first directory. If the user exists will use the first directory for login.

With what you mentioned, I would say, your user name is in JIRA and it's getting synchronised with Confluence via that user directory. That's why you do have same users in both JIRA and Confluence.

Why you are seeing that error and why it's concern for health check is, if you encounter to a network issue with JIRA Server or JIRA Server won't be accessible, you need to have on internal user for troubleshooting propose.

For fixing this issue you do have two options:

1. First Solution:

Change the Confluence Internal Directory into the first position. Create a user admin and assign it to Confluence User and Confluence Administrator Group. Change the position of your Remote JIRA Directory back to first place.

2. Create user from database

You can use the options from this document and create an admin user in your Internal Directory.

Tips:

When you creating user, please make sure that it won't have same name as other administrator users in JRIA Directory.

Create backup from your database prior to change anything. That way, you can ensure that you won't locked out from application.


问:
Range aggregation on date_range field
I have a set of documents with date range. I want to get schedule with in specific duration.

For example, following are 2 events.

```<code>1. Event 1 - from 10th to 20th
2. Event 2 - from 15th to 25th
</code>```

Get schedule from 1st to 30th. Expecting following output.

```<code>1. Date 10th to 14th - Event 1
2. Date 15th to 20th - Event 1 and Event 2
3. Date 21st to 25th - Event 2
</code>```

Please suggest how can i achieve this.

答: you can use the range datatypes to support this. See this introduction blog post</p>

Title: Range aggregation on date_range field

Body:
I have a set of documents with date range. I want to get schedule with in specific duration.

For example, following are 2 events.

1. Event 1 - from 10th to 20th
2. Event 2 - from 15th to 25th

Get schedule from 1st to 30th. Expecting following output.

1. Date 10th to 14th - Event 1
2. Date 15th to 20th - Event 1 and Event 2
3. Date 21st to 25th - Event 2

Please suggest how can i achieve this.


问:
How to change focus different Jbuttons when a keyboard key is pressed?
So hey guys, I've been trying to design a piano through java, net-beans for my final project at uni. thing here is every thing works well so far but I've got issues with focus here. for example I'm trying to play the keys through the keyboard, i want the piano keys to get focused to the specified key its assigned any idea on how to do it? much appreciated. this is my 1st question here, so I'm not sure if I'm asking the right things here.

I'm gonna provide the sample I'm working with.

```<code>   package javaapplication5;

   import sun.audio.*;

   import java.io.*;

   import javax.swing.JOptionPane;

   public class NewJFrame1 extends javax.swing.JFrame {

public NewJFrame1() {

    initComponents();

}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jButton1.setText("A");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });
    jButton1.addFocusListener(new java.awt.event.FocusAdapter() {
        public void focusGained(java.awt.event.FocusEvent evt) {
            jButton1FocusGained(evt);
        }
    });
    jButton1.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyPressed(java.awt.event.KeyEvent evt) {
            jButton1KeyPressed(evt);
        }
        public void keyReleased(java.awt.event.KeyEvent evt) {
            jButton1KeyReleased(evt);
        }
    });

    jButton2.setText("B");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });
    jButton2.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyPressed(java.awt.event.KeyEvent evt) {
            jButton2KeyPressed(evt);
        }
    });

    jButton3.setText("C");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton3ActionPerformed(evt);
        }
    });
    jButton3.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyPressed(java.awt.event.KeyEvent evt) {
            jButton3KeyPressed(evt);
        }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(89, 89, 89)
            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(123, Short.MAX_VALUE))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
            .addContainerGap(91, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(110, 110, 110))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(45, 45, 45)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(190, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(51, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

    InputStream iAudio;

    try{
        iAudio = new FileInputStream(new File("C:\\Users\\MohammedRishad\\Desktop\\Audios\\A.wav"));
        AudioStream iMusic = new AudioStream(iAudio);
        AudioPlayer.player.start(iMusic);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    InputStream iAudio;

    try{
        iAudio = new FileInputStream(new File("C:\\Users\\MohammedRishad\\Desktop\\Audios\\B.wav"));
        AudioStream iMusic = new AudioStream(iAudio);
        AudioPlayer.player.start(iMusic);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
}

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
   InputStream iAudio;

    try{
        iAudio = new FileInputStream(new File("C:\\Users\\MohammedRishad\\Desktop\\Audios\\C.wav"));
        AudioStream iMusic = new AudioStream(iAudio);
        AudioPlayer.player.start(iMusic);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
}

private void jButton1KeyPressed(java.awt.event.KeyEvent evt) {

    if(evt.getKeyChar()=='z'){
    InputStream iAudio;

    try{
        iAudio = new FileInputStream(new File("C:\\Users\\MohammedRishad\\Desktop\\Audios\\A.wav"));
        AudioStream iMusic = new AudioStream(iAudio);
        AudioPlayer.player.start(iMusic);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
   }

}

private void jButton2KeyPressed(java.awt.event.KeyEvent evt) {

    if(evt.getKeyChar()=='x'){
    InputStream iAudio;

    try{
        iAudio = new FileInputStream(new File("C:\\Users\\MohammedRishad\\Desktop\\Audios\\B.wav"));
        AudioStream iMusic = new AudioStream(iAudio);
        AudioPlayer.player.start(iMusic);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
   }
}

private void jButton3KeyPressed(java.awt.event.KeyEvent evt) {

    if(evt.getKeyChar()=='c'){
    InputStream iAudio;

    try{
        iAudio = new FileInputStream(new File("C:\\Users\\MohammedRishad\\Desktop\\Audios\\C.wav"));
        AudioStream iMusic = new AudioStream(iAudio);
        AudioPlayer.player.start(iMusic);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
   }
}

public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new NewJFrame1().setVisible(true);
        }
    });
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JPanel jPanel1;
// End of variables declaration
</code>```

}

As this is a sample I'm working with just 3 buttons here. I'd like to get all the help i can thanks in advance

答: Can change focus on button using requestFocus() method</p>

Body:
So hey guys, I've been trying to design a piano through java, net-beans for my final project at uni. thing here is every thing works well so far but I've got issues with focus here. for example I'm trying to play the keys through the keyboard, i want the piano keys to get focused to the specified key its assigned any idea on how to do it? much appreciated. this is my 1st question here, so I'm not sure if I'm asking the right things here.

I'm gonna provide the sample I'm working with.

   package javaapplication5;

   import sun.audio.*;

   import java.io.*;

   import javax.swing.JOptionPane;

   public class NewJFrame1 extends javax.swing.JFrame {

public NewJFrame1() {

    initComponents();

}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jButton1.setText("A");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });
    jButton1.addFocusListener(new java.awt.event.FocusAdapter() {
        public void focusGained(java.awt.event.FocusEvent evt) {
            jButton1FocusGained(evt);
        }
    });
    jButton1.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyPressed(java.awt.event.KeyEvent evt) {
            jButton1KeyPressed(evt);
        }
        public void keyReleased(java.awt.event.KeyEvent evt) {
            jButton1KeyReleased(evt);
        }
    });

    jButton2.setText("B");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });
    jButton2.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyPressed(java.awt.event.KeyEvent evt) {
            jButton2KeyPressed(evt);
        }
    });

    jButton3.setText("C");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton3ActionPerformed(evt);
        }
    });
    jButton3.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyPressed(java.awt.event.KeyEvent evt) {
            jButton3KeyPressed(evt);
        }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(89, 89, 89)
            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(123, Short.MAX_VALUE))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
            .addContainerGap(91, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(110, 110, 110))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(45, 45, 45)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(190, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(51, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

    InputStream iAudio;

    try{
        iAudio = new FileInputStream(new File("C:\\Users\\MohammedRishad\\Desktop\\Audios\\A.wav"));
        AudioStream iMusic = new AudioStream(iAudio);
        AudioPlayer.player.start(iMusic);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    InputStream iAudio;

    try{
        iAudio = new FileInputStream(new File("C:\\Users\\MohammedRishad\\Desktop\\Audios\\B.wav"));
        AudioStream iMusic = new AudioStream(iAudio);
        AudioPlayer.player.start(iMusic);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
}

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
   InputStream iAudio;

    try{
        iAudio = new FileInputStream(new File("C:\\Users\\MohammedRishad\\Desktop\\Audios\\C.wav"));
        AudioStream iMusic = new AudioStream(iAudio);
        AudioPlayer.player.start(iMusic);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
}

private void jButton1KeyPressed(java.awt.event.KeyEvent evt) {

    if(evt.getKeyChar()=='z'){
    InputStream iAudio;

    try{
        iAudio = new FileInputStream(new File("C:\\Users\\MohammedRishad\\Desktop\\Audios\\A.wav"));
        AudioStream iMusic = new AudioStream(iAudio);
        AudioPlayer.player.start(iMusic);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
   }

}

private void jButton2KeyPressed(java.awt.event.KeyEvent evt) {

    if(evt.getKeyChar()=='x'){
    InputStream iAudio;

    try{
        iAudio = new FileInputStream(new File("C:\\Users\\MohammedRishad\\Desktop\\Audios\\B.wav"));
        AudioStream iMusic = new AudioStream(iAudio);
        AudioPlayer.player.start(iMusic);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
   }
}

private void jButton3KeyPressed(java.awt.event.KeyEvent evt) {

    if(evt.getKeyChar()=='c'){
    InputStream iAudio;

    try{
        iAudio = new FileInputStream(new File("C:\\Users\\MohammedRishad\\Desktop\\Audios\\C.wav"));
        AudioStream iMusic = new AudioStream(iAudio);
        AudioPlayer.player.start(iMusic);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
   }
}

public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new NewJFrame1().setVisible(true);
        }
    });
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JPanel jPanel1;
// End of variables declaration

}

As this is a sample I'm working with just 3 buttons here. I'd like to get all the help i can thanks in advance


问:
XPath to return default value if node not present
Say I have a pair of XML documents

```<code><Foo>
    <Bar/>
    <Baz>mystring</Baz>
</Foo>
</code>```

and

```<code><Foo>
    <Bar/>
</Foo>
</code>```

I want an XPath (Version 1.0 only) that returns "mystring" for the first document and "not-found" for the second. I tried

```<code>(string('not-found') | //Baz)[last()]
</code>```

but the left hand side of the union isn't a node-set

ContentLicense: CC BY-SA 2.5

Body:
Say I have a pair of XML documents

<Foo>
    <Bar/>
    <Baz>mystring</Baz>
</Foo>

and

<Foo>
    <Bar/>
</Foo>

I want an XPath (Version 1.0 only) that returns "mystring" for the first document and "not-found" for the second. I tried

(string('not-found') | //Baz)[last()]

but the left hand side of the union isn't a node-set

Body: /Foo/(Baz/string(), 'not-found')[1]


问:
VBA Clear formatting hides line breaks until formula bar is activated? Why?
I have noticed that when clearing formatting, .ClearFormats, of a sheet in Excel via VBA it also appears it clears the line feeds in text strings inside cells. However, when you click and activate the formula bar and exits it again, the line feeds reappears.

What is going on? And is there a way to show the line feeds in the cells again with VBA? I am currently clearing formatting for faster savings (cell colorings are slowing down my saving time), and I would like to avoid having to manually click every header and the formula bar everytime.

This is my procedure at the moment. (I had to add one image instead of four since I do not have enough reputation points for more than two links.)

After my code is run and formatting is done.

Then I run the line ActiveWorksheet.Cells.ClearFormats

If I run my formatting procedure again (unchanged text strings in cells)

I then click on cell D1 --> Click in formula bar --> Click in random other cell

Print Screens of the different stages of the explained procedure

Why is this happening? And is there a way to avoid it without resetting default formatting for each "format setting" (e.g. background color, border, font etc.)?

答:
Add a ActiveWorksheet.Cells.WrapText = True after your ActiveWorksheet.Cells.ClearFormats

Or specialize it to a range of cells if not all cells should be wrapped.


问:
Using session in EJS with node
I am new to node and need some help in using session. I am using EJS to render my web-pages. Please find my code below.

app.js

```<code>var express = require('express');
var registerController = require('./controllers/registerController');
var app =express();
var bodyParser = require('body-parser');
var sessions=require('express-session');

app.set('view engine', 'ejs');

app.use(express.static('./public'));

app.use(sessions({
    secret:'asasds*(&^*(',
    resave:false,
    saveUninitialized:true
}));

app.use(function(req, res, next) {
  res.locals.user = req.session.user;
  next();
});

//controllers
registerController(app);

app.listen(3000);
console.log( " you are listening to port 3000");
</code>```

registercontroller.js

```<code>var bodyParser = require('body-parser');
var fs = require('fs');

var urlencodedParser = bodyParser.urlencoded({ extended: false });

module.exports=function(app){

    app.get('/register',function(req,res){
            res.render('register');
    });

    app.post('/register',urlencodedParser,function(req,res){
        console.log(" inside controller :::" );

        var userObj = {
            "username":req.body.username,
            "password":req.body.password,
            "email":req.body.email,
            "fNmame":req.body.fNmame,
            "lNmame":req.body.lNmame
        }
        console.log(" userObj :::" + JSON.stringify(userObj));

        fs.writeFile("/assets/data.txt", JSON.stringify(userObj), function(err) {
            if(err) {
                return console.log(err);
            }

            console.log("The file was saved!");
        });
        var val = req.session.user;

     res.render('index2',{session: req.session});
    });
};
</code>```

index2.ejs

```<code> <%= JSON.stringify(session) %>
</code>```

Using all the above I get the below error

```<code> <%= JSON.stringify(session) %>

session is not defined
    at eval (eval at compile (c:\learning\socialnetworking\node_modules\ejs\lib\ejs.js:524:12), <anonymous>:24:41)
    at returnedFn (c:\learning\socialnetworking\node_modules\ejs\lib\ejs.js:555:17)
    at tryHandleCache (c:\learning\socialnetworking\node_modules\ejs\lib\ejs.js:203:34)
    at View.exports.renderFile [as engine] (c:\learning\socialnetworking\node_modules\ejs\lib\ejs.js:412:10)
    at View.render (c:\learning\socialnetworking\node_modules\express\lib\view.js:128:8)
    at tryRender (c:\learning\socialnetworking\node_modules\express\lib\application.js:640:10)
    at EventEmitter.render (c:\learning\socialnetworking\node_modules\express\lib\application.js:592:3)
    at ServerResponse.render (c:\learning\socialnetworking\node_modules\express\lib\response.js:971:7)
    at c:\learning\socialnetworking\controllers\registerController.js:26:13
    at Layer.handle [as handle_request] (c:\learning\socialnetworking\node_modules\express\lib\router\layer.js:95:5)
    at next (c:\learning\socialnetworking\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (c:\learning\socialnetworking\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (c:\learning\socialnetworking\node_modules\express\lib\router\layer.js:95:5)
    at c:\learning\socialnetworking\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (c:\learning\socialnetworking\node_modules\express\lib\router\index.js:335:12)
    at next (c:\learning\socialnetworking\node_modules\express\lib\router\index.js:275:10)
</code>```

答:
```<code>res.render('register.ejs', {
    layout:false,
    session: req.session
});
</code>```

you need to include this basically

Title: Using session in EJS with node

Body:
I am new to node and need some help in using session. I am using EJS to render my web-pages. Please find my code below.

app.js

var express = require('express');
var registerController = require('./controllers/registerController');
var app =express();
var bodyParser = require('body-parser');
var sessions=require('express-session');

app.set('view engine', 'ejs');

app.use(express.static('./public'));

app.use(sessions({
    secret:'asasds*(&^*(',
    resave:false,
    saveUninitialized:true
}));

app.use(function(req, res, next) {
  res.locals.user = req.session.user;
  next();
});

//controllers
registerController(app);

app.listen(3000);
console.log( " you are listening to port 3000");

registercontroller.js

var bodyParser = require('body-parser');
var fs = require('fs');

var urlencodedParser = bodyParser.urlencoded({ extended: false });

module.exports=function(app){

    app.get('/register',function(req,res){
            res.render('register');
    });

    app.post('/register',urlencodedParser,function(req,res){
        console.log(" inside controller :::" );

        var userObj = {
            "username":req.body.username,
            "password":req.body.password,
            "email":req.body.email,
            "fNmame":req.body.fNmame,
            "lNmame":req.body.lNmame
        }
        console.log(" userObj :::" + JSON.stringify(userObj));

        fs.writeFile("/assets/data.txt", JSON.stringify(userObj), function(err) {
            if(err) {
                return console.log(err);
            }

            console.log("The file was saved!");
        });
        var val = req.session.user;

     res.render('index2',{session: req.session});
    });
};

index2.ejs

 <%= JSON.stringify(session) %>

Using all the above I get the below error

 <%= JSON.stringify(session) %>

session is not defined
    at eval (eval at compile (c:\learning\socialnetworking\node_modules\ejs\lib\ejs.js:524:12), <anonymous>:24:41)
    at returnedFn (c:\learning\socialnetworking\node_modules\ejs\lib\ejs.js:555:17)
    at tryHandleCache (c:\learning\socialnetworking\node_modules\ejs\lib\ejs.js:203:34)
    at View.exports.renderFile [as engine] (c:\learning\socialnetworking\node_modules\ejs\lib\ejs.js:412:10)
    at View.render (c:\learning\socialnetworking\node_modules\express\lib\view.js:128:8)
    at tryRender (c:\learning\socialnetworking\node_modules\express\lib\application.js:640:10)
    at EventEmitter.render (c:\learning\socialnetworking\node_modules\express\lib\application.js:592:3)
    at ServerResponse.render (c:\learning\socialnetworking\node_modules\express\lib\response.js:971:7)
    at c:\learning\socialnetworking\controllers\registerController.js:26:13
    at Layer.handle [as handle_request] (c:\learning\socialnetworking\node_modules\express\lib\router\layer.js:95:5)
    at next (c:\learning\socialnetworking\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (c:\learning\socialnetworking\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (c:\learning\socialnetworking\node_modules\express\lib\router\layer.js:95:5)
    at c:\learning\socialnetworking\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (c:\learning\socialnetworking\node_modules\express\lib\router\index.js:335:12)
    at next (c:\learning\socialnetworking\node_modules\express\lib\router\index.js:275:10)

Body:
res.render('register.ejs', {
    layout:false,
    session: req.session
});

you need to include this basically


问:
How do i add ObservableList obtained from Mysql server to javaFX Tableview?
I want to populate JavaFX tableview with the contents of a mysql database. I have created an observable list and added table data in it but i don't know how to display this list in tableview. Here is code for list,

```<code>public ObservableList<PatientDto> getAllPatientInfo() {
    ObservableList<PatientDto> list = FXCollections.observableArrayList();
    PreparedStatement ps = null;
    try {
        String sql = "select * from patient_record";
        ps = DbUtil.getConnection().prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            PatientDto patientDto = new PatientDto();
            patientDto.setPid(rs.getInt("PID"));
            patientDto.setPatient_Name(rs.getString("Patient_Name"));
            patientDto.setAddress(rs.getString("Address"));
            patientDto.setAge(rs.getInt("Age"));
            patientDto.setDisease(rs.getString("Disease"));
            patientDto.setDoctor_Name(rs.getString("Doctor_Name"));
            patientDto.setAdmit_Date(rs.getDate("Admit_date"));
            patientDto.setDischarge_Date(rs.getDate("Discharge_Date"));
            list.add(patientDto);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return list;
}
</code>```

I am using scene builder for UI and this is interface of my tableview
TableView In scene builder

And this is ss of my table in mysql database. Table in Mysql server.
I am newbie in JavaFX so i am finding it difficult to implement available answers. So please describe in detailed manner.

答:
first of all you need a model class that holds the information for the table, lets call this as PatientModel that looks like this:

```<code>public class PatientModel {

private StringProperty pid;
private StringProperty patientName;
private StringProperty address;
/* ...
 * and so on...
 */

public PatientModel(String pid, String patientName, String address) {
    this.pid = new SimpleStringProperty(pid);
    this.patientName = new SimpleStringProperty(patientName);
    this.address = new SimpleStringProperty(address);
}

public String getPid() {
    return pid.get();
}

public StringProperty pidProperty() {
    return pid;
}

public String getPatientName() {
    return patientName.get();
}

public StringProperty patientNameProperty() {
    return patientName;
}

public String getAddress() {
    return address.get();
}

public StringProperty addressProperty() {
    return address;
}
}
</code>```

Then you need an .fxml file that similar to this:

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="500.0" prefWidth="700.0" xmlns="http://javafx.com/javafx/8.0.91"
        xmlns:fx="http://javafx.com/fxml/1"
fx:controller="stackoverflow.TestController">
    <TableView fx:id="table">
        <columns>
            <TableColumn fx:id="pidColumn" text="PID"/>
            <TableColumn fx:id="nameColumn" text="Patient Name"/>
            <TableColumn fx:id="addressColumn" text="Address"/>
            <!-- and so on... -->
        </columns>
    </TableView>
</AnchorPane>
</code>```

Then a controller class:

```<code>public class TestController implements Initializable {

@FXML
private TableView<PatientModel> table;
@FXML
private TableColumn<PatientModel, String> pidColumn;
@FXML
private TableColumn<PatientModel, String> nameColumn;
@FXML
private TableColumn<PatientModel, String> addressColumn;

private ObservableList<PatientModel> tableData = FXCollections.observableArrayList();

@Override
public void initialize(URL location, ResourceBundle resources) {
    initTable();
    // if the data is coming from an other class you have probably a list of them,
    // if not you can simply populate the tableData
    List<PatientDto> dtosFromDB = new ArrayList<>();
    tableData.addAll(dtosFromDB.stream().map(this::convertDtoToModel).collect(Collectors.toList()));
}

private void initTable() {
    table.setItems(tableData);

    pidColumn.setCellValueFactory(data -> data.getValue().pidProperty()); // here is where tha magic happens :)

    nameColumn.setCellValueFactory(data -> data.getValue().patientNameProperty()); // this sets the cells value from
                                                                                // the model.
    addressColumn.setCellValueFactory(data -> data.getValue().addressProperty());
}

private PatientModel convertDtoToModel(PatientDto dto) {
    return new PatientModel(dto.getPid().toString(), dto.getName(), dto.getAddress()/* and so on */);
}
}
</code>```

After you have these classes you can simply load the .fxml from your main class, then you have to complete with all of the informations and it should work.

P.S. Sorry for the indenting, I cannot indent here the whole code just by rows and it is so boring.

Body:
I want to populate JavaFX tableview with the contents of a mysql database. I have created an observable list and added table data in it but i don't know how to display this list in tableview. Here is code for list,

public ObservableList<PatientDto> getAllPatientInfo() {
    ObservableList<PatientDto> list = FXCollections.observableArrayList();
    PreparedStatement ps = null;
    try {
        String sql = "select * from patient_record";
        ps = DbUtil.getConnection().prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            PatientDto patientDto = new PatientDto();
            patientDto.setPid(rs.getInt("PID"));
            patientDto.setPatient_Name(rs.getString("Patient_Name"));
            patientDto.setAddress(rs.getString("Address"));
            patientDto.setAge(rs.getInt("Age"));
            patientDto.setDisease(rs.getString("Disease"));
            patientDto.setDoctor_Name(rs.getString("Doctor_Name"));
            patientDto.setAdmit_Date(rs.getDate("Admit_date"));
            patientDto.setDischarge_Date(rs.getDate("Discharge_Date"));
            list.add(patientDto);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return list;
}

I am using scene builder for UI and this is interface of my tableview
TableView In scene builder

And this is ss of my table in mysql database. Table in Mysql server.
I am newbie in JavaFX so i am finding it difficult to implement available answers. So please describe in detailed manner.

Body:
first of all you need a model class that holds the information for the table, lets call this as PatientModel that looks like this:

public class PatientModel {

private StringProperty pid;
private StringProperty patientName;
private StringProperty address;
/* ...
 * and so on...
 */

public PatientModel(String pid, String patientName, String address) {
    this.pid = new SimpleStringProperty(pid);
    this.patientName = new SimpleStringProperty(patientName);
    this.address = new SimpleStringProperty(address);
}

public String getPid() {
    return pid.get();
}

public StringProperty pidProperty() {
    return pid;
}

public String getPatientName() {
    return patientName.get();
}

public StringProperty patientNameProperty() {
    return patientName;
}

public String getAddress() {
    return address.get();
}

public StringProperty addressProperty() {
    return address;
}
}

Then you need an .fxml file that similar to this:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="500.0" prefWidth="700.0" xmlns="http://javafx.com/javafx/8.0.91"
        xmlns:fx="http://javafx.com/fxml/1"
fx:controller="stackoverflow.TestController">
    <TableView fx:id="table">
        <columns>
            <TableColumn fx:id="pidColumn" text="PID"/>
            <TableColumn fx:id="nameColumn" text="Patient Name"/>
            <TableColumn fx:id="addressColumn" text="Address"/>
            <!-- and so on... -->
        </columns>
    </TableView>
</AnchorPane>

Then a controller class:

public class TestController implements Initializable {

@FXML
private TableView<PatientModel> table;
@FXML
private TableColumn<PatientModel, String> pidColumn;
@FXML
private TableColumn<PatientModel, String> nameColumn;
@FXML
private TableColumn<PatientModel, String> addressColumn;

private ObservableList<PatientModel> tableData = FXCollections.observableArrayList();

@Override
public void initialize(URL location, ResourceBundle resources) {
    initTable();
    // if the data is coming from an other class you have probably a list of them,
    // if not you can simply populate the tableData
    List<PatientDto> dtosFromDB = new ArrayList<>();
    tableData.addAll(dtosFromDB.stream().map(this::convertDtoToModel).collect(Collectors.toList()));
}

private void initTable() {
    table.setItems(tableData);

    pidColumn.setCellValueFactory(data -> data.getValue().pidProperty()); // here is where tha magic happens :)

    nameColumn.setCellValueFactory(data -> data.getValue().patientNameProperty()); // this sets the cells value from
                                                                                // the model.
    addressColumn.setCellValueFactory(data -> data.getValue().addressProperty());
}

private PatientModel convertDtoToModel(PatientDto dto) {
    return new PatientModel(dto.getPid().toString(), dto.getName(), dto.getAddress()/* and so on */);
}
}

After you have these classes you can simply load the .fxml from your main class, then you have to complete with all of the informations and it should work.

P.S. Sorry for the indenting, I cannot indent here the whole code just by rows and it is so boring.


问:
explain these how the conditional operator helps in counting the negative and positive numbers in an array?
my confusion is that how in the program the number of positive and negative numbers are calculated by writing that piece of code shown.
explain these code please!</p>

```<code>int num[5], i, neg = 0, pos = 0;

printf("enter any 5 numbers");
for (i = 0; i <= 4; i++)
    scanf("%d", &num[i]);
for (i = 0; i <= 4; i++) {
    num[i] < 0 ? neg++ : (pos++);
}
printf("\nnegative elements=%d", neg);
printf("\npositive elements=%d", pos);
getch();
</code>```

答:
```<code> num[i]<0?neg++:(pos++);
</code>```

Here, If number less then zero then condition become true and count the negative numbers and If number not less then zero then condition become false and count positive numbers.

Body:
my confusion is that how in the program the number of positive and negative numbers are calculated by writing that piece of code shown.
explain these code please!

int num[5], i, neg = 0, pos = 0;

printf("enter any 5 numbers");
for (i = 0; i <= 4; i++)
    scanf("%d", &num[i]);
for (i = 0; i <= 4; i++) {
    num[i] < 0 ? neg++ : (pos++);
}
printf("\nnegative elements=%d", neg);
printf("\npositive elements=%d", pos);
getch();

Body:
 num[i]<0?neg++:(pos++);

Here, If number less then zero then condition become true and count the negative numbers and If number not less then zero then condition become false and count positive numbers.


问:
Yii2 validation. Run filter on multiple attributes
```<code>public function rules()
{
    return [
        [['option_list', 'modifier'], 'filter', 'filter' => function($value) {
            // I can get the value but I don't know to which attribute it belongs (option_list or modifier)
        }],
    ];
}
</code>```

How do I get an attribute name which is being processed? The only workaround that I found is to make separate filter for each attribute...

答:
The first parameter passed to validation function is $attribute so You can use it as follows

```<code>public function rules()
{
    return [
        [['option_list', 'modifier'], function($attribute) {
            // use $this->$attribute for conditions or filtering
            // use $this->addError($attribute, '<error message>') for adding errors
        }],
    ];
}
</code>```

see http://www.yiiframework.com/doc-2.0/guide-input-validation.html#creating-validators

Body:
public function rules()
{
    return [
        [['option_list', 'modifier'], 'filter', 'filter' => function($value) {
            // I can get the value but I don't know to which attribute it belongs (option_list or modifier)
        }],
    ];
}

How do I get an attribute name which is being processed? The only workaround that I found is to make separate filter for each attribute...

Body:
The first parameter passed to validation function is $attribute so You can use it as follows

public function rules()
{
    return [
        [['option_list', 'modifier'], function($attribute) {
            // use $this->$attribute for conditions or filtering
            // use $this->addError($attribute, '<error message>') for adding errors
        }],
    ];
}

see http://www.yiiframework.com/doc-2.0/guide-input-validation.html#creating-validators


问:
Mongodb Cxx Driver Test crashing in Release Build [ Works fine in Debug ]
I have build the mongodb cxx binaries in windows following the steps described here.

I have created the Test application as mentioned in the steps.
On release builds, the application throws bad allocation exception:
std::bad_alloc at memory location 0x0047EB60] in this line :

```<code>mongocxx::uri muri{ uri_string };
</code>```

The same code works with Debug build.

Could someone please help me to fix the issue in Release build ?

答:
My issue got resolved after I built mongocxx and bsoncxx in Release and used that. Previously I built those in Debug and Test Application in release.
Need to match the target configuration.</p>

Body:
I have build the mongodb cxx binaries in windows following the steps described here.

I have created the Test application as mentioned in the steps.
On release builds, the application throws bad allocation exception:
std::bad_alloc at memory location 0x0047EB60] in this line :

mongocxx::uri muri{ uri_string };

The same code works with Debug build.

Could someone please help me to fix the issue in Release build ?


问:
Microsoft Authentication: How to refresh access token using ajax post?
I've been going through the app authorization steps here https://developer.microsoft.com/en-us/graph/docs/authorization/app_authorization, but can't seem to get the request to work. I consistently get errors saying

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access."

This seems weird as I am including that header.

```<code> $.ajax({
            type: "POST",
            url: url,
            crossDomain: true,
            data: {
                'refreshToken': refreshToken,
                'client_id': clientId,
                'client_secret': clientSecret,
                'redirect_uri': redirect_uri,
                'resource': resource
            },
            dataType: 'json',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('Access-Control-Allow-Origin', "*");
                xhr.setRequestHeader('Access-Control-Allow-Methods', "*");
                xhr.setRequestHeader('Access-Control-Allow-Headers', "*");
            },
            success: function (data, status, headers, config) {
                callback(data);
            },
            error: function (data, status, headers, config) {
                console.log('Error getting access token from Microsoft Graph: ' + status + " " + JSON.stringify(data));
            }
        });
</code>```

答:
You are using a wrong OAuth2 flow. You should not use the Authorization grand code flow in browser applications, because you cannot keep the client secret safe and the tokens get to the server when a browser requests the redirect URL (the tokens are not in the hash # part of the URL).

That's why Microsoft API doesn't support XHR access to the /token endpoint (by omitting the CORS response headers).

You could consider using the Implicit flow, which is designed for usage in browsers, keeps the tokens safe and doesn't require a client secret.

Body:
I've been going through the app authorization steps here https://developer.microsoft.com/en-us/graph/docs/authorization/app_authorization, but can't seem to get the request to work. I consistently get errors saying

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access."

This seems weird as I am including that header.

 $.ajax({
            type: "POST",
            url: url,
            crossDomain: true,
            data: {
                'refreshToken': refreshToken,
                'client_id': clientId,
                'client_secret': clientSecret,
                'redirect_uri': redirect_uri,
                'resource': resource
            },
            dataType: 'json',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('Access-Control-Allow-Origin', "*");
                xhr.setRequestHeader('Access-Control-Allow-Methods', "*");
                xhr.setRequestHeader('Access-Control-Allow-Headers', "*");
            },
            success: function (data, status, headers, config) {
                callback(data);
            },
            error: function (data, status, headers, config) {
                console.log('Error getting access token from Microsoft Graph: ' + status + " " + JSON.stringify(data));
            }
        });


问:
Increase height of jumbotron
I want to increase height of my jumbotron without giving it in class because then it will be no more responsive.
I wanna make this. But mine look like this

Here is my code
Html:

```<code><div class="container">
            <div class="row">
                <div class="jumbotron">
                    <div class="col-md-10">
                        <h2 class="meeting_heading">MeetingResult is dedicated to ridding the world of ineffective, under-performing and outright wasteful business meetings.</h2>
                    </div>
                    <div class="col-ms-2">
                        <button type="button" class="btn btn-default btn-lg btn-custom">Learn More</button>
                    </div>
                </div>
            </div>
        </div>
</code>```

CSS:

```<code>.container
{
    width:87%;
}
.jumbotron
{
    box-shadow: inset 0px -8px 0 rgba(0, 0, 0, 0.1);
    border-radius: 13px;
    background-color: #FAFAFA;
    min-height:300px;
}
.btn-custom
{
    width: 152px;
    background-color: #1abc9c;
    border: none;
    color:#ffffff;
    font-size: 21.994px;
    line-height: 22px;
    padding: 15px 20px 16px;
    position: relative;
    top: 13px;
    right: 4px;
}
</code>```

答:
Looks like it's working fine..

But there should be another situation in your side, that your jumbotron may be inherited from it's parent so you need to use padding there and make that rule important like this..

```<code>    .jumbotron {
        padding: 48px 60px !important;
    }
</code>```

Or you can use min-height as you are using already like:

```<code>    .jumbotron {
        min-height: 300px !important;
    }
</code>```

It may solve your problem...!

Title: Increase height of jumbotron

Body:
I want to increase height of my jumbotron without giving it in class because then it will be no more responsive.
I wanna make this. But mine look like this

Here is my code
Html:

MeetingResult is dedicated to ridding the world of ineffective, under-performing and outright wasteful business meetings.

                        <button type="button" class="btn btn-default btn-lg btn-custom">Learn More</button>

CSS:

.container
{
    width:87%;
}
.jumbotron
{
    box-shadow: inset 0px -8px 0 rgba(0, 0, 0, 0.1);
    border-radius: 13px;
    background-color: #FAFAFA;
    min-height:300px;
}
.btn-custom
{
    width: 152px;
    background-color: #1abc9c;
    border: none;
    color:#ffffff;
    font-size: 21.994px;
    line-height: 22px;
    padding: 15px 20px 16px;
    position: relative;
    top: 13px;
    right: 4px;
}

Body:
Looks like it's working fine..

But there should be another situation in your side, that your jumbotron may be inherited from it's parent so you need to use padding there and make that rule important like this..

    .jumbotron {
        padding: 48px 60px !important;
    }

Or you can use min-height as you are using already like:

    .jumbotron {
        min-height: 300px !important;
    }

It may solve your problem...!


问:
An operation was attempted on a nonexistent network connection, error code 1229
Just working on a nice and simple HttpListener and all of the sudden this exception pops-up.

An operation was attempted on a nonexistent network connection.

Look hours for a solution and could not find one. The code crashed as soon as i submit data from the webpage to the HttpListener.
Can someone please explain to me how i can fix this issue?

The Code is below:

C#

```<code>public static void StartListening()
    {

        Stream ouputStream;

        HttpListener listener = new HttpListener();
        SetPrefixes(listener);

        if (listener.Prefixes.Count > 0)
        {
            listener.Start();

            Console.WriteLine("HttpClient Started");

            while(true)
            {
                HttpListenerContext context = listener.GetContext();
                HttpListenerRequest request= context.Request;
                HttpListenerResponse response = context.Response;

                string html = Properties.Resources.index;
                byte[] webPageBuffer = Encoding.UTF8.GetBytes(html);

                response.ContentLength64 = webPageBuffer.Length;
                ouputStream = response.OutputStream;
                ouputStream.Write(webPageBuffer, 0, webPageBuffer.Length);

                ouputStream.Flush();

                Common.Wait(2000);

                String url = request.RawUrl;
                String[] queryStringArray = url.Split('/');
                String postedtext = GetPostedText(request);

                byte[] buffer = null;

                // Lots of if statements because a switch would not work here.
                if(queryStringArray[0] == "myForm")
                {
                    buffer = System.Text.Encoding.UTF8.GetBytes("I recieved myForm");
                }
                if(queryStringArray[1] == "doSomething")
                {
                    buffer = System.Text.Encoding.UTF8.GetBytes("I recieved doSomething");
                }
                if(buffer != null)
                {
                    response.AddHeader("Cache-Control", "no-cache");
                    response.AddHeader("Acces-Control-Allow-Origin","*");

                    response.ContentLength64 = buffer.Length;
                    ouputStream = response.OutputStream;
                    ouputStream.Write(buffer, 0, buffer.Length);
                    ouputStream.Close();
                }
            }
        }
    }

    private static void SetContext(HttpListenerContext context, Stream ouputStream)
    {
        // De GetContext methode blokkeert terwijl die wacht op een aanvraag(request)

    }

    private static void SetPrefixes(HttpListener listener)
    {
        String[] prefixes = new String[] { "http://localhost:8100/", "http://192.168.33.28:8000/" };

        int i = 0;

        foreach (string s in prefixes)
        {
            listener.Prefixes.Add(s);
            i++;
        }
    }

    private static string GetPostedText(HttpListenerRequest request)
    {
        string recievedText;

        using(StreamReader reader = new StreamReader(request.InputStream, request.ContentEncoding))
        {
            recievedText= reader.ReadToEnd();
        }

        if (recievedText != "")
        {
            Console.WriteLine("{0} RECIEVED: " + recievedText, DateTime.Now);
        }

        return recievedText;
    }
</code>```

HTML

```<code><html>
    <head>
        <title>http</title>
        <meta charset="utf-8">
        <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
        <style>

            body{
        font-size: 12px;
        font-family: Arial;
        }

        legend{
            font-weight: bold;
            font-size: 14px !important;
        }

        fieldset{
            width:200px;
            margin: 0;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-right: -50%;
            transform: translate(-50%, -50%) }

        .wrapper{
            width: 100%;
        }

        </style>

        <script language="javascript">

        //<!-- Create variable timer -->
            var timer;

        //<!-- Create Fucntion CheckOne -->
        /*
            Wannneer de functie aangroepen word, word eerst de timeout van de variable timer geleegd.
            Daarna word er een timeout ingesteld van 2000 (2sec). Die timeout wordt ingeschakeld nadat het textveld niet meer actief beschouwd word(niet meer gebruikt word, de focus blijft wel op het veld.).
            Na die 2 seconden krijgt de volgende textbox de focus met de zelfde manier maar onder een andere functie.
            Zodra hier ook de 2 seconden om zijn verspringt de focus weer maar nu naar een sumbit (verzenden) knop. Dit is gedaan omdat je dan makkelijk op een OK knop kan drukken op het apparaat.
        */

            function CheckOne() {
                 clearTimeout(timer)
                 timer = setTimeout(function(){
                     document.getElementById("two").focus();
                     //clearTimeout(timer);
                 }, 750)
            }

            function CheckTwo(){
                clearTimeout(timer);
                timer = setTimeout(function(){
                     document.getElementById("sub").focus();
                 }, 750)
            }

        </script>

    </head>

    <body>

    <div class="wrapper">
        <fieldset>
            <legend>HttpListener </legend><br/>
            <form id="searchForm" action="http://localhost:8100/myForm/doSomething" >
                Locatienummer: <br />
                <input type="text" id="one" onkeyup="CheckOne()" name="locatienummer"><br />
                Bonnummer: <br />
                <input type="text" id="two" onkeyup="CheckTwo()" name="bonnummer"><br /><br />
                <input id="sub" type="submit" value="Verzenden" />
            </form>
        </fieldset>
    </div>
    <!-- Include the needed files-->

        <script>
    $("#searchForm").submit(function (event)
    {
        // Stop form from submitting normally
        event.preventDefault();

        // Get some values from elements on the page:
        var $form = $(this),

        locatieValue = $form.find("input[name='locatienummer']").val(),
        bonValue = $form.find("input[name='bonnummer']").val(),

        url = $form.attr("action");

        // Send the data using post
        $.post(url, { a: locatieValue, b: bonValue });

    });
        </script>

    </body>
</html>
</code>```

答: I got the same exception today and the cause of my case is that I stopped the listener before I tried to write to the HttpResponseStream. The trick is to always write your response first right after getting the listener context.

Body:
Just working on a nice and simple HttpListener and all of the sudden this exception pops-up.

An operation was attempted on a nonexistent network connection.

Look hours for a solution and could not find one. The code crashed as soon as i submit data from the webpage to the HttpListener.
Can someone please explain to me how i can fix this issue?

The Code is below:

C#

public static void StartListening()
    {

        Stream ouputStream;

        HttpListener listener = new HttpListener();
        SetPrefixes(listener);

        if (listener.Prefixes.Count > 0)
        {
            listener.Start();

            Console.WriteLine("HttpClient Started");

            while(true)
            {
                HttpListenerContext context = listener.GetContext();
                HttpListenerRequest request= context.Request;
                HttpListenerResponse response = context.Response;

                string html = Properties.Resources.index;
                byte[] webPageBuffer = Encoding.UTF8.GetBytes(html);

                response.ContentLength64 = webPageBuffer.Length;
                ouputStream = response.OutputStream;
                ouputStream.Write(webPageBuffer, 0, webPageBuffer.Length);

                ouputStream.Flush();

                Common.Wait(2000);

                String url = request.RawUrl;
                String[] queryStringArray = url.Split('/');
                String postedtext = GetPostedText(request);

                byte[] buffer = null;

                // Lots of if statements because a switch would not work here.
                if(queryStringArray[0] == "myForm")
                {
                    buffer = System.Text.Encoding.UTF8.GetBytes("I recieved myForm");
                }
                if(queryStringArray[1] == "doSomething")
                {
                    buffer = System.Text.Encoding.UTF8.GetBytes("I recieved doSomething");
                }
                if(buffer != null)
                {
                    response.AddHeader("Cache-Control", "no-cache");
                    response.AddHeader("Acces-Control-Allow-Origin","*");

                    response.ContentLength64 = buffer.Length;
                    ouputStream = response.OutputStream;
                    ouputStream.Write(buffer, 0, buffer.Length);
                    ouputStream.Close();
                }
            }
        }
    }

    private static void SetContext(HttpListenerContext context, Stream ouputStream)
    {
        // De GetContext methode blokkeert terwijl die wacht op een aanvraag(request)

    }

    private static void SetPrefixes(HttpListener listener)
    {
        String[] prefixes = new String[] { "http://localhost:8100/", "http://192.168.33.28:8000/" };

        int i = 0;

        foreach (string s in prefixes)
        {
            listener.Prefixes.Add(s);
            i++;
        }
    }

    private static string GetPostedText(HttpListenerRequest request)
    {
        string recievedText;

        using(StreamReader reader = new StreamReader(request.InputStream, request.ContentEncoding))
        {
            recievedText= reader.ReadToEnd();
        }

        if (recievedText != "")
        {
            Console.WriteLine("{0} RECIEVED: " + recievedText, DateTime.Now);
        }

        return recievedText;
    }

HTML

        <title>http</title>
        <meta charset="utf-8">

        <fieldset>
            <legend>HttpListener </legend>

            <form id="searchForm" action="http://localhost:8100/myForm/doSomething" >
                Locatienummer:

                <input type="text" id="one" onkeyup="CheckOne()" name="locatienummer">

                Bonnummer:

                <input type="text" id="two" onkeyup="CheckTwo()" name="bonnummer">

                <input id="sub" type="submit" value="Verzenden" />
            </form>
        </fieldset>


问:
Why is the following code throws undefined index while uploading file in PHP?
Marking the question as duplicate is futile, cause I've referred all such questions on SO and none of them did provide a solution.

```<code><?php
if(isset($_POST['submit'])){
$name=$_FILES['filedoc']['name'];
$temp_name=$_FILES['filedoc']['tmp_name'];
if(isset($name)){
    if(!empty($name)){
        $file=file_get_contents($temp_name);
        }
    }
else echo"Please upload file";

echo "<form action=\"";echo htmlentities($_SERVER["PHP_SELF"]);echo "\" method=\"post\">
    <h2>New Paste</h2>
    <label> Upload File?  <input type = \"file\" name = \"filedoc\"/></label><br><span class=\"error\">";echo $fileErr;echo"</span><br>
    <input id=\"button\"class=\"red\" type =\"submit\" class=\"red\" name=\"submit\" value = \"Paste\"/><br><span class=\"error\">";echo $submitErr;echo "</span>
    </form>";
}
?>
</code>```

Form is being displayed correctly. So there are no errors in the second part. But then, I get this error ( ! ) Notice: Undefined index: filedoc in path of the file

答: form attribute enctype="multipart/form-data" is missing

Body:
Marking the question as duplicate is futile, cause I've referred all such questions on SO and none of them did provide a solution.

<?php
if(isset($_POST['submit'])){
$name=$_FILES['filedoc']['name'];
$temp_name=$_FILES['filedoc']['tmp_name'];
if(isset($name)){
    if(!empty($name)){
        $file=file_get_contents($temp_name);
        }
    }
else echo"Please upload file";

echo "<form action=\"";echo htmlentities($_SERVER["PHP_SELF"]);echo "\" method=\"post\">

New Paste

     Upload File?  <input type = \"file\" name = \"filedoc\"/>
";echo $fileErr;echo"

    <input id=\"button\"class=\"red\" type =\"submit\" class=\"red\" name=\"submit\" value = \"Paste\"/>
";echo $submitErr;echo "
    </form>";
}
?>

Form is being displayed correctly. So there are no errors in the second part. But then, I get this error ( ! ) Notice: Undefined index: filedoc in path of the file


问:
Check for value of multiple properties only if they exist in Neo4j
I have nodes of type x with some properties.
I am trying to form a query that checks if a given set of properties exist in x, and if they do, compare each them with a value and then return the relevant node. The psuedo code would be something like this:-

```<code>match(x)
if exist(x.a, x.b)
   then if(x.a==1 and x.b==2)
         return x
else if exist(x.a)
   then if(x.a==1)
         return x
else if exist(x.b)
   then if(x.b==1)
         return x
</code>```

I have tried :-

```<code>MATCH (x) WHERE exists(x.a) and ('high' IN (x.a)) and exists(x.b) and ('high' IN (x.b)) RETURN x
</code>```

and:-

```<code>match(x) where x.a='high' and x.b='high' return x
</code>```

But the problem with both these queries is that if, say 'a' is not a property in x and 'b' is, it returns null without giving a result based on at least the value of 'b'. I am assuming that is because of the and clause, but I cant find an alternative.
I am using neo4j 3.1.3

答:
The UNION operator will help out in this case, making the query something like this:-

```<code>match(x) where x.a='high' return x union match(x) where x.b='high' return x
</code>```

Got the idea from Tom's answer above!

Body:
I have nodes of type x with some properties.
I am trying to form a query that checks if a given set of properties exist in x, and if they do, compare each them with a value and then return the relevant node. The psuedo code would be something like this:-

match(x)
if exist(x.a, x.b)
   then if(x.a==1 and x.b==2)
         return x
else if exist(x.a)
   then if(x.a==1)
         return x
else if exist(x.b)
   then if(x.b==1)
         return x

I have tried :-

MATCH (x) WHERE exists(x.a) and ('high' IN (x.a)) and exists(x.b) and ('high' IN (x.b)) RETURN x

and:-

match(x) where x.a='high' and x.b='high' return x

But the problem with both these queries is that if, say 'a' is not a property in x and 'b' is, it returns null without giving a result based on at least the value of 'b'. I am assuming that is because of the and clause, but I cant find an alternative.
I am using neo4j 3.1.3

Body:
The UNION operator will help out in this case, making the query something like this:-

match(x) where x.a='high' return x union match(x) where x.b='high' return x

Got the idea from Tom's answer above!


问:
Android: weird NullPointerException in ImageView widget
Something a bit weird is happening in my code and I do not understand what is it...

I have some Imageviews, 4 of them, that can be clicked in order to launch the CropActivity, crop an image and the cropped image shall be displayed in the clicked ImageView.

So, to find out which of the 4 ImageViews was clicked I do like this:

```<code>public void onImageViewClicked(View v){
        String tag = v.getTag().toString();
        switch (tag){
            case "imgvW_1":
                this.clickedImgVw = (ImageView) findViewById(R.id.imgvW_1);
                break;
            case "imgvW_2":
                this.clickedImgVw = (ImageView) findViewById(R.id.imgvW_2);
                break;
            case "imgvW_3":
                this.clickedImgVw = (ImageView) findViewById(R.id.imgvW_3);
                break;
            case "imgvW_4":
                this.clickedImgVw = (ImageView) findViewById(R.id.imgvW_4);
                break;

        }

    }
</code>```

So now...If I am correct....the clicked ImageView is stored in clickedImgVw.....

The problem is that...when I try to access clickedImgVw in onActivityResult, after the cropping, I get NullPointerException:

```<code>@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0 && resultCode == RESULT_OK){
            ImageCropFunction();
        }
        else if (requestCode == 2) {
            if (data != null) {
                imgUri = data.getData();
                ImageCropFunction();
            }
        }
        else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            if (data != null) {

                CropImage.ActivityResult result = CropImage.getActivityResult(data);

//THIS LINE HERE GIVES NULLPOINTEREXCEPTION ---------
                    String tag = clickedImgVw.getTag().toString();
//THIS LINE HERE GIVES NULLPOINTEREXCEPTION ---------

                if (resultCode == RESULT_OK) {
                    Uri resultUri = result.getUri();
                    DisplayImageOptions options = new DisplayImageOptions.Builder()
                            .displayer(new RoundedBitmapDisplayer(10))
                            .build();
                   imageLoader.displayImage(String.valueOf(resultUri),clickedImgVw, options);

                }
            }
        }
    }
</code>```

What is it going on here?, What is wrong here?

* ------- EDIT --------- *

After some debug, I have noticed that the variable named tag changes its value on run time.

I have some screencaps showing it during the same debug run....when the application enters in a class named AppCompatViewInflater.java the variable tab loses its value

Before tag gets a value:

After tag gets a value:

After entering AppCompatViewInflater.java:

答:
Activity.class

```<code>public void onImageViewClicked(View v){
    String tag = v.getTag().toString();
    v.setTag("imgvW_1");
    switch (tag){
        case "imgvW_1":
            this.clickedImgVw = (ImageView) findViewById(R.id.imgvW_1);
            this.clickedImgVw.setTag("imgvW_1");
            break;
        case "imgvW_2":
            this.clickedImgVw = (ImageView) findViewById(R.id.imgvW_2);
            this.clickedImgVw.setTag("imgvW_2");
            break;
        case "imgvW_3":
            this.clickedImgVw = (ImageView) findViewById(R.id.imgvW_3);
            this.clickedImgVw.setTag("imgvW_3");
            break;
        case "imgvW_4":
            this.clickedImgVw = (ImageView) findViewById(R.id.imgvW_4);
            this.clickedImgVw.setTag("imgvW_4");
            break;

    }

}
</code>```

Body:
Something a bit weird is happening in my code and I do not understand what is it...

I have some Imageviews, 4 of them, that can be clicked in order to launch the CropActivity, crop an image and the cropped image shall be displayed in the clicked ImageView.

So, to find out which of the 4 ImageViews was clicked I do like this:

public void onImageViewClicked(View v){
        String tag = v.getTag().toString();
        switch (tag){
            case "imgvW_1":
                this.clickedImgVw = (ImageView) findViewById(R.id.imgvW_1);
                break;
            case "imgvW_2":
                this.clickedImgVw = (ImageView) findViewById(R.id.imgvW_2);
                break;
            case "imgvW_3":
                this.clickedImgVw = (ImageView) findViewById(R.id.imgvW_3);
                break;
            case "imgvW_4":
                this.clickedImgVw = (ImageView) findViewById(R.id.imgvW_4);
                break;

        }

    }

So now...If I am correct....the clicked ImageView is stored in clickedImgVw.....

The problem is that...when I try to access clickedImgVw in onActivityResult, after the cropping, I get NullPointerException:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0 && resultCode == RESULT_OK){
            ImageCropFunction();
        }
        else if (requestCode == 2) {
            if (data != null) {
                imgUri = data.getData();
                ImageCropFunction();
            }
        }
        else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            if (data != null) {

                CropImage.ActivityResult result = CropImage.getActivityResult(data);

//THIS LINE HERE GIVES NULLPOINTEREXCEPTION ---------
                    String tag = clickedImgVw.getTag().toString();
//THIS LINE HERE GIVES NULLPOINTEREXCEPTION ---------

                if (resultCode == RESULT_OK) {
                    Uri resultUri = result.getUri();
                    DisplayImageOptions options = new DisplayImageOptions.Builder()
                            .displayer(new RoundedBitmapDisplayer(10))
                            .build();
                   imageLoader.displayImage(String.valueOf(resultUri),clickedImgVw, options);

                }
            }
        }
    }

What is it going on here?, What is wrong here?

* ------- EDIT --------- *

After some debug, I have noticed that the variable named tag changes its value on run time.

I have some screencaps showing it during the same debug run....when the application enters in a class named AppCompatViewInflater.java the variable tab loses its value

Before tag gets a value:

After tag gets a value:

After entering AppCompatViewInflater.java:

Body:
Activity.class

public void onImageViewClicked(View v){
    String tag = v.getTag().toString();
    v.setTag("imgvW_1");
    switch (tag){
        case "imgvW_1":
            this.clickedImgVw = (ImageView) findViewById(R.id.imgvW_1);
            this.clickedImgVw.setTag("imgvW_1");
            break;
        case "imgvW_2":
            this.clickedImgVw = (ImageView) findViewById(R.id.imgvW_2);
            this.clickedImgVw.setTag("imgvW_2");
            break;
        case "imgvW_3":
            this.clickedImgVw = (ImageView) findViewById(R.id.imgvW_3);
            this.clickedImgVw.setTag("imgvW_3");
            break;
        case "imgvW_4":
            this.clickedImgVw = (ImageView) findViewById(R.id.imgvW_4);
            this.clickedImgVw.setTag("imgvW_4");
            break;

    }

}


问:
Elasticsearch full text search: How to return 0 hits if user query has a word thats missing/unknown in indices
How to make elasticsearch return 0 hits if query string from user has a word thats missing/unknown in indices?</p>

答: you could change the default_operator if your query to AND, see the documentation about the query string query


问:
I want to get all data in elasticsearch 5.4
I used size :0 in Elasticsearch 2.x but now in Elasticsearch 5.4 this can not be used.

How do I get the same effect as size: 0 in Elasticsearch 5.4 ?

答:
Use ES's snapshot and restore instead :

https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html

Do note that a snapshot of an index created in 1.X cannot be restored to 5.X


问:
Firebase storage error 403 image retrieve
With this code i would like to display user's image

where taskImg is a dictionary string

```<code>    let url = NSURL(string:taskImg!)
    let data = NSData(contentsOf:url! as URL)

    if data != nil {
        imagePicked.image = UIImage(data:data! as Data)
    }
</code>```

I got:

```<code>ResponseErrorCode=403
</code>```

If I print the URL, it is showing correctly, but when I used it in a browser, it gives the 403 error response.

The view controller correctly see my authenticated user.

The only way to got it working is to set rules of Firebase to doesn't require authentication but i don't want this. What seems to be wrong?

答:
There are 3 potential considerations (even if they seem obvious, they may lead you to an answer :)

Are these images set up in the same account that you have your billing set up? If you put the images on Firebase storage for a different account that doesn't have billing active, you wont be able to set up the Encryption keys for testing (Settings (gear icon) > Users and permission > Encryption keys)

Do you have an API key active and correctly configured? If so, can you test this via API calls?

As far as what you mentioned about the user being authenticated, what do you have set up for your Sign-In Method (from the Authentication section)? Have you checked any whitelisting properties that may be needed?

Hope this helps

Body:
With this code i would like to display user's image

where taskImg is a dictionary string

    let url = NSURL(string:taskImg!)
    let data = NSData(contentsOf:url! as URL)

    if data != nil {
        imagePicked.image = UIImage(data:data! as Data)
    }

I got:

ResponseErrorCode=403

If I print the URL, it is showing correctly, but when I used it in a browser, it gives the 403 error response.

The view controller correctly see my authenticated user.

The only way to got it working is to set rules of Firebase to doesn't require authentication but i don't want this. What seems to be wrong?


问:
Spotify API automated initial authorization
I'm making a personal smart mirror and i'm looking to integrate the spotify API to display my 'currently playing' track. However, I've noticed that in the authorization process, you need to physically click log in and authorize the app in order to get the credentials required to move forward in obtaining your data. Could this be automated/require no user interaction?

I am referring to step 1 of the api authorization guide.

Many thanks.

答:
If you are using this for a personal smart mirror you shouldn't have a problem. You only need to authorize by clicking a button in a browser one time and will be able to make all API calls afterward without needing to click anything.

Specifically, after you do in step 3 of the authorization flow you will be given a refresh token. After the authorization token expires you can use the refresh token to refresh the authorization automatically without clicking anything.

From their documentation:

Accessing your data without showing a login form

I want to interact with the web API and show some data on my website. I see that the endpoints I need authorization, but I don’t need/want a login window to pop-up, because I want to grant my own app access to my own playlists once. Is there any way of doing this?

You basically need an access token and a refresh token issued for your
  user account. For obtaining a pair of access token / refresh token you
  need to follow the Authorization Code Flow (if you need a certain
  scope to be approved) or Client Credentials (if you just need to sign
  your request, like when fetching a certain playlist). Once you obtain
  them, you can use your access token and refresh it when it expires
  without having to show any login form.

If its not for you personally you could jump through hoops and write code that fakes being a web browser, perhaps using something like curl or selenium but odds are it is against their terms of service and are if you get caught they'll ban you.


问:
Angular.js ng-repeat filter without knowing key
I am having troubles filtering my JSON file in the ng-repeat.

Here is the JSON data which is in my code is coming from Firebase

```<code>{
"850": {
    "buttonText": "Button TST",
    "description": "",
    "documentNumber": "850",
    "language": "fi",
    "special": false,
    "newOrder": 99000500850
},
"851": {
    "buttonText": "eng ButtonTXT",
    "description": "I would like to get this",
    "documentNumber": "851",
    "language": "en",
    "special": false,
    "newOrder": 99000500851
},
"852": {
    "buttonText": "MORE FInnish button text",
    "description": "Oh my",
    "documentNumber": "852",
    "language": "fi",
    "special": false,
    "newOrder": 99000500015
       }
}
</code>```

The JSON-data is stored into $ctrl.documentMatrixFirebase. Here is the Angular.js HTML. It is component which does what I want to except the filtering part.

```<code>  <google-docs-card
  layout="column"
  ng-repeat="docButton in $ctrl.documentMatrixFirebase |
  orderObjectBy:'newOrder' track by docButton.newOrder "
  document-data="docButton"
  subject="$ctrl.subject"
  id="docnum_{{docButton.documentNumber}}"></google-docs-card>
</code>```

Here is the code I tried to use for filtering without luck.

```<code><google-docs-card
  layout="column"
  ng-repeat="docButton in $ctrl.documentMatrixFirebase |
  filter:docButton.language:'en' |
  orderObjectBy:'newOrder' track by docButton.newOrder "
  document-data="docButton"
  subject="$ctrl.subject"
  id="docnum_{{docButton.documentNumber}}"></google-docs-card>
</code>```

If possible, I would like to avoid adding custom filters for such a simple job.

答:
Looks like that AngularJs to Array filter solved the problem:
https://github.com/petebacondarwin/angular-toArrayFilter

I installed the array filter according the instructions and used it in the HTML like this.

```<code><google-docs-card
  layout="column"
  ng-repeat="docButton in $ctrl.documentMatrixFirebase
  |  toArray:false |  filter: {language: 'en'}
  | orderObjectBy:'newOrder' track by docButton.newOrder"
  document-data="docButton"
  subject="$ctrl.subject"
  id="docnum_{{docButton.documentNumber}}"></google-docs-card>
</code>```

Body:
I am having troubles filtering my JSON file in the ng-repeat.

Here is the JSON data which is in my code is coming from Firebase

{
"850": {
    "buttonText": "Button TST",
    "description": "",
    "documentNumber": "850",
    "language": "fi",
    "special": false,
    "newOrder": 99000500850
},
"851": {
    "buttonText": "eng ButtonTXT",
    "description": "I would like to get this",
    "documentNumber": "851",
    "language": "en",
    "special": false,
    "newOrder": 99000500851
},
"852": {
    "buttonText": "MORE FInnish button text",
    "description": "Oh my",
    "documentNumber": "852",
    "language": "fi",
    "special": false,
    "newOrder": 99000500015
       }
}

The JSON-data is stored into $ctrl.documentMatrixFirebase. Here is the Angular.js HTML. It is component which does what I want to except the filtering part.

  <google-docs-card
  layout="column"
  ng-repeat="docButton in $ctrl.documentMatrixFirebase |
  orderObjectBy:'newOrder' track by docButton.newOrder "
  document-data="docButton"
  subject="$ctrl.subject"
  id="docnum_{{docButton.documentNumber}}"></google-docs-card>

Here is the code I tried to use for filtering without luck.

<google-docs-card
  layout="column"
  ng-repeat="docButton in $ctrl.documentMatrixFirebase |
  filter:docButton.language:'en' |
  orderObjectBy:'newOrder' track by docButton.newOrder "
  document-data="docButton"
  subject="$ctrl.subject"
  id="docnum_{{docButton.documentNumber}}"></google-docs-card>

If possible, I would like to avoid adding custom filters for such a simple job.

Body:
Looks like that AngularJs to Array filter solved the problem:
https://github.com/petebacondarwin/angular-toArrayFilter

I installed the array filter according the instructions and used it in the HTML like this.

<google-docs-card
  layout="column"
  ng-repeat="docButton in $ctrl.documentMatrixFirebase
  |  toArray:false |  filter: {language: 'en'}
  | orderObjectBy:'newOrder' track by docButton.newOrder"
  document-data="docButton"
  subject="$ctrl.subject"
  id="docnum_{{docButton.documentNumber}}"></google-docs-card>


问:
hello at the time of installation magento show error Installation is incomplete. Check the console log for errors before trying again
Console Log show error
[ERROR] LogicException: Unknown module in the requested list: 'Magento_BundleSampleData' in C:\xampp\htdocs\Magento2\setup\src\Magento\Setup\Model\Installer.php:417 Stack trace: #0 C:\xampp\htdocs\Magento2\setup\src\Magento\Setup\Model\Installer.php(378): Magento\Setup\Model\Installer->readListOfModules(Array, Array, 'enable_modules') #1 C:\xampp\htdocs\Magento2\setup\src\Magento\Setup\Model\Installer.php(325): Magento\Setup\Model\Installer->createModulesConfig(Array) #2 C:\xampp\htdocs\Magento2\setup\src\Magento\Setup\Controller\Install.php(103): Magento\Setup\Model\Installer->install(Array) #3 C:\xampp\htdocs\Magento2\vendor\zendframework\zend-mvc\src\Controller\AbstractActionController.php(82): Magento\Setup\Controller\Install->startAction() #4 [internal function]: Zend\Mvc\Controller\AbstractActionController->onDispatch(Object(Zend\Mvc\MvcEvent)) #5 C:\xampp\htdocs\Magento2\vendor\zendframework\zend-eventmanager\src\EventManager.php(444): call_user_func(Array, Object(Zend\Mvc\MvcEvent)) #6 C:\xampp\htdocs\Magento2\vendor\zendframework\zend-eventmanager\src\EventManager.php(205): Zend\EventManager\EventManager->triggerListeners('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure)) #7 C:\xampp\htdocs\Magento2\vendor\zendframework\zend-mvc\src\Controller\AbstractController.php(118): Zend\EventManager\EventManager->trigger('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure)) #8 C:\xampp\htdocs\Magento2\vendor\zendframework\zend-mvc\src\DispatchListener.php(93): Zend\Mvc\Controller\AbstractController->dispatch(Object(Zend\Http\PhpEnvironment\Request), Object(Zend\Http\PhpEnvironment\Response)) #9 [internal function]: Zend\Mvc\DispatchListener->onDispatch(Object(Zend\Mvc\MvcEvent)) #10 C:\xampp\htdocs\Magento2\vendor\zendframework\zend-eventmanager\src\EventManager.php(444): call_user_func(Array, Object(Zend\Mvc\MvcEvent)) #11 C:\xampp\htdocs\Magento2\vendor\zendframework\zend-eventmanager\src\EventManager.php(205): Zend\EventManager\EventManager->triggerListeners('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure)) #12 C:\xampp\htdocs\Magento2\vendor\zendframework\zend-mvc\src\Application.php(314): Zend\EventManager\EventManager->trigger('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure)) #13 C:\xampp\htdocs\Magento2\setup\index.php(31): Zend\Mvc\Application->run() #14 {main}</p>

答:
You can disable this module by going to "Customize Your Store" "Advanced Modules Configurations" and uncheck "Magento_BundleSampleData"

If you would still like to install with this module i would advise you to try clearing all your cache maybe restart apache and mysql and make sure to be in incognito.


问:
How to Drop a Duplicates Column in dataframe while retaining the Unique Column including the only one column among duplicates
I am trying to drop the duplicate column while retaining only the unique columns and only one column among the duplicates after joining.

For Example:
Duplicate DataFrame

```<code>root
|-- id: string (nullable = true)
|-- name: string (nullable = true)
|-- loc: string (nullable = true)
|-- sal: string (nullable = true)
|-- name: string (nullable = true)
|-- loc: string (nullable = true)
|-- sal: string (nullable = true)

After removing duplicates, the output should be

root
|-- id: string (nullable = true)
|-- name: string (nullable = true)
|-- loc: string (nullable = true)
|-- sal: string (nullable = true)
</code>```

Any help will be appreciated?

答:
```<code>//For exemple
val dataFrame = sparkSession.sql("SELECT .....")
dataFrame .distinct() //since 2.0.0
//or
dataFrame.dropDuplicates()
//or
dataFrame.dropDuplicates(colNames)
</code>```

Body:
I am trying to drop the duplicate column while retaining only the unique columns and only one column among the duplicates after joining.

For Example:
Duplicate DataFrame

root
|-- id: string (nullable = true)
|-- name: string (nullable = true)
|-- loc: string (nullable = true)
|-- sal: string (nullable = true)
|-- name: string (nullable = true)
|-- loc: string (nullable = true)
|-- sal: string (nullable = true)

After removing duplicates, the output should be

root
|-- id: string (nullable = true)
|-- name: string (nullable = true)
|-- loc: string (nullable = true)
|-- sal: string (nullable = true)

Any help will be appreciated?


问:
Which characters are valid in CSS class names/selectors?
What characters/symbols are allowed within the CSS class selectors?

I know that the following characters are invalid, but what characters are valid?

~ ! @ $ % ^ & * ( ) + = , . / ' ; : " ? > < [ ] \ { } | ` #
```

答:
You can check directly at the CSS grammar.

Basically1, a name must begin with an underscore (_), a hyphen (-), or a letter(a–z), followed by any number of hyphens, underscores, letters, or numbers. There is a catch: if the first character is a hyphen, the second character must2 be a  letter or underscore, and the name must be at least 2 characters long.

-?[_a-zA-Z]+[_a-zA-Z0-9-]*
```

In short, the previous rule translates to the following, extracted from the W3C specification:

In CSS, identifiers (including element names, classes, and IDs in
selectors) can contain only the characters [a-z0-9] and ISO 10646
characters U+00A0 and higher, plus the hyphen (-) and the underscore
(_); they cannot start with a digit, or a hyphen followed by a digit.
Identifiers can also contain escaped characters and any ISO 10646
character as a numeric code (see next item). For instance, the
identifier "B&W?" may be written as "B&W?" or "B\26 W\3F".

Identifiers beginning with a hyphen or underscore are typically reserved for browser-specific extensions, as in -moz-opacity.

1 It's all made a bit more complicated by the inclusion of escaped Unicode characters (that no one really uses).

2 Note that, according to the grammar I linked, a rule starting with two hyphens, e.g., --indent1, is invalid.  However, I'm pretty sure I've seen this in practice.

OwnerDisplayName: Darryl Hein

Body:
You can check directly at the CSS grammar.

Basically1, a name must begin with an underscore (_), a hyphen (-), or a letter(a–z), followed by any number of hyphens, underscores, letters, or numbers. There is a catch: if the first character is a hyphen, the second character must2 be a  letter or underscore, and the name must be at least 2 characters long.

-?[_a-zA-Z]+[_a-zA-Z0-9-]*

In short, the previous rule translates to the following, extracted from the W3C specification:

In CSS, identifiers (including element names, classes, and IDs in
selectors) can contain only the characters [a-z0-9] and ISO 10646
characters U+00A0 and higher, plus the hyphen (-) and the underscore
(_); they cannot start with a digit, or a hyphen followed by a digit.
Identifiers can also contain escaped characters and any ISO 10646
character as a numeric code (see next item). For instance, the
identifier "B&W?" may be written as "B&W?" or "B\26 W\3F".

Identifiers beginning with a hyphen or underscore are typically reserved for browser-specific extensions, as in -moz-opacity.

1 It's all made a bit more complicated by the inclusion of escaped Unicode characters (that no one really uses).

2 Note that, according to the grammar I linked, a rule starting with two hyphens, e.g., --indent1, is invalid.  However, I'm pretty sure I've seen this in practice.

OwnerDisplayName: Triptych

LastEditorDisplayName: Triptych


问:
NavigationBar hidden in detailViewController when presented modally
I am basically presenting my DetailViewController as modalView.In the modalView navigation bar is never visible, though I am not hiding it any where.Please help!</p>

答:
```<code>WriteReviewController *newReview = [[WriteReviewController alloc] initWithNibName:@"WriteReviewController" bundle:nil];

UINavigationController *modalNavController = [[UINavigationController alloc] initWithRootViewController:newReview];

// This is intended to be presented in another view controller class
modalNavController.navigationBar.barStyle = UIBarStyleDefault;
[self.parentViewController presentModalViewController:modalNavController animated:YES];
[modalNavController release];
</code>```

This code worked for me

Body:
WriteReviewController *newReview = [[WriteReviewController alloc] initWithNibName:@"WriteReviewController" bundle:nil];

UINavigationController *modalNavController = [[UINavigationController alloc] initWithRootViewController:newReview];

// This is intended to be presented in another view controller class
modalNavController.navigationBar.barStyle = UIBarStyleDefault;
[self.parentViewController presentModalViewController:modalNavController animated:YES];
[modalNavController release];

This code worked for me