问:
How can I get user id at the time of user creation in Firebase
In my project only Admin can add user to firebase.
At the time of creation i want to get user id because i want to set up profile of that user in Firebase Database.

```<code>public void addNewFaculty(View view){
    String name,email,password,rePassword;
    name = txtname.getText().toString();
    email = txtEmail.getText().toString().trim();
    password = txtPassword.getText().toString().trim();
    rePassword = txtRepassword.getText().toString().trim();
    if(password.equals(rePassword))
    {
        Toast.makeText(this, "Password is not match", Toast.LENGTH_SHORT).show();
        return;
    }
    databaseReference= FirebaseDatabase.getInstance().getReference();
    firebaseUser = firebaseAuth.getCurrentUser();
    String id= firebaseUser.getUid();
    databaseReference = databaseReference.child("Profile").child(id);
    databaseReference.child("Name").setValue(name);
    // and some other things
    firebaseAuth.createUserWithEmailAndPassword(email,password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if(task.isSuccessful()){
                        Toast.makeText(getApplicationContext(), "Employee Added Successfully", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(getApplicationContext(), "Please try Again", Toast.LENGTH_SHORT).show();
                    }
                }
            });

}
</code>```

And my firebase structure is
And my firebase structure is given below. I want to get user id at the time of user creation
Here is my Firebase Auth Image

And want to set id here

答:
When You create a user in firebase auth, it automatically log in. Therefore you can get your id in onComplete(), if method as:</p>

```<code>    if(task.isSuccessful()){
       String id1 = firebaseAuth.getCurrentUser().getUid();
       //For adding into database

       databaseReference = databaseReference.child("Profile").child(id1);
       databaseReference.child("Name").setValue(name);

       Toast.makeText(getApplicationContext(), "Employee Added Successfully", Toast.LENGTH_SHORT).show();
    }else{
       Toast.makeText(getApplicationContext(), "Please try Again", Toast.LENGTH_SHORT).show();
    }
</code>```

Body:
In my project only Admin can add user to firebase.
At the time of creation i want to get user id because i want to set up profile of that user in Firebase Database.

public void addNewFaculty(View view){
    String name,email,password,rePassword;
    name = txtname.getText().toString();
    email = txtEmail.getText().toString().trim();
    password = txtPassword.getText().toString().trim();
    rePassword = txtRepassword.getText().toString().trim();
    if(password.equals(rePassword))
    {
        Toast.makeText(this, "Password is not match", Toast.LENGTH_SHORT).show();
        return;
    }
    databaseReference= FirebaseDatabase.getInstance().getReference();
    firebaseUser = firebaseAuth.getCurrentUser();
    String id= firebaseUser.getUid();
    databaseReference = databaseReference.child("Profile").child(id);
    databaseReference.child("Name").setValue(name);
    // and some other things
    firebaseAuth.createUserWithEmailAndPassword(email,password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if(task.isSuccessful()){
                        Toast.makeText(getApplicationContext(), "Employee Added Successfully", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(getApplicationContext(), "Please try Again", Toast.LENGTH_SHORT).show();
                    }
                }
            });

}

And my firebase structure is
And my firebase structure is given below. I want to get user id at the time of user creation
Here is my Firebase Auth Image

And want to set id here

Body:
When You create a user in firebase auth, it automatically log in. Therefore you can get your id in onComplete(), if method as:

    if(task.isSuccessful()){
       String id1 = firebaseAuth.getCurrentUser().getUid();
       //For adding into database

       databaseReference = databaseReference.child("Profile").child(id1);
       databaseReference.child("Name").setValue(name);

       Toast.makeText(getApplicationContext(), "Employee Added Successfully", Toast.LENGTH_SHORT).show();
    }else{
       Toast.makeText(getApplicationContext(), "Please try Again", Toast.LENGTH_SHORT).show();
    }


来源: stackexchange

问:
How to implement contract testing when kafka is involved in microservice architecture?
I am currently working on a project where we have kafka implementation in micro service architecture. Were you successful in creating contract test cases for mS to kafka topic interaction please using pact-jvm ?

My implementation is microservice1 publishes a message to a REST Client which in turn posts the message to Kafka Topic. microservice2 uses GET method to retrieve messages from the Kafka Topic.

答:
Pact-JVM supports Message Pacts, which encapsulate a message that is consumed (one way) over some mechanism, normally a message queue. The idea is to test the consumer code can consume the message via a consumer test, and then verify that the provider generates an appropriate message. The actual message queue is not used in the test.

This was originally developed to apply contract tests for micro-services communicating over a Kafka message queue.

The tests are done in two parts, just like Request-Response Pact tests, except the Consumer reads the message during the consumer pact test and if successful a pact file is written. Then the provider code is called to generate a message, and that is compared to what is in the pact file.

The relevant sections of the Pact-JVM docs are:

Gradle Plugin

Maven Plugin

JUnit Example

ContentLicense: CC BY-SA 3.0


问:
ERROR 2003 (HY000): Can't connect to MySQL server on 'x.x.x.x' (110)
I'm trying to establish a basic mysql connection from a google compute engine instance in one project to a google cloud sql instance (2nd generation) in a different project.

I've done this many times before without any problem. You simply add the ip address of the google compute instance to the list of authorized networks for the google cloud sql instance. This has always worked in the past but it is not working now.

The only thing that I can think of which is different about this situation is that I've recently been experimenting with using the cloudsql-proxy to establish a connection from a different gce instance to the same google cloud sql instance. Could this be the problem? Perhaps the google cloud sql instance is getting confused by having to support both connection mechanisms?

I just need the connection to work. Is there a work-around?

答:
There isn't a problem using both modes of connectivity simultaneously.

The only thing I can think of is that you are accidentally using an ephemeral IP addresses for your VMs instead of static, which means the VM may have a different IP address than you expect (after a restart, for example).

If that's not the case, please send a mail to cloud-sql@google.com with a little bit more information (project and database name, project/name/ip of your VM) so that we can figure out what's going on in the backend.


问:
How to config a specific node as a driver node in spark-submit with cluster mode and standalone mode
I have to problem in spark-submit with cluster deploy mode and standalone mode:

How to specify a node as a driver node in spark cluster

in my case, the driver node was assigned dynamically by spark

How to distribute the app automatic from local

in my case, i must deploy the jar of app to every node,because i don't know which node will be the driver node .

PS : My submit command is :
 spark-submit --master spark://master_ip:6066 --class appMainClass --deploy-mode cluster  file:///tmp/spark_app/sparkrun

答:
The --deploy-mode flag determines if the job will be submitted in cluster or client mode.

In cluster mode all the nodes will act as executors. One node will submit the JAR and then you can track the execution using web UI. That particular node will also act as an executor.

In client mode, the node where the spark-submit is invoked will act as the driver. Note that this node will not execute the DAG as this it is designated as a driver for your cluster. All the other nodes will be executors. Again, Web UI will help to see the execution of jobs and other useful information like RDD partitions, cached RDDs size etc.


问:
Is it safe to frequently Compact and Repair Access DB?
I have an Access Database which I populate using a pass through query.

I get specific data from an SQL database and dumps it on Access.

This Access DB is updated weekly but I cannot simply append new data from the previous week because all other past weeks also updates.

What I did is truncate the Access DB and then load everything again.

When I do that, I need to Compact and Repair the DB so that the size doesn't bloat.

My question is, is it ok to do that? Currently I am using the logic posted in this answer.

I have not encountered any problems yet but I just want to make sure and get our access guru's thought about it. Also I'm planning on doing a scheduled run on our server to do the task.

Just need to make sure that it will not get corrupted easily (what is the chance of corrupting the file in the first place?).

If you'll ask, why do I need to do this? Users of data have no access on SQL server.
So I have to pull data for them so they can just connect to Access DB instead.

Just in case you need the code:

```<code>Dim sqlDelete As String
Dim sqlAppend As String

sqlDelete = "DELETE * FROM dbo_Table;"

sqlAppend = "INSERT INTO dbo_Table (Col1,Col2) SELECT Col1,Col2 FROM passThrough;"

With DoCmd
    .SetWarnings False
    .RunSQL sqlDelete

    .RunSQL sqlAppend
    .SetWarnings True
End With

Application.SetOption "Auto Compact", True
</code>```

答:
If you need to truncate the data and load again I would recommend to move all tables, which should be truncated and all temporary tables to separate database.
After separating it will be possible to replace this database with unnecessary data by empty database file when the application starts. Just save a copy of empty database and copy this file over existing database with old data. This should be done before opening any form/recordset based on tables from temp database. It will work faster than C&R each time and more reliable, because sometimes C&R may damage the file.

Template database file also can be stored in main database in Memo field

Body:
I have an Access Database which I populate using a pass through query.

I get specific data from an SQL database and dumps it on Access.

This Access DB is updated weekly but I cannot simply append new data from the previous week because all other past weeks also updates.

What I did is truncate the Access DB and then load everything again.

When I do that, I need to Compact and Repair the DB so that the size doesn't bloat.

My question is, is it ok to do that? Currently I am using the logic posted in this answer.

I have not encountered any problems yet but I just want to make sure and get our access guru's thought about it. Also I'm planning on doing a scheduled run on our server to do the task.

Just need to make sure that it will not get corrupted easily (what is the chance of corrupting the file in the first place?).

If you'll ask, why do I need to do this? Users of data have no access on SQL server.
So I have to pull data for them so they can just connect to Access DB instead.

Just in case you need the code:

Dim sqlDelete As String
Dim sqlAppend As String

sqlDelete = "DELETE * FROM dbo_Table;"

sqlAppend = "INSERT INTO dbo_Table (Col1,Col2) SELECT Col1,Col2 FROM passThrough;"

With DoCmd
    .SetWarnings False
    .RunSQL sqlDelete

    .RunSQL sqlAppend
    .SetWarnings True
End With

Application.SetOption "Auto Compact", True


问:
Creating error/result function in node
I'm having trouble understanding how to create functions that would return in the format of (err, result) for an Express app.

My current db query function is:

```<code>pool.query(
  'SELECT id FROM users WHERE email = ? LIMIT 1',
  [email],
  (results) => { // I'd like this to be (err, results)
    if(results instanceof Error){...}
  }
})
</code>```

In my db.js file, pool looks like this:

```<code>module.exports = {
  query: (query, args, cb) => {
    pool.getConnection( (err, connection) => {
      if(err){
        new Error('No database connections available in pool')
      } else {
        connection.query(query, args, (error, results, fields) => {
          connection.release()
          // I got a MySQL error here and I'd like to handle it in my callback function
          if(error){
            new Error('Bad query')
          } else {
            cb(results)
          }
        })
      }
    })
  }
}
</code>```

For this and other functions, I'd like to return a proper Error if there is one, and have my callback listen for err, result as parameters.

I tried using new Error('Bad query') but that came back as the first variable in my callback no matter what (which is how I ended up with instanceof Error.

How do you structure a callback and response so that your callback can be in the err, result format and check for/handle errors properly on functions you're creating? (I understand how to use it for modules already in this format - I'm talking about writing/formatting your own code.)

Thanks!

答:
You can do it like this:

```<code>module.exports = {
  query: (query, args, cb) => {
    pool.getConnection( (err, connection) => {
      if(err){
        cb(new Error('No database connections available in pool'));
      } else {
        connection.query(query, args, (error, results, fields) => {
          connection.release();
          // I got a MySQL error here and I'd like to handle it in my callback function
          if(error){
            cb(new Error('Bad query'));
          } else {
            cb(null, results);
          }
        });
      }
    });
  }
}
</code>```

You always pass the error value as the first argument to the callback and, if there is a result, you pass it as the second.  Then, within the callback, you check to see if err is non-null and, if so, there is an error.  If it's null, then the second argument contains the result.

Note that by not returning or including the actual err value that the database gave you, you may be hiding useful information (like why the query failed).

Then, where you use this, you do something like this:

```<code>let query = 'SELECT id FROM users WHERE email = ? LIMIT 1';
pool.query(query, [email], (err, result) => {
    if (err) {
        // handle error here
    } else {
        // process result here
    }
});
</code>```

Title: Creating error/result function in node

Body:
I'm having trouble understanding how to create functions that would return in the format of (err, result) for an Express app.

My current db query function is:

pool.query(
  'SELECT id FROM users WHERE email = ? LIMIT 1',
  [email],
  (results) => { // I'd like this to be (err, results)
    if(results instanceof Error){...}
  }
})

In my db.js file, pool looks like this:

module.exports = {
  query: (query, args, cb) => {
    pool.getConnection( (err, connection) => {
      if(err){
        new Error('No database connections available in pool')
      } else {
        connection.query(query, args, (error, results, fields) => {
          connection.release()
          // I got a MySQL error here and I'd like to handle it in my callback function
          if(error){
            new Error('Bad query')
          } else {
            cb(results)
          }
        })
      }
    })
  }
}

For this and other functions, I'd like to return a proper Error if there is one, and have my callback listen for err, result as parameters.

I tried using new Error('Bad query') but that came back as the first variable in my callback no matter what (which is how I ended up with instanceof Error.

How do you structure a callback and response so that your callback can be in the err, result format and check for/handle errors properly on functions you're creating? (I understand how to use it for modules already in this format - I'm talking about writing/formatting your own code.)

Thanks!

Body:
You can do it like this:

module.exports = {
  query: (query, args, cb) => {
    pool.getConnection( (err, connection) => {
      if(err){
        cb(new Error('No database connections available in pool'));
      } else {
        connection.query(query, args, (error, results, fields) => {
          connection.release();
          // I got a MySQL error here and I'd like to handle it in my callback function
          if(error){
            cb(new Error('Bad query'));
          } else {
            cb(null, results);
          }
        });
      }
    });
  }
}

You always pass the error value as the first argument to the callback and, if there is a result, you pass it as the second.  Then, within the callback, you check to see if err is non-null and, if so, there is an error.  If it's null, then the second argument contains the result.

Note that by not returning or including the actual err value that the database gave you, you may be hiding useful information (like why the query failed).

Then, where you use this, you do something like this:

let query = 'SELECT id FROM users WHERE email = ? LIMIT 1';
pool.query(query, [email], (err, result) => {
    if (err) {
        // handle error here
    } else {
        // process result here
    }
});


问:
Is it possible to restrict disabling gps, internet or enabling flight mode
I am developing a mobile application for tracking employee location in ionic.
The issues what I am facing is, users disabling gps / internet or enabling the flight mode. So it's very hard to track their respective location.

Now what I did is, if user turns-off gps/internet. I have created a log file, and send the log to server when he turns on again. I can't do anything specifically for disabling flight mode, so I check the internet/gps only.

Is my method is correct or Is any alternate thing that can be used to restrict disabling gps, internet or enabling flight mode. or it is possible only in native application.

答: In this case you should install your app as device owner. As device owner app you have full control of location, your app can enable it and disable it without user intervention. The problem with airplane mode still remains but you can just use a job service scheduling work with a constraint "network type any", when the connection come back, you can send the log file filled offline. Generally it's better to send more data together using a job compared to send a single location each time to avoid battery drain</p>


问:
android - Place imageview next to two textviews under each other

How do i create above layout in android studio ?

答:
First add  dependencies in your gradle file for circular image view

```<code> compile 'de.hdodenhof:circleimageview:2.1.0'
</code>```

now you can use below code as per your requirement

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

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="3">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/meal_image_order"
            android:layout_width="96dp"
            android:layout_height="96dp"
            android:src="@color/colorAccent"
            app:civ_border_color="@color/colorPrimaryDark"
            app:civ_border_width="2dp" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2"
        android:gravity="center"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tv1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Textview 1" />

        <TextView
            android:id="@+id/tv2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Textview 2" />

    </LinearLayout>
</LinearLayout>
</LinearLayout>
</code>```

sample output

Body:
First add  dependencies in your gradle file for circular image view

 compile 'de.hdodenhof:circleimageview:2.1.0'

now you can use below code as per your requirement

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

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="3">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/meal_image_order"
            android:layout_width="96dp"
            android:layout_height="96dp"
            android:src="@color/colorAccent"
            app:civ_border_color="@color/colorPrimaryDark"
            app:civ_border_width="2dp" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2"
        android:gravity="center"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tv1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Textview 1" />

        <TextView
            android:id="@+id/tv2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Textview 2" />

    </LinearLayout>
</LinearLayout>
</LinearLayout>

sample output


问:
Is declaring the same variable multiple times a good practice
Here is my javascript code:

```<code>(function(){
"use strict";
document.addEventListener("DOMContentLoaded",animations); /*on content loaded */

function animations() {

/*start of animation for the toggle navigation button in smaller view ports*/
(function () {

    var button = document.getElementById('nav-icon');
    button.addEventListener('click', function(){
        if (this.classList.contains('active')===true) {
            this.classList.remove('active');
        }
        else {
            this.classList.add('active');
        }
    })

})();  /*End of the toggle navigation animation*/

/*Start of  scrolling side navigation for smaller view ports*/

(function(){

        var button = document.getElementById('nav-icon');
        var body = document.querySelector('body');
        button.addEventListener('click', function(){
        if (this.classList.contains('active')===true) {
            body.classList.add('active-nav');
        }
        else {
            body.classList.remove('active-nav');
        }

    });

    })(); /*End of scrolling side navigation*/

(function () {
        // body...
        var media = window.matchMedia("(min-width: 992px)");
        var body = document.querySelector('body');
        var button = document.getElementById('nav-icon');
        window.addEventListener('resize',function(){

            if (media.matches) {

                    body.classList.remove('active-nav');

                    if (button.classList.contains('active')===true) {

                        button.classList.remove('active');
                    }

                }

        });

    })();

};

})();
</code>```

As you can see I have declared variables that have exactly the same value multiple times in my code, but they are in different functions. each iife is a seperate animation and has a different functionality although they might share  common elements. However, I wanted to know if this was a good practice. Should I declare common variables in the main function so they might be in the execution context of all the sub functions? Also, please highlight anything that doesnot look good or is not a good practice. Thank you

答:
As others have said, it's fine because of function scope, however, you should know that it's better practice to move these two lines outside of their iife (to about line 4)

```<code>var button = document.getElementById('nav-icon');
var body = document.querySelector('body');
</code>```

So that js only performs the look up once, instead of 3 times. This caches the dom lookup which will improve performance.

Body:
Here is my javascript code:

(function(){
"use strict";
document.addEventListener("DOMContentLoaded",animations); /*on content loaded */

function animations() {

/*start of animation for the toggle navigation button in smaller view ports*/
(function () {

    var button = document.getElementById('nav-icon');
    button.addEventListener('click', function(){
        if (this.classList.contains('active')===true) {
            this.classList.remove('active');
        }
        else {
            this.classList.add('active');
        }
    })

})();  /*End of the toggle navigation animation*/

/*Start of  scrolling side navigation for smaller view ports*/

(function(){

        var button = document.getElementById('nav-icon');
        var body = document.querySelector('body');
        button.addEventListener('click', function(){
        if (this.classList.contains('active')===true) {
            body.classList.add('active-nav');
        }
        else {
            body.classList.remove('active-nav');
        }

    });

    })(); /*End of scrolling side navigation*/

(function () {
        // body...
        var media = window.matchMedia("(min-width: 992px)");
        var body = document.querySelector('body');
        var button = document.getElementById('nav-icon');
        window.addEventListener('resize',function(){

            if (media.matches) {

                    body.classList.remove('active-nav');

                    if (button.classList.contains('active')===true) {

                        button.classList.remove('active');
                    }

                }

        });

    })();

};

})();

As you can see I have declared variables that have exactly the same value multiple times in my code, but they are in different functions. each iife is a seperate animation and has a different functionality although they might share  common elements. However, I wanted to know if this was a good practice. Should I declare common variables in the main function so they might be in the execution context of all the sub functions? Also, please highlight anything that doesnot look good or is not a good practice. Thank you

Body:
As others have said, it's fine because of function scope, however, you should know that it's better practice to move these two lines outside of their iife (to about line 4)

var button = document.getElementById('nav-icon');
var body = document.querySelector('body');

So that js only performs the look up once, instead of 3 times. This caches the dom lookup which will improve performance.


问:
Proxy exec.Cmd Stdout / Stderr without losing TTY
I've got the following code that executes an arbitrary shell command and pipes the stdout and stderr to the terminal.:

```<code>c := exec.Command("/bin/sh", "-c", cmd)
c.Stdin = os.Stdin
c.Stdout = os.Stdout
c.Stderr = os.Stderr
</code>```

However, I need to process the output before I print it, so I've wrapped it with a proxy io.Writer interface:

```<code>type ProxyWriter struct {
    file   *os.File
}

func NewProxyWriter(file *os.File) *ProxyWriter {
    return &ProxyWriter{
        file: file,
    }
}

func (w *ProxyWriter) Write(p []byte) (int, error) {
    // ... do something with bytes first
    fmt.Fprintf(w.file, "%s", string(p))
    return len(p), nil
}
</code>```

So the original code is now:

```<code>c := exec.Command("/bin/sh", "-c", cmd)
c.Stdin = os.Stdin
c.Stdout = NewProxyWriter(os.Stdout)
c.Stderr = NewProxyWriter(os.Stderr)
</code>```

This works for the most part, however, stdout and stderr no longer seem to qualify as a TTY. Any previously styled or colored output is no longer styled or colored.

I've confirmed that this is not an issue of my ProxyWriter simply messing with the formatting by setting the command to the following, which outputs the colored text correctly.

```<code>c := exec.Command("echo", "\033[0;31mTEST\033[0m")
</code>```

A more explicit test is:

```<code>c := exec.Command("/bin/sh", "-c", "if [ -t 1 ] ; then echo \"terminal\"; else echo \"not a terminal\"; fi")
</code>```

Which outputs:

```<code>not a terminal
</code>```

Is there anyway I can wrap the commands stdout / stderr without losing the TTY status?

答:
Replace

```<code>func (w *ProxyWriter) Write(p []byte) (int, error) {
    // ... do something with bytes first
    fmt.Fprintf(w.file, "%s", string(p))
    return len(p), nil
}
</code>```

To

```<code>func (w *ProxyWriter) Write(p []byte) (int, error) {
    return w.Write(p)
}
</code>```

fmt.Fprintf have some logic to avoid terminal breaking.

Body:
I've got the following code that executes an arbitrary shell command and pipes the stdout and stderr to the terminal.:

c := exec.Command("/bin/sh", "-c", cmd)
c.Stdin = os.Stdin
c.Stdout = os.Stdout
c.Stderr = os.Stderr

However, I need to process the output before I print it, so I've wrapped it with a proxy io.Writer interface:

type ProxyWriter struct {
    file   *os.File
}

func NewProxyWriter(file *os.File) *ProxyWriter {
    return &ProxyWriter{
        file: file,
    }
}

func (w *ProxyWriter) Write(p []byte) (int, error) {
    // ... do something with bytes first
    fmt.Fprintf(w.file, "%s", string(p))
    return len(p), nil
}

So the original code is now:

c := exec.Command("/bin/sh", "-c", cmd)
c.Stdin = os.Stdin
c.Stdout = NewProxyWriter(os.Stdout)
c.Stderr = NewProxyWriter(os.Stderr)

This works for the most part, however, stdout and stderr no longer seem to qualify as a TTY. Any previously styled or colored output is no longer styled or colored.

I've confirmed that this is not an issue of my ProxyWriter simply messing with the formatting by setting the command to the following, which outputs the colored text correctly.

c := exec.Command("echo", "\033[0;31mTEST\033[0m")

A more explicit test is:

c := exec.Command("/bin/sh", "-c", "if [ -t 1 ] ; then echo \"terminal\"; else echo \"not a terminal\"; fi")

Which outputs:

not a terminal

Is there anyway I can wrap the commands stdout / stderr without losing the TTY status?

Body:
Replace

func (w *ProxyWriter) Write(p []byte) (int, error) {
    // ... do something with bytes first
    fmt.Fprintf(w.file, "%s", string(p))
    return len(p), nil
}

To

func (w *ProxyWriter) Write(p []byte) (int, error) {
    return w.Write(p)
}

fmt.Fprintf have some logic to avoid terminal breaking.


问:
Switch from dyadic to monadic interpretation in a J sentence
I am trying to understand composition in J, after struggling to mix and match different phases. I would like help switching between monadic and dyadic phrases in the same sentence.

I just made a simple dice roller in J, which will serve as an example:

```<code>   d=.1+[:?[#]
   4 d 6
2 3 1 1
   8 d 12
10 2 11 11 5 11 1 10
</code>```

This is a chain: "d is one plus the (capped) roll of x occurrences of y"

But what if I wanted to use >: to increment (and skip the cap [: ), such that it "switched" to monadic interpretation after the first fork?
It would read: "d is the incremented roll of x occurrences of y".

Something like this doesn't work, even though it looks to me to have about the right structure:

```<code>   d=.>:&?[#]
   d
>:&? ([ # ])
</code>```

(If this approach is against the grain for J and I should stick to capped forks, that is also useful information.)

答:
Let's look at a dyadic fork a(c d f h g)b where c,d,f, g and h are verbs and a and b are arguments, which is evaluated as: (a c b) d (a f b) h (a g b) The arguments are applied dyadically to the verbs in the odd positions (or tines c,f and g) - and those results are fed dyadically right to left into the even tines d and h. Also a fork can be either in the form of (v v v) or (n v v) where v stands for verbs and n stands for nouns. In the case of (n v v) you just get the value of n as the left argument to the middle tine.

If you look at your original definition of d=.1+[:?[#] you might notice it simplifies to a dyadic fork with five tines (1 + [: ? #) where the [ # ] can be replaced by # as it is a dyadic fork (see definition above).

The [: (Cap) verb returns no value to the left argument of ? which means that ? acts monadically on the result of a # b and this becomes the right argument to + which has a left argument of 1.

So, on to the question of how to get rid of the [: and use >: instead of 1 + ...

You can also write ([: f g) as f@:g to get rid of the Cap, which means that ([: ? #) becomes ?@:# and now since you want to feed this result into >: you can do that by either:

```<code>   d1=.>:@:?@:#
   d2=. [: >: ?@:#
   4 d1 6
6 6 1 5
   4 d2 6
2 3 4 5
   8 d1 12
7 6 6 4 6 9 8 7
   8 d2 12
2 10 10 9 8 12 4 3
</code>```

Hope this helps, it is a good fundamental question about how forks are evaluated. It would be your preference of whether you use the ([: f g) or f@:g forms of composition.

Body:
I am trying to understand composition in J, after struggling to mix and match different phases. I would like help switching between monadic and dyadic phrases in the same sentence.

I just made a simple dice roller in J, which will serve as an example:

   d=.1+[:?[#]
   4 d 6
2 3 1 1
   8 d 12
10 2 11 11 5 11 1 10

This is a chain: "d is one plus the (capped) roll of x occurrences of y"

But what if I wanted to use >: to increment (and skip the cap [: ), such that it "switched" to monadic interpretation after the first fork?
It would read: "d is the incremented roll of x occurrences of y".

Something like this doesn't work, even though it looks to me to have about the right structure:

   d=.>:&?[#]
   d
>:&? ([ # ])

(If this approach is against the grain for J and I should stick to capped forks, that is also useful information.)

Body:
Let's look at a dyadic fork a(c d f h g)b where c,d,f, g and h are verbs and a and b are arguments, which is evaluated as: (a c b) d (a f b) h (a g b) The arguments are applied dyadically to the verbs in the odd positions (or tines c,f and g) - and those results are fed dyadically right to left into the even tines d and h. Also a fork can be either in the form of (v v v) or (n v v) where v stands for verbs and n stands for nouns. In the case of (n v v) you just get the value of n as the left argument to the middle tine.

If you look at your original definition of d=.1+[:?[#] you might notice it simplifies to a dyadic fork with five tines (1 + [: ? #) where the [ # ] can be replaced by # as it is a dyadic fork (see definition above).

The [: (Cap) verb returns no value to the left argument of ? which means that ? acts monadically on the result of a # b and this becomes the right argument to + which has a left argument of 1.

So, on to the question of how to get rid of the [: and use >: instead of 1 + ...

You can also write ([: f g) as f@:g to get rid of the Cap, which means that ([: ? #) becomes ?@:# and now since you want to feed this result into >: you can do that by either:

   d1=.>:@:?@:#
   d2=. [: >: ?@:#
   4 d1 6
6 6 1 5
   4 d2 6
2 3 4 5
   8 d1 12
7 6 6 4 6 9 8 7
   8 d2 12
2 10 10 9 8 12 4 3

Hope this helps, it is a good fundamental question about how forks are evaluated. It would be your preference of whether you use the ([: f g) or f@:g forms of composition.


问:
Htaccess redirect subdirectory extension and query string
I have url like this http://www.example.com/subdir/Subcontent?QUERY=420501 i want to redirect it to http://www.example.com/subcontent.html?QUERY=420501 so if Subcontent is dynamic in url then it will change first letter of Subcontent to small and redirect to final url http://www.example.com/subcontent.html?QUERY=420501

I have tried with this

```<code>RewriteCond %{QUERY_STRING} QUERY=([0-9]+) [NC]
RewriteCond %{REQUEST_URI} !\.html
RewriteRule ^subdir/(.*)$ /$1 [L,R=301]
</code>```

But it does not seems to work i think sequence is not proper of conditions cangetting clueless on this.

答:
Add this RewriteMap in Apache or vhost server config:

```<code>RewriteMap lc int:tolower
</code>```

Also you have an extra condition, use this rule to redirect and lowercase your URLs:

```<code>RewriteCond %{QUERY_STRING} (^|&)QUERY=([0-9]+) [NC]
RewriteRule ^subdir/([\w-]+)/?$ /${lc:$1}.html [L,NC,R=301]
</code>```

Body:
I have url like this http://www.example.com/subdir/Subcontent?QUERY=420501 i want to redirect it to http://www.example.com/subcontent.html?QUERY=420501 so if Subcontent is dynamic in url then it will change first letter of Subcontent to small and redirect to final url http://www.example.com/subcontent.html?QUERY=420501

I have tried with this

RewriteCond %{QUERY_STRING} QUERY=([0-9]+) [NC]
RewriteCond %{REQUEST_URI} !\.html
RewriteRule ^subdir/(.*)$ /$1 [L,R=301]

But it does not seems to work i think sequence is not proper of conditions cangetting clueless on this.

Body:
Add this RewriteMap in Apache or vhost server config:

RewriteMap lc int:tolower

Also you have an extra condition, use this rule to redirect and lowercase your URLs:

RewriteCond %{QUERY_STRING} (^|&)QUERY=([0-9]+) [NC]
RewriteRule ^subdir/([\w-]+)/?$ /${lc:$1}.html [L,NC,R=301]


问:
Alter the gmail subject line
I am trying to alter the Gmail subject by prefixing it with certain word if it matches the filter condition. I am aware that it is not possible to modify the subject line using Google App Script. But is it possible to modify it using GMAIL API and App Script. Also, I am member of G-Suite so is there any default configuration or inbuilt method to achieve the same.

Similar question: How to edit Gmail messages as they arrive?

答:
It is technically not possible to modify the subject or content of an email message via the Gmail API. You can only change the labels via the API.

One possible workaround is to retrieve the original message, change only the subject line and append the message in the Gmail thread with Insert.

Title: Alter the gmail subject line


问:
nHibernate criteria - how do I implement 'having count'
I have the following table structure and I want a turn the query into a NH criteria but I'm not sure how to incorporate the correct 'Projection', does anyone know how?

And the query I want to turn into a Criteria:

```<code>select ComponentId from Table_1
where [Name] = 'Contact' or [Name] = 'CurrencyPair'
group by ComponentId
having count(VersionId) = 2
</code>```

答:
I came across this question when trying to find a solution to my problem.

This post was useful.

In my case I was trying to return all records which have all the sub records the user specifies.
I ended up using a sub query which filters the sub records to the ones the user specified and returns the count, and checking that the count of the sub query equals the number of sub records the user specified.
Bit different from your scenario, but hope helps.

ContentLicense: CC BY-SA 2.5

Body:
I have the following table structure and I want a turn the query into a NH criteria but I'm not sure how to incorporate the correct 'Projection', does anyone know how?

And the query I want to turn into a Criteria:

select ComponentId from Table_1
where [Name] = 'Contact' or [Name] = 'CurrencyPair'
group by ComponentId
having count(VersionId) = 2


问:
Checkbox unchecked when I scroll listview on Android
I am new to Android development. I created a listview with a textbox and checkbox.

When I check the checkbox and scroll it down to check some other items in the list view, the older ones are unchecked.

How do I avoid this problem in a listview? Please guide me with my code.

Here is the code:

main.xml:

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

    <TextView
        android:id="@+id/TextView01"
        android:layout_height="wrap_content"
        android:text="List of items"
        android:textStyle="normal|bold"
        android:gravity="center_vertical|center_horizontal"
        android:layout_width="fill_parent"/>

    <ListView
        android:id="@+id/ListView01"
        android:layout_height="250px"
        android:layout_width="fill_parent"/>

    <Button
        android:text="Save"
        android:id="@+id/btnSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>
</code>```

This is the XML page I used to create dynamic list row:

listview.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:gravity="left|center"
    android:layout_width="wrap_content"
    android:paddingBottom="5px"
    android:paddingTop="5px"
    android:paddingLeft="5px">

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="#FFFF00"
        android:text="hi"/>

    <TextView
        android:text="hello"
        android:id="@+id/TextView02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10px"
        android:textColor="#0099CC"/>

    <EditText
        android:id="@+id/txtbox"
        android:layout_width="120px"
        android:layout_height="wrap_content"
        android:textSize="12sp"
        android:layout_x="211px"
        android:layout_y="13px"/>

    <CheckBox
        android:id="@+id/chkbox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>
</code>```

This is my activity class.

CustomListViewActivity.java:

```<code>public class CustomListViewActivity extends Activity {

    ListView lstView;
    static Context mContext;
    Button btnSave;

    private static class EfficientAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        public EfficientAdapter(Context context) {
            mInflater = LayoutInflater.from(context);

        }

        public int getCount() {
            return country.length;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.listview, parent,
                        false);
                holder = new ViewHolder();
                holder.text = (TextView) convertView
                        .findViewById(R.id.TextView01);
                holder.text2 = (TextView) convertView
                        .findViewById(R.id.TextView02);
                holder.txt = (EditText) convertView.findViewById(R.id.txtbox);
                holder.cbox = (CheckBox) convertView.findViewById(R.id.chkbox1);

                convertView.setTag(holder);
            }
            else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.text.setText(curr[position]);
            holder.text2.setText(country[position]);
            holder.txt.setText("");
            holder.cbox.setChecked(false);

            return convertView;
        }

        public class ViewHolder {
            TextView text;
            TextView text2;
            EditText txt;
            CheckBox cbox;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        lstView = (ListView) findViewById(R.id.ListView01);
        lstView.setAdapter(new EfficientAdapter(this));
        btnSave = (Button)findViewById(R.id.btnSave);
        mContext = this;

        btnSave.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // I want to print the text which is in the listview one by one.
                // Later I will insert it in the database.
                //
                //            Toast.makeText(getBaseContext(), "EditText Value, checkbox value and other values", Toast.LENGTH_SHORT).show();
                for (int i = 0; i < lstView.getCount(); i++) {
                    View listOrderView;
                    listOrderView = lstView.getChildAt(i);
                    try{
                        EditText txtAmt = (EditText)listOrderView.findViewById(R.id.txtbox);
                        CheckBox cbValue = (CheckBox)listOrderView.findViewById(R.id.chkbox1);
                        if(cbValue.isChecked()== true){
                            String amt = txtAmt.getText().toString();
                            Toast.makeText(getBaseContext(), "Amount is :"+amt, Toast.LENGTH_SHORT).show();
                        }

                    }
                    catch (Exception e) {
                        // TODO: handle exception
                    }
                }

            }
        });
    }

    private static final String[] country = { "item1", "item2", "item3",
        "item4", "item5", "item6","item7", "item8", "item9",
        "item10", "item11", "item12" };

    private static final String[] curr = { "1", "2", "3", "4", "5", "6","7", "8", "9", "10", "11", "12" };
}
</code>```

Please help me to solve this problem.

I have referred to this problem in many places. But I could not get proper answer to solve this problem.

Please provide me the code to avoid unchecking the checkbox while scrolling up and down.

答:
You can use the following adapter code to run a checkbox perfectly in a ListView.

A detailed demo is here: Listview With Checkbox Android

See the detailed demo link for deep information. It also shows how to send checked information to the next activity.

```<code>import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;

public class CustomAdapter  extends BaseAdapter {

    private Context context;
    public static ArrayList<Model> modelArrayList;

    public CustomAdapter(Context context, ArrayList<Model> modelArrayList) {

        this.context = context;
        this.modelArrayList = modelArrayList;
    }

    @Override
    public int getViewTypeCount() {
        return getCount();
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    @Override
    public int getCount() {
        return modelArrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return modelArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;

        if (convertView == null) {
            holder = new ViewHolder(); LayoutInflater inflater = (LayoutInflater) context
                     .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.lv_item, null, true);

            holder.checkBox = (CheckBox) convertView.findViewById(R.id.cb);
            holder.tvAnimal = (TextView) convertView.findViewById(R.id.animal);

            convertView.setTag(holder);
        }
        else {
            // The getTag returns the viewHolder object set as a tag to the view
            holder = (ViewHolder)convertView.getTag();
        }

        holder.checkBox.setText("Checkbox " + position);
        holder.tvAnimal.setText(modelArrayList.get(position).getAnimal());

        holder.checkBox.setChecked(modelArrayList.get(position).getSelected());

        holder.checkBox.setTag(R.integer.btnplusview, convertView);
        holder.checkBox.setTag( position);
        holder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                View tempview = (View) holder.checkBox.getTag(R.integer.btnplusview);
                TextView tv = (TextView) tempview.findViewById(R.id.animal);
                Integer pos = (Integer)  holder.checkBox.getTag();
                Toast.makeText(context, "Checkbox " + pos + " clicked!", Toast.LENGTH_SHORT).show();

                if (modelArrayList.get(pos).getSelected()){
                    modelArrayList.get(pos).setSelected(false);
                }
                else {
                    modelArrayList.get(pos).setSelected(true);
                }

            }
        });

        return convertView;
    }

    private class ViewHolder {

        protected CheckBox checkBox;
        private TextView tvAnimal;
    }
}
</code>```

Model is

```<code>public class Model {

    private boolean isSelected;

    private String animal;

    public String getAnimal() {
        return animal;
    }

    public void setAnimal(String animal) {
        this.animal = animal;
    }

    public boolean getSelected() {
        return isSelected;
    }

    public void setSelected(boolean selected) {
        isSelected = selected;
    }
}
</code>```

Body:
I am new to Android development. I created a listview with a textbox and checkbox.

When I check the checkbox and scroll it down to check some other items in the list view, the older ones are unchecked.

How do I avoid this problem in a listview? Please guide me with my code.

Here is the code:

main.xml:

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

    <TextView
        android:id="@+id/TextView01"
        android:layout_height="wrap_content"
        android:text="List of items"
        android:textStyle="normal|bold"
        android:gravity="center_vertical|center_horizontal"
        android:layout_width="fill_parent"/>

    <ListView
        android:id="@+id/ListView01"
        android:layout_height="250px"
        android:layout_width="fill_parent"/>

    <Button
        android:text="Save"
        android:id="@+id/btnSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

This is the XML page I used to create dynamic list row:

listview.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:gravity="left|center"
    android:layout_width="wrap_content"
    android:paddingBottom="5px"
    android:paddingTop="5px"
    android:paddingLeft="5px">

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="#FFFF00"
        android:text="hi"/>

    <TextView
        android:text="hello"
        android:id="@+id/TextView02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10px"
        android:textColor="#0099CC"/>

    <EditText
        android:id="@+id/txtbox"
        android:layout_width="120px"
        android:layout_height="wrap_content"
        android:textSize="12sp"
        android:layout_x="211px"
        android:layout_y="13px"/>

    <CheckBox
        android:id="@+id/chkbox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

This is my activity class.

CustomListViewActivity.java:

public class CustomListViewActivity extends Activity {

    ListView lstView;
    static Context mContext;
    Button btnSave;

    private static class EfficientAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        public EfficientAdapter(Context context) {
            mInflater = LayoutInflater.from(context);

        }

        public int getCount() {
            return country.length;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.listview, parent,
                        false);
                holder = new ViewHolder();
                holder.text = (TextView) convertView
                        .findViewById(R.id.TextView01);
                holder.text2 = (TextView) convertView
                        .findViewById(R.id.TextView02);
                holder.txt = (EditText) convertView.findViewById(R.id.txtbox);
                holder.cbox = (CheckBox) convertView.findViewById(R.id.chkbox1);

                convertView.setTag(holder);
            }
            else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.text.setText(curr[position]);
            holder.text2.setText(country[position]);
            holder.txt.setText("");
            holder.cbox.setChecked(false);

            return convertView;
        }

        public class ViewHolder {
            TextView text;
            TextView text2;
            EditText txt;
            CheckBox cbox;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        lstView = (ListView) findViewById(R.id.ListView01);
        lstView.setAdapter(new EfficientAdapter(this));
        btnSave = (Button)findViewById(R.id.btnSave);
        mContext = this;

        btnSave.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // I want to print the text which is in the listview one by one.
                // Later I will insert it in the database.
                //
                //            Toast.makeText(getBaseContext(), "EditText Value, checkbox value and other values", Toast.LENGTH_SHORT).show();
                for (int i = 0; i < lstView.getCount(); i++) {
                    View listOrderView;
                    listOrderView = lstView.getChildAt(i);
                    try{
                        EditText txtAmt = (EditText)listOrderView.findViewById(R.id.txtbox);
                        CheckBox cbValue = (CheckBox)listOrderView.findViewById(R.id.chkbox1);
                        if(cbValue.isChecked()== true){
                            String amt = txtAmt.getText().toString();
                            Toast.makeText(getBaseContext(), "Amount is :"+amt, Toast.LENGTH_SHORT).show();
                        }

                    }
                    catch (Exception e) {
                        // TODO: handle exception
                    }
                }

            }
        });
    }

    private static final String[] country = { "item1", "item2", "item3",
        "item4", "item5", "item6","item7", "item8", "item9",
        "item10", "item11", "item12" };

    private static final String[] curr = { "1", "2", "3", "4", "5", "6","7", "8", "9", "10", "11", "12" };
}

Please help me to solve this problem.

I have referred to this problem in many places. But I could not get proper answer to solve this problem.

Please provide me the code to avoid unchecking the checkbox while scrolling up and down.

Body:
You can use the following adapter code to run a checkbox perfectly in a ListView.

A detailed demo is here: Listview With Checkbox Android

See the detailed demo link for deep information. It also shows how to send checked information to the next activity.

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;

public class CustomAdapter  extends BaseAdapter {

    private Context context;
    public static ArrayList<Model> modelArrayList;

    public CustomAdapter(Context context, ArrayList<Model> modelArrayList) {

        this.context = context;
        this.modelArrayList = modelArrayList;
    }

    @Override
    public int getViewTypeCount() {
        return getCount();
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    @Override
    public int getCount() {
        return modelArrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return modelArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;

        if (convertView == null) {
            holder = new ViewHolder(); LayoutInflater inflater = (LayoutInflater) context
                     .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.lv_item, null, true);

            holder.checkBox = (CheckBox) convertView.findViewById(R.id.cb);
            holder.tvAnimal = (TextView) convertView.findViewById(R.id.animal);

            convertView.setTag(holder);
        }
        else {
            // The getTag returns the viewHolder object set as a tag to the view
            holder = (ViewHolder)convertView.getTag();
        }

        holder.checkBox.setText("Checkbox " + position);
        holder.tvAnimal.setText(modelArrayList.get(position).getAnimal());

        holder.checkBox.setChecked(modelArrayList.get(position).getSelected());

        holder.checkBox.setTag(R.integer.btnplusview, convertView);
        holder.checkBox.setTag( position);
        holder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                View tempview = (View) holder.checkBox.getTag(R.integer.btnplusview);
                TextView tv = (TextView) tempview.findViewById(R.id.animal);
                Integer pos = (Integer)  holder.checkBox.getTag();
                Toast.makeText(context, "Checkbox " + pos + " clicked!", Toast.LENGTH_SHORT).show();

                if (modelArrayList.get(pos).getSelected()){
                    modelArrayList.get(pos).setSelected(false);
                }
                else {
                    modelArrayList.get(pos).setSelected(true);
                }

            }
        });

        return convertView;
    }

    private class ViewHolder {

        protected CheckBox checkBox;
        private TextView tvAnimal;
    }
}

Model is

public class Model {

    private boolean isSelected;

    private String animal;

    public String getAnimal() {
        return animal;
    }

    public void setAnimal(String animal) {
        this.animal = animal;
    }

    public boolean getSelected() {
        return isSelected;
    }

    public void setSelected(boolean selected) {
        isSelected = selected;
    }
}


问:
DuplicateFileException When building ionic app for android
I'm trying to build my app for android, and ever since I updated my android-cordova to 6.2.3 I have not been able to build my app for android anymore.

Rolling back to android-cordova 6.1.1 didn't help, I was unable to build again after the previous upgrade.

The full error is

```<code>* What went wrong:
Execution failed for task ':transformResourcesWithMergeJavaResForDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate file
s copied in APK META-INF/rxjava.properties
        File1: /Users/admin/Desktop/Gravity/clubezy-meteorionic/platforms/android/build/intermediates/exploded-aar/com.goo
gle.android.gms/play-services-basement/11.0.0/jars/classes.jar
        File2: /Users/admin/.gradle/caches/modules-2/files-2.1/io.reactivex/rxjava/1.1.9/e4362e62f1ba92e360b197d6d7ffae67e
5ecae9a/rxjava-1.1.9.jar
</code>```

I have a suspicion that it could be an issue with one of my cordova plugins that may be causing this.

This is my environment and plugins.

```<code>ionic info:
global packages:

@ionic/cli-utils : 1.4.0
Cordova CLI : 7.0.1
Ionic CLI : 3.4.0

local packages:

@ionic/app-scripts : 1.3.7
@ionic/cli-plugin-cordova : 1.4.0
@ionic/cli-plugin-ionic-angular : 1.3.1
Cordova Platforms : ios 4.4.0, android 6.2.3
Ionic Framework : ionic-angular 3.4.2

System:

Node : v6.10.3
OS : Linux 4.4
Xcode : not installed
ios-deploy : not installed
ios-sim : not installed
npm : 5.0.3

cordova plugin ls

com.instabug.cordova.plugin 1.0.0 "instabug-cordova"
cordova-plugin-3dtouch 1.3.5 "3D Touch"
cordova-plugin-app-version 0.1.9 "AppVersion"
cordova-plugin-camera 2.3.1 "Camera"
cordova-plugin-compat 1.1.0 "Compat"
cordova-plugin-console 1.0.5 "Console"
cordova-plugin-device 1.1.6 "Device"
cordova-plugin-file 4.3.3 "File"
cordova-plugin-file-transfer 1.6.3 "File Transfer"
cordova-plugin-multidex 0.1.1 "Cordova Multi Dex"
cordova-plugin-splashscreen 4.0.3 "Splashscreen"
cordova-plugin-statusbar 2.2.3 "StatusBar"
cordova-plugin-whitelist 1.3.1 "Whitelist"
ionic-plugin-keyboard 2.2.1 "Keyboard"
onesignal-cordova-plugin 2.0.11 "OneSignal Push Notifications"
</code>```

The plugin I think may be causing this is the instabug one.

~edit

After adding each plugin one at a time either

com.instabug.cordova.plugin or cordova-plugin-multidex

is causing it

multidex is a dependancy of instabug

答:
To get it to build on my iOS and Linux build machines I changed the build.gradle  to have this.

```<code>android {
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
        }
    }

    defaultConfig {
        applicationId = doExtractStringFromManifest("package")
    }

    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/rxjava.properties'
    }
}
</code>```

It now seems to be building correctly, I created a branch with the changes so I could pull it from github to install via the packages.

Body:
I'm trying to build my app for android, and ever since I updated my android-cordova to 6.2.3 I have not been able to build my app for android anymore.

Rolling back to android-cordova 6.1.1 didn't help, I was unable to build again after the previous upgrade.

The full error is

* What went wrong:
Execution failed for task ':transformResourcesWithMergeJavaResForDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate file
s copied in APK META-INF/rxjava.properties
        File1: /Users/admin/Desktop/Gravity/clubezy-meteorionic/platforms/android/build/intermediates/exploded-aar/com.goo
gle.android.gms/play-services-basement/11.0.0/jars/classes.jar
        File2: /Users/admin/.gradle/caches/modules-2/files-2.1/io.reactivex/rxjava/1.1.9/e4362e62f1ba92e360b197d6d7ffae67e
5ecae9a/rxjava-1.1.9.jar

I have a suspicion that it could be an issue with one of my cordova plugins that may be causing this.

This is my environment and plugins.

ionic info:
global packages:

@ionic/cli-utils : 1.4.0
Cordova CLI : 7.0.1
Ionic CLI : 3.4.0

local packages:

@ionic/app-scripts : 1.3.7
@ionic/cli-plugin-cordova : 1.4.0
@ionic/cli-plugin-ionic-angular : 1.3.1
Cordova Platforms : ios 4.4.0, android 6.2.3
Ionic Framework : ionic-angular 3.4.2

System:

Node : v6.10.3
OS : Linux 4.4
Xcode : not installed
ios-deploy : not installed
ios-sim : not installed
npm : 5.0.3

cordova plugin ls

com.instabug.cordova.plugin 1.0.0 "instabug-cordova"
cordova-plugin-3dtouch 1.3.5 "3D Touch"
cordova-plugin-app-version 0.1.9 "AppVersion"
cordova-plugin-camera 2.3.1 "Camera"
cordova-plugin-compat 1.1.0 "Compat"
cordova-plugin-console 1.0.5 "Console"
cordova-plugin-device 1.1.6 "Device"
cordova-plugin-file 4.3.3 "File"
cordova-plugin-file-transfer 1.6.3 "File Transfer"
cordova-plugin-multidex 0.1.1 "Cordova Multi Dex"
cordova-plugin-splashscreen 4.0.3 "Splashscreen"
cordova-plugin-statusbar 2.2.3 "StatusBar"
cordova-plugin-whitelist 1.3.1 "Whitelist"
ionic-plugin-keyboard 2.2.1 "Keyboard"
onesignal-cordova-plugin 2.0.11 "OneSignal Push Notifications"

The plugin I think may be causing this is the instabug one.

~edit

After adding each plugin one at a time either

com.instabug.cordova.plugin or cordova-plugin-multidex

is causing it

multidex is a dependancy of instabug

Body:
To get it to build on my iOS and Linux build machines I changed the build.gradle  to have this.

android {
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
        }
    }

    defaultConfig {
        applicationId = doExtractStringFromManifest("package")
    }

    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/rxjava.properties'
    }
}

It now seems to be building correctly, I created a branch with the changes so I could pull it from github to install via the packages.


问:
How to double quote escape the embedded java in JSP?
I'm trying to make an feature that could make my image button disappear when user don't have the Permission.

```<code><input type="image"
src="<%=request.getContextPath()%>/img/pencil.png"
onClick="document.sentToBack.submit()" />
</code>```

Above one is the original code that I'm trying to make it display conditionally.

```<code><%
    if(DisplayBtn == true) {
        out.println("<input type=\"image\""
        + " src=\"/img/pencil.png\""
        + " onClick=\"document.sentToBack.submit()\" />");
    }
%>
</code>```

This one is workable, but won't display my image properly because that path isn't correct. And if I put my embedded java back into above code, it will tell me that I'm not properly double-quoted that string.

Can anyone tell me how to escape that embedded java and make it works as usual?

答:
Just replace double quote with single quote</p>

```<code><%
    if(DisplayBtn == true) {
        out.println("<input type='image'"
        + " src='img/pencil.png'"
        + " onClick='document.sentToBack.submit()' />");
    }
%>
</code>```

Body:
I'm trying to make an feature that could make my image button disappear when user don't have the Permission.

<input type="image"
src="<%=request.getContextPath()%>/img/pencil.png"
onClick="document.sentToBack.submit()" />

Above one is the original code that I'm trying to make it display conditionally.

<%
    if(DisplayBtn == true) {
        out.println("<input type=\"image\""
        + " src=\"/img/pencil.png\""
        + " onClick=\"document.sentToBack.submit()\" />");
    }
%>

This one is workable, but won't display my image properly because that path isn't correct. And if I put my embedded java back into above code, it will tell me that I'm not properly double-quoted that string.

Can anyone tell me how to escape that embedded java and make it works as usual?

Body:
Just replace double quote with single quote

<%
    if(DisplayBtn == true) {
        out.println("<input type='image'"
        + " src='img/pencil.png'"
        + " onClick='document.sentToBack.submit()' />");
    }
%>


问:
How to convert Base64 data and NSData into string
i am new in IOS and i am making a project in which i receive Base64 data from web service. how to convert Base64 data into string and how to open a pdf view in swift and also check that is there any pdf owner application install or not in iPhone .and i want to know that how to convert NSDATA in string swift.Help me
example like this is Base64 data
JVBERi0xLjQKJcfsj6IKNSAwIG9iago8PC9MZW5ndGggNiAwIFIvRmlsdGVyIC9GbGF0ZURlY29kZT4+CnN0cmVhbQp4nLVcza8ct5GH1rK9ejIU24lkO5GtJ8vWm5E87eY3uXtbYLHAYi8JdItySrABAjhA8v8fUuwmu35kF2fmxbsWDMxjk8VisapYX+TfbudJ6ds5/6s//vj

Like this is nsdata
<25504446 2d312e34 0a25c7ec 8fa20a35 2030206f 626a0a3c 3c2f4c65 6e677468 20362030 20522f46 696c7465 72202f46 6c617465 4465636f 64653e3e 0a737472 65616d0a 789cb55c cdaf1cb7 9187d6b2 bd7a3214 db89643b 91ad27cb d69b913c

答:
Swift 3.0

A handy extension of string. Hope will help you.

```<code>extension String {

    func fromBase64() -> String? {
        guard let data = Data(base64Encoded: self) else {
            return nil
        }

        return String(data: data, encoding: .utf8)
    }

    func toBase64() -> String {
        return Data(self.utf8).base64EncodedString()
    }
}
</code>```

Body:
Swift 3.0

A handy extension of string. Hope will help you.

extension String {

    func fromBase64() -> String? {
        guard let data = Data(base64Encoded: self) else {
            return nil
        }

        return String(data: data, encoding: .utf8)
    }

    func toBase64() -> String {
        return Data(self.utf8).base64EncodedString()
    }
}


问:
mysql connector isn't integrate in visual studio
i've installed mysql connector on my pc. But when i start Visual Web Developer 2010, i if i try to add a database server, i can't find and choose Mysql server.
I 've only Sql server, oracle and odbc driver.
I've tried to reinstall mysql connector (msi file downloaded via Mysql web site), but it not solve.

Does Anyone have the same problem ?

答:
I've found my problem: i was using visual studio express. Express seems not integrate mysql connector !
Thank you anyway for your answer!</p>


问:
Program throws 'Access-Control-Allow-Origin' header in JavaScript? Works in Postman, not through browser
Solved

I have been working on this program since 07:00. This has been driving me crazy. I have written multiple full stack web apps and have not had this problem.

Basically I have a form in html that allows a user to input data. Whenever the submit button is clicked, it sends that data to a collection in mongoDB. I have tested this in postman and it works. However, when I run the program through a webbrowser, I get this error:

XMLHttpRequest cannot load http://localhost:8080/articles/addArticle. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 404.

I tried installing CORS and configuring the endpoint

I tried going into the javascript file and changing the

This is my JavaScript file

```<code>alert('JS is linked to page!');

function Article(id = 1, title = "", authors="", content = "", genre = "", date = 1497484623) {
    console.log("JavaScript file loaded successfully");
    var self = this;
    self.Id = id;
    self.Title = title;
    self.Authors = authors;
    self.Content = content;
    self.Genre = genre;
    self.Date = date;
    self.Save = function() {
        var settings = {
            url: 'http://localhost:8080/articles/addArticle',
            method: 'POST',
            dataType: "json",
              beforeSend: function (xhr) {
                xhr.setRequestHeader("Accept", "application/json");
            }
        };
        var myData = {
            "Id" : self.Id,
            "Title": self.Title,
            "Authors": self.Authors,
            "Content": self.Content,
            "Genre": self.Genre,
            "Date": self.Date
        };
        settings.data = myData;

        $.ajax(settings).done(function(article) {
         var myArticle = new Article(article.Id, article.Title, article.Authors,
                article.Content, article.Genre, article.Date);
        });
    };
}

function addArticle(Article) {
    alert('addArticle Activated');
    var settings = {
        url: 'http://localhost:8080/articles/addArticle',
        method: 'POST',
        dataType: "json",
          beforeSend: function (xhr) {
                xhr.setRequestHeader("Accept", "application/json");
            }
    };
    var myData = {
        "Title": Article.Title,
        "Authors" : Article.Authors,
        "Content": Article.Content,
        "Genre" : Article.Genre,
        "Date": Article.Date
    };
    settings.data = myData;

    $.ajax(settings).done(function(Article) {
        var myArticle = new Article(article.Id, article.Title, article.Authors, article.Content,
            article.Genre, article.Date);
        console.log("Article Created");
    });
}

$(document).ready(function() {

    $(document).on("submit", "#add-article", function(e) {
        e.preventDefault();
            alert('submit Activated');
        var title, authors, genre, content;
        title = $("#Title").val();
        director = $("#Authors").val();
        rating = $("#Genre").val();
        notes = $("#Content").val();
        var myArticle = new Article(0, title, authors, genre, content, 1497484623);
        alert(myArticle.Title);
        addArticle(myArticle);
        $("#add-article")[0].reset();
        $("#title").focus();

    });

});

/*function CreateSuccessRow(Article) {
    var successDataRow = `<tr id="Article-${Article.Id}"><td>${Article.Title}</td>
                <td>${Article.Authors}</td>
                <td>${Article.Genre}</td>
</code>```

Due to popular demand, this is the server-side code:

```<code>package com.stereoscopics.app.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.stereoscopics.app.models.Article;
import com.stereoscopics.app.repo.ArticleRepo;

@RestController
@RequestMapping("/articles")
public class ArticleController {

private ArticleRepo articleRepo;

@Autowired
public ArticleController(ArticleRepo articleRepo) {
    this.articleRepo = articleRepo;
}

@RequestMapping(value = "/findall", method = RequestMethod.GET)
@ResponseBody
public List<Article> findall() {
    return articleRepo.findAll();
}

@RequestMapping(value = "/addArticle", method = RequestMethod.POST)
@ResponseBody
public Article addArticle(@RequestBody Article newArticle) {
    articleRepo.save(newArticle);
    return newArticle;
}
</code>```

}

I have no idea how to fix this. Please help.

UPDATE

This still isn't working. I've updated the code as per some suggestions and I'm either doing it wrong or it's incorrect. The changes are shown below:

```<code>  @RestController
  @RequestMapping("/articles")
  public class ArticleController {

private ArticleRepo articleRepo;

@Autowired
public ArticleController(ArticleRepo articleRepo) {
    this.articleRepo = articleRepo;
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    response.addHeader("Access-Control-Allow-Origin", "*");
}

@RequestMapping(value = "/findall", method = RequestMethod.GET)
@ResponseBody
public List<Article> findall() {
    return articleRepo.findAll();
}

@RequestMapping(value = "/addArticle", method = RequestMethod.POST)
@ResponseBody
public Article addArticle(@RequestBody Article newArticle, final
HttpServletResponse response) {
    response.addHeader("Access-Control-Allow-Origin", "*");
    articleRepo.save(newArticle);
    return newArticle;
  }
}
</code>```

THIS IS NOT SOLVED YET

答:
You can not solve cors as javascript end, I mean to say the problem is with your server code.

Cors is a security feature implemented by browser, let me tell you how it works.

when you query server, at first it hits with option method, at this time server sends allowed origins list, it can be one or multiple. now if your local domain or any domain is not present in that list then browser does not make the actual request.

To fix this you will have to configure cors filter on your server you can do it like

```<code>package com.package.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

 @Component
 public class SimpleCORSFilter extends GenericFilterBean {

/**
 * The Logger for this class.
 */
private final Logger logger = LoggerFactory.getLogger(this.getClass());

@Override
public void doFilter(ServletRequest req, ServletResponse resp,
                     FilterChain chain) throws IOException, ServletException {
    logger.info("> doFilter");

    HttpServletResponse response = (HttpServletResponse) resp;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
    //response.setHeader("Access-Control-Allow-Credentials", "true");
    chain.doFilter(req, resp);

    logger.info("< doFilter");
}
</code>```

now if it's still not working then you will have to debug it line by line at server what's code, and at browser end you can test if option method has list of allowed origins or not.

Body:
Solved

I have been working on this program since 07:00. This has been driving me crazy. I have written multiple full stack web apps and have not had this problem.

Basically I have a form in html that allows a user to input data. Whenever the submit button is clicked, it sends that data to a collection in mongoDB. I have tested this in postman and it works. However, when I run the program through a webbrowser, I get this error:

XMLHttpRequest cannot load http://localhost:8080/articles/addArticle. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 404.

I tried installing CORS and configuring the endpoint

I tried going into the javascript file and changing the

This is my JavaScript file

alert('JS is linked to page!');

function Article(id = 1, title = "", authors="", content = "", genre = "", date = 1497484623) {
    console.log("JavaScript file loaded successfully");
    var self = this;
    self.Id = id;
    self.Title = title;
    self.Authors = authors;
    self.Content = content;
    self.Genre = genre;
    self.Date = date;
    self.Save = function() {
        var settings = {
            url: 'http://localhost:8080/articles/addArticle',
            method: 'POST',
            dataType: "json",
              beforeSend: function (xhr) {
                xhr.setRequestHeader("Accept", "application/json");
            }
        };
        var myData = {
            "Id" : self.Id,
            "Title": self.Title,
            "Authors": self.Authors,
            "Content": self.Content,
            "Genre": self.Genre,
            "Date": self.Date
        };
        settings.data = myData;

        $.ajax(settings).done(function(article) {
         var myArticle = new Article(article.Id, article.Title, article.Authors,
                article.Content, article.Genre, article.Date);
        });
    };
}

function addArticle(Article) {
    alert('addArticle Activated');
    var settings = {
        url: 'http://localhost:8080/articles/addArticle',
        method: 'POST',
        dataType: "json",
          beforeSend: function (xhr) {
                xhr.setRequestHeader("Accept", "application/json");
            }
    };
    var myData = {
        "Title": Article.Title,
        "Authors" : Article.Authors,
        "Content": Article.Content,
        "Genre" : Article.Genre,
        "Date": Article.Date
    };
    settings.data = myData;

    $.ajax(settings).done(function(Article) {
        var myArticle = new Article(article.Id, article.Title, article.Authors, article.Content,
            article.Genre, article.Date);
        console.log("Article Created");
    });
}

$(document).ready(function() {

    $(document).on("submit", "#add-article", function(e) {
        e.preventDefault();
            alert('submit Activated');
        var title, authors, genre, content;
        title = $("#Title").val();
        director = $("#Authors").val();
        rating = $("#Genre").val();
        notes = $("#Content").val();
        var myArticle = new Article(0, title, authors, genre, content, 1497484623);
        alert(myArticle.Title);
        addArticle(myArticle);
        $("#add-article")[0].reset();
        $("#title").focus();

    });

});

/*function CreateSuccessRow(Article) {
    var successDataRow = `
${Article.Title}
                ${Article.Authors}
                ${Article.Genre}

Due to popular demand, this is the server-side code:

package com.stereoscopics.app.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.stereoscopics.app.models.Article;
import com.stereoscopics.app.repo.ArticleRepo;

@RestController
@RequestMapping("/articles")
public class ArticleController {

private ArticleRepo articleRepo;

@Autowired
public ArticleController(ArticleRepo articleRepo) {
    this.articleRepo = articleRepo;
}

@RequestMapping(value = "/findall", method = RequestMethod.GET)
@ResponseBody
public List
 findall() {
    return articleRepo.findAll();
}

@RequestMapping(value = "/addArticle", method = RequestMethod.POST)
@ResponseBody
public Article addArticle(@RequestBody Article newArticle) {
    articleRepo.save(newArticle);
    return newArticle;
}

}

I have no idea how to fix this. Please help.

UPDATE

This still isn't working. I've updated the code as per some suggestions and I'm either doing it wrong or it's incorrect. The changes are shown below:

  @RestController
  @RequestMapping("/articles")
  public class ArticleController {

private ArticleRepo articleRepo;

@Autowired
public ArticleController(ArticleRepo articleRepo) {
    this.articleRepo = articleRepo;
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    response.addHeader("Access-Control-Allow-Origin", "*");
}

@RequestMapping(value = "/findall", method = RequestMethod.GET)
@ResponseBody
public List
 findall() {
    return articleRepo.findAll();
}

@RequestMapping(value = "/addArticle", method = RequestMethod.POST)
@ResponseBody
public Article addArticle(@RequestBody Article newArticle, final
HttpServletResponse response) {
    response.addHeader("Access-Control-Allow-Origin", "*");
    articleRepo.save(newArticle);
    return newArticle;
  }
}

THIS IS NOT SOLVED YET

Body:
You can not solve cors as javascript end, I mean to say the problem is with your server code.

Cors is a security feature implemented by browser, let me tell you how it works.

when you query server, at first it hits with option method, at this time server sends allowed origins list, it can be one or multiple. now if your local domain or any domain is not present in that list then browser does not make the actual request.

To fix this you will have to configure cors filter on your server you can do it like

package com.package.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

 @Component
 public class SimpleCORSFilter extends GenericFilterBean {

/**
 * The Logger for this class.
 */
private final Logger logger = LoggerFactory.getLogger(this.getClass());

@Override
public void doFilter(ServletRequest req, ServletResponse resp,
                     FilterChain chain) throws IOException, ServletException {
    logger.info("> doFilter");

    HttpServletResponse response = (HttpServletResponse) resp;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
    //response.setHeader("Access-Control-Allow-Credentials", "true");
    chain.doFilter(req, resp);

    logger.info("< doFilter");
}

now if it's still not working then you will have to debug it line by line at server what's code, and at browser end you can test if option method has list of allowed origins or not.


问:
How to make request using KONG?
When I making a request to Kong using

1)Add API to KONG

```<code>curl -i -X POST \
--url http://localhost:8001/apis/ \
--data 'name=AnalyticInputHist19api' \
--data 'hosts=localhost' \
--data 'upstream_url=http://localhost:9090/AnalyticsInputHistoryController'
</code>```

2)make request using

```<code>curl -i -X GET \
--url http://localhost:8000/ \
--header 'Host: localhost'
</code>```

It returns me:

HTTP/1.1 502 Bad Gateway
Date: Fri, 30 Jun 2017 06:16:03 GMT
Content-Type: text/plain; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Server: kong/0.10.3
An invalid response was received from the upstream server

kindly help me on how to make successfull request using kong.Thank you!

答:
1) Add api:

curl -i -X POST \
      --url http://localhost:8001/apis/ \
      --data 'name=AnalyticsInputHistory' \
      --data 'uris=/API_analytics' \
      --data 'strip_uri=false' \
      --data 'upstream_url=http://10.223.98.66:9090'

2)Make a request:

curl -i -X GET http://localhost:8000/API_analytics/AnalyticsInputHistoryController?user=1

Title: How to make request using KONG?

Body:
When I making a request to Kong using

1)Add API to KONG

curl -i -X POST \
--url http://localhost:8001/apis/ \
--data 'name=AnalyticInputHist19api' \
--data 'hosts=localhost' \
--data 'upstream_url=http://localhost:9090/AnalyticsInputHistoryController'

2)make request using

curl -i -X GET \
--url http://localhost:8000/ \
--header 'Host: localhost'

It returns me:

HTTP/1.1 502 Bad Gateway
Date: Fri, 30 Jun 2017 06:16:03 GMT
Content-Type: text/plain; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Server: kong/0.10.3
An invalid response was received from the upstream server

kindly help me on how to make successfull request using kong.Thank you!


问:
Nexus Jenkins plugin
I've been trying to configure the Nexus Jenkins plugin for about a week now. Only to find out that the plugin didn't work with our Nexus 3.x oss.

Since then I have downgraded our nexus and have configured everything to work. Except, when I try to add the Maven artifact file path to the jenkins.war file I get an error with the following message:

```<code>Uploading Maven asset with groupId: com.riddlesvillage artifactId: core
version: Version: 1.0.0-SNAPSHOT To repository: releases
Upload of /usr/share/jenkins/ failed
Failing build due to failure to upload file to Nexus Repository Manager

Publisher
FATAL: Upload of /usr/share/jenkins/ failed
    ...

Caused: java.io.IOException: Failed to copy /usr/share/jenkins to
/tmp/jenkins6954159502505207420tmp `$`
</code>```

Tho, when I move the file path and leave it empty it builds, but it still doesn't upload anything to nexus.

答:
If you did follow "How do I configure the Nexus Jenkins Plugin " and it is still not working, the only alternative is to do the deployment to Nexus yourself with a mvn command.

```<code>mvn deploy:deploy-file -DgroupId=<group-id> \
  -DartifactId=<artifact-id> \
  -Dversion=<version> \
  -Dpackaging=<type-of-packaging> \
  -Dfile=<path-to-file> \
  -DrepositoryId=<id-to-map-on-server-section-of-settings.xml> \
  -Durl=<url-of-the-repository-to-deploy>
</code>```

See "Guide to deploying 3rd party JARs to remote repository": that is what I have been using,... and it works both with Nexus 2.x and Nexus 3.x

Title: Nexus Jenkins plugin

Body:
I've been trying to configure the Nexus Jenkins plugin for about a week now. Only to find out that the plugin didn't work with our Nexus 3.x oss.

Since then I have downgraded our nexus and have configured everything to work. Except, when I try to add the Maven artifact file path to the jenkins.war file I get an error with the following message:

Uploading Maven asset with groupId: com.riddlesvillage artifactId: core
version: Version: 1.0.0-SNAPSHOT To repository: releases
Upload of /usr/share/jenkins/ failed
Failing build due to failure to upload file to Nexus Repository Manager

Publisher
FATAL: Upload of /usr/share/jenkins/ failed
    ...

Caused: java.io.IOException: Failed to copy /usr/share/jenkins to
/tmp/jenkins6954159502505207420tmp `$`

Tho, when I move the file path and leave it empty it builds, but it still doesn't upload anything to nexus.

Body:
If you did follow "How do I configure the Nexus Jenkins Plugin " and it is still not working, the only alternative is to do the deployment to Nexus yourself with a mvn command.

mvn deploy:deploy-file -DgroupId=<group-id> \
  -DartifactId=<artifact-id> \
  -Dversion=<version> \
  -Dpackaging=<type-of-packaging> \
  -Dfile=<path-to-file> \
  -DrepositoryId=<id-to-map-on-server-section-of-settings.xml> \
  -Durl=<url-of-the-repository-to-deploy>

See "Guide to deploying 3rd party JARs to remote repository": that is what I have been using,... and it works both with Nexus 2.x and Nexus 3.x


问:
Ndb strong consistency and frequent writes
I'm trying to achieve strong consistency with ndb using python.
And looks like I'm missing something as my reads behave like they're not strongly consistent.

The query is:

```<code>links = Link.query(ancestor=lead_key).filter(Link.last_status ==
None).fetch(keys_only=True)

if links:
    do_action()
</code>```

The key structure is:

```<code>Lead root (generic key) -> Lead -> Website (one per lead) -> Link
</code>```

I have many tasks that are executed concurrently using TaskQueue and this query is performed at the end of every task. Sometimes I'm getting "too much contention" exception when updating the last_status field but I deal with it using retries. Can it break strong consistency?

The expected behavior is having do_action() called when there are no links left with last_status equal to None. The actual behavior is inconsistent: sometimes do_action() is called twice and sometimes not called at all.

答: Using an ancestor key to get strong consistency has a limitation: you're limited to one update per second per entity group. One way to work around this is to shard the entity groups. Sharding Counters describes the technique. It's an old article, but as far as I know, the advise is still sound.</p>

Body:
I'm trying to achieve strong consistency with ndb using python.
And looks like I'm missing something as my reads behave like they're not strongly consistent.

The query is:

links = Link.query(ancestor=lead_key).filter(Link.last_status ==
None).fetch(keys_only=True)

if links:
    do_action()

The key structure is:

Lead root (generic key) -> Lead -> Website (one per lead) -> Link

I have many tasks that are executed concurrently using TaskQueue and this query is performed at the end of every task. Sometimes I'm getting "too much contention" exception when updating the last_status field but I deal with it using retries. Can it break strong consistency?

The expected behavior is having do_action() called when there are no links left with last_status equal to None. The actual behavior is inconsistent: sometimes do_action() is called twice and sometimes not called at all.