问:
Generate sql insert script from excel worksheet
I have a large excel worksheet that I want to add to my database.

Can I generate an SQL insert script from this excel worksheet?

答:
You can use the following excel statement:

```<code>="INSERT INTO table_name(`"&$A$1&"`,`"&$B$1&"`,`"&$C$1&"`, `"&$D$1&"`) VALUES('"&SUBSTITUTE(A2, "'", "\'")&"','"&SUBSTITUTE(B2, "'", "\'")&"','"&SUBSTITUTE(C2, "'", "\'")&"', "&D2&");"
</code>```

This improves upon Hart CO's answer as it takes into account column names and gets rid of compile errors due to quotes in the column. The final column is an example of a numeric value column, without quotes.

Body:
You can use the following excel statement:

="INSERT INTO table_name(`"&$A$1&"`,`"&$B$1&"`,`"&$C$1&"`, `"&$D$1&"`) VALUES('"&SUBSTITUTE(A2, "'", "\'")&"','"&SUBSTITUTE(B2, "'", "\'")&"','"&SUBSTITUTE(C2, "'", "\'")&"', "&D2&");"

This improves upon Hart CO's answer as it takes into account column names and gets rid of compile errors due to quotes in the column. The final column is an example of a numeric value column, without quotes.


来源: stackexchange

问:
devise_token_auth: wrong number of arguments (given 0, expected 1) during RegistrationsController#create
I'm using devise_token_auth to set up authentication for an API-only Rails app. I am testing the registration creation using httpie at the command line with the following command:

http POST :3000/auth 'email=username@email.com' 'password=password' 'password_confirmation=password'

The response is the full HTML output of the error page, and the error within is wrong number of arguments (given 0, expected 1). The offending action is DeviseTokenAuth::RegistrationsController#create.

Thanks in advance for any guidance. Code is here: https://github.com/jraczak/flow-api

Devise is applied to the User model: here

Routes is here

答:
Summarising the chat discussion with an answer...

Just remove has_secure_password in https://github.com/jraczak/flow-api/blob/master/app/models/user.rb and :password_digest from validates_presence_of :name, :email, :password_digest...Devise already does that

I see that you already added encrypted_password column in your schema (https://github.com/jraczak/flow-api/blob/master/db/schema.rb) ...In that case remove the password_digest column from the table...It would work

```<code>rails g migration RemovePwdDigest

class RemovePwdDigest < ActiveRecord::Migration
  def change
    remove_column :users, :password_digest
  end
end
</code>```

What might have gone wrong even after removing has_secure_password and validation:

https://github.com/plataformatec/devise/blob/ee01bac8b0b828b3da0d79c46115ba65c433d6c8/lib/devise/models/database_authenticatable.rb#L45

If you see this line, devise tries to call it's internal password_digest method while setting a new password or wherever you use password= method. But, as you already have a db column with name similar to the method (password_digest column), it is calling that instead of devise internal method. So, you are facing an error. (I may be wrong, this alone seems to be suspicious)

ContentLicense: CC BY-SA 3.0

Body:
Summarising the chat discussion with an answer...

Just remove has_secure_password in https://github.com/jraczak/flow-api/blob/master/app/models/user.rb and :password_digest from validates_presence_of :name, :email, :password_digest...Devise already does that

I see that you already added encrypted_password column in your schema (https://github.com/jraczak/flow-api/blob/master/db/schema.rb) ...In that case remove the password_digest column from the table...It would work

rails g migration RemovePwdDigest

class RemovePwdDigest < ActiveRecord::Migration
  def change
    remove_column :users, :password_digest
  end
end

What might have gone wrong even after removing has_secure_password and validation:

https://github.com/plataformatec/devise/blob/ee01bac8b0b828b3da0d79c46115ba65c433d6c8/lib/devise/models/database_authenticatable.rb#L45

If you see this line, devise tries to call it's internal password_digest method while setting a new password or wherever you use password= method. But, as you already have a db column with name similar to the method (password_digest column), it is calling that instead of devise internal method. So, you are facing an error. (I may be wrong, this alone seems to be suspicious)


问:
How do I filter and select inside a expanded collection on Microsoft Graph?
This code works

```<code>https://graph.microsoft.com:443/v1.0/me/drive/root?$filter=Size eq 0&$expand=children($select=id,folder,name,parentReference,cwebUrl)&$select=Id,folder,name,parentReference,children,webUrl
</code>```

I want to filter inside the children:

```<code>https://graph.microsoft.com:443/v1.0/me/drive/root?$filter=Size eq 0&$expand=children($select=id,folder,name,parentReference,cwebUrl&$filter=Size eq 0)&$select=Id,folder,name,parentReference,children,webUrl
</code>```

答:
When filtering/selecting within an expand, you need to use ; as the separator, not &. So your URL should be:

https://graph.microsoft.com:443/v1.0/me/drive/root?$filter=Size eq 0&$expand=children($select=id,folder,name,parentReference,cwebUrl;$filter=Size eq 0)&$select=Id,folder,name,parentReference,children,webUrl

Here is an example of a URL on the TripPin example OData service to show this in action:

http://services.odata.org/V4/TripPinServiceRW/People?$expand=Trips($select=TripId,Name,Description;$filter=TripId eq 0)

Body:
This code works

https://graph.microsoft.com:443/v1.0/me/drive/root?$filter=Size eq 0&$expand=children($select=id,folder,name,parentReference,cwebUrl)&$select=Id,folder,name,parentReference,children,webUrl

I want to filter inside the children:

https://graph.microsoft.com:443/v1.0/me/drive/root?$filter=Size eq 0&$expand=children($select=id,folder,name,parentReference,cwebUrl&$filter=Size eq 0)&$select=Id,folder,name,parentReference,children,webUrl


问:
rxBindings - How to know what consumer type should be when debouncing click events?
using rxBindings im trying to slow down a click event but i would like to know what the parameter is need.

For example, here is a call i am doing on a imageview. So ImageView v;

```<code>RxView.clicks(v)
                  .throttleFirst(400, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
                  .subscribe(new Consumer<Object>() {

                      @Override
                      public void accept(@io.reactivex.annotations.NonNull Object v) throws Exception {
                          showBottomSheet(getAdapterPosition());
                      }
                  });

              but im im not sure what the parameter in accept should be ?

              I was expecting i would get the view here but when i try changing the type to View i get an error of no such method.
</code>```

答:
If you look at the source code of the Observable generate using RxView.clicks(), you will see that when the click happens, the following code is triggered:

```<code>observer.onNext(Notification.INSTANCE);
</code>```

that is defined in the library, as:

```<code>public enum Notification {
  INSTANCE
}
</code>```

It is just a convenient way for indicating that the event happened, it doesn't carry any extra information.

Body:
using rxBindings im trying to slow down a click event but i would like to know what the parameter is need.

For example, here is a call i am doing on a imageview. So ImageView v;

RxView.clicks(v)
                  .throttleFirst(400, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
                  .subscribe(new Consumer<Object>() {

                      @Override
                      public void accept(@io.reactivex.annotations.NonNull Object v) throws Exception {
                          showBottomSheet(getAdapterPosition());
                      }
                  });

              but im im not sure what the parameter in accept should be ?

              I was expecting i would get the view here but when i try changing the type to View i get an error of no such method.

Body:
If you look at the source code of the Observable generate using RxView.clicks(), you will see that when the click happens, the following code is triggered:

observer.onNext(Notification.INSTANCE);

that is defined in the library, as:

public enum Notification {
  INSTANCE
}

It is just a convenient way for indicating that the event happened, it doesn't carry any extra information.


问:
Has Anyone Got HTTP Compression Working with ASP.NET?
I've spent quite a bit of time on this but seem to be going nowhere. I have a large page that I really want to speed up. The obvious place to start seems to be HTTP compression, but I just can't seem to get it to work for me.

After considerable searching, I've tried several variations of the code below. It kind of works, but after refreshing the browser, the results seem to fall apart. They were turning to garbage when the page used caching. If I turn off caching, then the page seems right but I lose my CSS formatting (stored in a separate file) and get an error that an included JS file contains invalid characters.

Most of the resources I've found on the Web were either very old or focused on accessing IIS directly. My page is running on a shared hosting account and I do not have direct access to IIS7, which it's running on.

```<code>protected void Application_BeginRequest(object sender, EventArgs e)
{
    // Implement HTTP compression
    if (Request["HTTP_X_MICROSOFTAJAX"] == null) // Avoid compressing AJAX calls
    {
        // Retrieve accepted encodings
        string encodings = Request.Headers.Get("Accept-Encoding");
        if (encodings != null)
        {
            // Verify support for or gzip (deflate takes preference)
            encodings = encodings.ToLower();
            if (encodings.Contains("gzip") || encodings == "*")
            {
                Response.Filter = new GZipStream(Response.Filter,
                    CompressionMode.Compress);
                Response.AppendHeader("Content-Encoding", "gzip");
                Response.Cache.VaryByHeaders["Accept-encoding"] = true;
            }
            else if (encodings.Contains("deflate"))
            {
                Response.Filter = new DeflateStream(Response.Filter,
                    CompressionMode.Compress);
                Response.AppendHeader("Content-Encoding", "deflate");
                Response.Cache.VaryByHeaders["Accept-encoding"] = true;
            }
        }
    }
}
</code>```

Is anyone having better success with this?

答:
I've had good results using GZipStream and DeflateStream to write the output directly, although I'm not familiar with the Response.Filter property. Give this a whirl:

```<code>string response = "your output body";
string accept = Request.Headers["Accept-Encoding"];
if(accept == null) accept = "";
if (response.Length < 100 || !(accept.Contains("deflate") || accept.Contains("gzip")))
    Response.Write(response);
else
{
    byte[] compressed;
    bool useDeflate = accept.Contains("deflate");
    using (MemoryStream stream = new MemoryStream())
    {
        using (Stream deflate = useDeflate
            ? (Stream)new DeflateStream(stream, CompressionMode.Compress, true)
            : (Stream)new GZipStream(stream, CompressionMode.Compress, true))
        using (StreamWriter writer = new StreamWriter(deflate))
            writer.Write(response);
        compressed = new byte[stream.Length];
        stream.Position = 0;
        stream.Read(compressed, 0, compressed.Length);
    }
    Response.Headers["Content-Encoding"] = useDeflate ? "deflate" : "gzip";
    Response.BinaryWrite(compressed);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I've spent quite a bit of time on this but seem to be going nowhere. I have a large page that I really want to speed up. The obvious place to start seems to be HTTP compression, but I just can't seem to get it to work for me.

After considerable searching, I've tried several variations of the code below. It kind of works, but after refreshing the browser, the results seem to fall apart. They were turning to garbage when the page used caching. If I turn off caching, then the page seems right but I lose my CSS formatting (stored in a separate file) and get an error that an included JS file contains invalid characters.

Most of the resources I've found on the Web were either very old or focused on accessing IIS directly. My page is running on a shared hosting account and I do not have direct access to IIS7, which it's running on.

protected void Application_BeginRequest(object sender, EventArgs e)
{
    // Implement HTTP compression
    if (Request["HTTP_X_MICROSOFTAJAX"] == null) // Avoid compressing AJAX calls
    {
        // Retrieve accepted encodings
        string encodings = Request.Headers.Get("Accept-Encoding");
        if (encodings != null)
        {
            // Verify support for or gzip (deflate takes preference)
            encodings = encodings.ToLower();
            if (encodings.Contains("gzip") || encodings == "*")
            {
                Response.Filter = new GZipStream(Response.Filter,
                    CompressionMode.Compress);
                Response.AppendHeader("Content-Encoding", "gzip");
                Response.Cache.VaryByHeaders["Accept-encoding"] = true;
            }
            else if (encodings.Contains("deflate"))
            {
                Response.Filter = new DeflateStream(Response.Filter,
                    CompressionMode.Compress);
                Response.AppendHeader("Content-Encoding", "deflate");
                Response.Cache.VaryByHeaders["Accept-encoding"] = true;
            }
        }
    }
}

Is anyone having better success with this?

Body:
I've had good results using GZipStream and DeflateStream to write the output directly, although I'm not familiar with the Response.Filter property. Give this a whirl:

string response = "your output body";
string accept = Request.Headers["Accept-Encoding"];
if(accept == null) accept = "";
if (response.Length < 100 || !(accept.Contains("deflate") || accept.Contains("gzip")))
    Response.Write(response);
else
{
    byte[] compressed;
    bool useDeflate = accept.Contains("deflate");
    using (MemoryStream stream = new MemoryStream())
    {
        using (Stream deflate = useDeflate
            ? (Stream)new DeflateStream(stream, CompressionMode.Compress, true)
            : (Stream)new GZipStream(stream, CompressionMode.Compress, true))
        using (StreamWriter writer = new StreamWriter(deflate))
            writer.Write(response);
        compressed = new byte[stream.Length];
        stream.Position = 0;
        stream.Read(compressed, 0, compressed.Length);
    }
    Response.Headers["Content-Encoding"] = useDeflate ? "deflate" : "gzip";
    Response.BinaryWrite(compressed);
}


问:
Image need to be replaced with another image each time with a different button click in html page
I have 3 buttons in a html page and each button is associated with an image.
I need the working as follows,

ButtonA, ButtonB, ButtonC and ImageA, ImageB, Image C.

When ButtonA is clicked, ImageA should be displayed.
When ButtonB is clicked, ImageA should be REPLACED with ImageB.
When ButtonC is clicked, ImageB should be REPLACED with ImageC.
Again when ButtonA is clicked ImageC should be REPLACED with ImageA.

I can use only javascript and html for coding. Is it possible to accomplish it? If yes, Can you give me sample code which i can refer?

答:
Here is an example approach to do this using Javascript and HTML
for example: if you have 3 images inside images folder

```<code>+Images
 -a.png
 -b.png
 -c.png
</code>```

then you can do in javascript:

```<code>    var a = "images/a.png";
    var b = "images/a.png";
    var c = "images/a.png";

   //this function will be used to change image source whenever button is clicked.
    function changeImage(i)
    {
        var img = document.getElementById("img");
        switch(i)
        {
            case 'a': img.setAttribute('src',a); break;
            case 'b': img.setAttribute('src',b); break;
            case 'c': img.setAttribute('src',c); break;
            default: return false;
        }
    }
</code>```

Your HTML may look like this:

```<code><input type="button" value="Button A" onClick="changeImage('a');">
<input type="button" value="Button B" onClick="changeImage('b');">
<input type="button" value="Button C" onClick="changeImage('c');">
<img id="img" width="320px" height="220px">
</code>```

Body:
Here is an example approach to do this using Javascript and HTML
for example: if you have 3 images inside images folder

+Images
 -a.png
 -b.png
 -c.png

then you can do in javascript:

    var a = "images/a.png";
    var b = "images/a.png";
    var c = "images/a.png";

   //this function will be used to change image source whenever button is clicked.
    function changeImage(i)
    {
        var img = document.getElementById("img");
        switch(i)
        {
            case 'a': img.setAttribute('src',a); break;
            case 'b': img.setAttribute('src',b); break;
            case 'c': img.setAttribute('src',c); break;
            default: return false;
        }
    }

Your HTML may look like this:

<input type="button" value="Button A" onClick="changeImage('a');">
<input type="button" value="Button B" onClick="changeImage('b');">
<input type="button" value="Button C" onClick="changeImage('c');">
<img id="img" width="320px" height="220px">


问:
Django: How to mention number of process? like how it is done with Flaks
I am trying to create a simple Fibonacci web service with
* Django and
* Flask

I am using djangorestframework and flask_restful
I am doing this to make some comparison.

with Flask I am able to specify
the number of process or
to use threading etc. with Api in flask_restful

```<code>from flask import Flask, request, Response, jsonify
from flask_restful import abort, Resource, Api, reqparse
api = Api(app)
api.add_resource(Test, '/test/')

app.run(port=1234, host='0.0.0.0', threaded=True) #processes=50)
</code>```

My question, how to specify the same in django rest framework?
From the docs I am not able to find a straight forward answer, yet..

答:
That's because it's two different matters.
Django only provides a development server which obviously is for development and single thread/process.

If you want to tune the number of process, you'll need to run the Django project through gunicorn / uwsgi / mod_wsgi / ..., each of those lets you tune the process / threads.

Body:
I am trying to create a simple Fibonacci web service with
* Django and
* Flask

I am using djangorestframework and flask_restful
I am doing this to make some comparison.

with Flask I am able to specify
the number of process or
to use threading etc. with Api in flask_restful

from flask import Flask, request, Response, jsonify
from flask_restful import abort, Resource, Api, reqparse
api = Api(app)
api.add_resource(Test, '/test/')

app.run(port=1234, host='0.0.0.0', threaded=True) #processes=50)

My question, how to specify the same in django rest framework?
From the docs I am not able to find a straight forward answer, yet..


问:
Numbers in SELECT statements
I encountered sql queries like 'SELECT 1 FROM TABLE_NAME' or 'SELECT 2 FROM TABLE_NAME' while debugging a program. I am curious as to what the numbers in the queries do and what result set does it return.

Thanks

答:
It will return a single column with the number as value, with n rows, n being the number of rows returned from the select.

This is usefull in cases such as

```<code>SELECT *
FROM YourTable yt
WHERE EXISTS(
    SELECT 1
    FROM SomeOtherTable sot
    WHERE yt.ID = sot.ID
    )
</code>```

Also, good article at SELECT 1 vs SELECT * – An Interesting Observation

Title: Numbers in SELECT statements

Body:
It will return a single column with the number as value, with n rows, n being the number of rows returned from the select.

This is usefull in cases such as

SELECT *
FROM YourTable yt
WHERE EXISTS(
    SELECT 1
    FROM SomeOtherTable sot
    WHERE yt.ID = sot.ID
    )

Also, good article at SELECT 1 vs SELECT * – An Interesting Observation


问:
Jupyter notebook failed to adapt to default browser
I installed Jupiter notebook as part of Anaconda3. I changed to the default browser form Chrome to Safari, however, it still runs form Chrome.

To explicitly set the required browser, I created a configuration file as follow:

```<code>jupyter notebook --generate-config
</code>```

and changed this line in the config file from:

```<code># c.NotebookApp.browser = ''
</code>```

to

```<code>c.NotebookApp.browser = '~/Applications/Safari.app'
</code>```

I get the below error:

No web browser found: could not locate runnable browser.

How can I get Jupiter notebook to detect the default browser without explicitly configure it? If that is not possible, how to get it to work with different browser?

I am on Mac OS V. 10.12.5

答:
I am now able to run it on Safari by set the configuration file to have:

```<code>c.NotebookApp.browser = u'open -a /Applications/Safari.app %s'
</code>```

Still not sure why Jupiter doesn't recognise the default browser when configured to c.NotebookApp.browser = ''

Body:
I installed Jupiter notebook as part of Anaconda3. I changed to the default browser form Chrome to Safari, however, it still runs form Chrome.

To explicitly set the required browser, I created a configuration file as follow:

jupyter notebook --generate-config

and changed this line in the config file from:

# c.NotebookApp.browser = ''

to

c.NotebookApp.browser = '~/Applications/Safari.app'

I get the below error:

No web browser found: could not locate runnable browser.

How can I get Jupiter notebook to detect the default browser without explicitly configure it? If that is not possible, how to get it to work with different browser?

I am on Mac OS V. 10.12.5

Body:
I am now able to run it on Safari by set the configuration file to have:

c.NotebookApp.browser = u'open -a /Applications/Safari.app %s'

Still not sure why Jupiter doesn't recognise the default browser when configured to c.NotebookApp.browser = ''


问:
ASP.NET Web Api 2 code first JSON array returns null
I need help with my ASP.NET Web Api 2 project, I can make successfully send JSON data, I want to save Invites and the members who are invited.

Post Data Successfully saved on localdb

I used the scaffolding on Visual Studio 2017 and this is my first ever attempt on the .NET enviroment

```<code>{
    "InviteID": 6,
    "Subject": "sddsdsds",
    "DateTime": "54545:55",
    "Members": [
        {
            "MemberID": 8,
            "MemberName": "sdds",
            "IsAdmin": false,
            "MemberNumber": 0,
            "PhoneNumber": null,
            "InviteID": 6
        },
        {
            "MemberID": 9,
            "MemberName": "sdds",
            "IsAdmin": false,
            "MemberNumber": 0,
            "PhoneNumber": null,
            "InviteID": 6
        },
        {
            "MemberID": 10,
            "MemberName": "sdds",
            "IsAdmin": false,
            "MemberNumber": 0,
            "PhoneNumber": null,
            "InviteID": 6
        }
    ]
}
</code>```

But when I try to retrieve the invites, the members array is null:

```<code>[
    {
        "InviteID": 2,
        "Subject": null,
        "DateTime": null,
        "Members": null
    },
    {
        "InviteID": 3,
        "Subject": null,
        "DateTime": null,
        "Members": null
    },
    {
        "InviteID": 4,
        "Subject": "sddsdsds",
        "DateTime": "54545:55",
        "Members": null
    },
    {
        "InviteID": 5,
        "Subject": "sddsdsds",
        "DateTime": "54545:55",
        "Members": null
    },
    {
        "InviteID": 6,
        "Subject": "sddsdsds",
        "DateTime": "54545:55",
        "Members": null
    }
]
</code>```

My Invites model

```<code>public class Invite
{
    public int InviteID { get; set; }
    public string Subject { get; set; }
    public string DateTime { get; set; }
    public virtual List<Member> Members { get; set; }
}
</code>```

My Member model

```<code>public class Member
{
    public int MemberID { get; set; }
    public string MemberName { get; set; }
    public bool IsAdmin { get; set; }
    public int MemberNumber { get; set; }
    public string PhoneNumber { get; set; }
    public int InviteID { get; set; }
    [JsonIgnore]
    public virtual Invite Iinvite { get; set; }
}
</code>```

My controller

```<code>public class InvitesController : ApiController
{
    private InviteContext db = new InviteContext();

    public InvitesController()
    {
        db.Configuration.ProxyCreationEnabled = false;
    }

    // GET: api/Invites
    public IEnumerable<Invite> Getinvites()
    {
        return db.invites.ToList();
    }

    // GET: api/Invites/5
    [ResponseType(typeof(Invite))]
    public IHttpActionResult GetInvite(int id)
    {
        Invite invite = db.invites.Find(id);

        if (invite == null)
        {
            return NotFound();
        }

        return Ok(invite);
    }

    // PUT: api/Invites/5
    [ResponseType(typeof(void))]
    public IHttpActionResult PutInvite(int id, Invite invite)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != invite.InviteID)
        {
            return BadRequest();
        }

        db.Entry(invite).State = EntityState.Modified;

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!InviteExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

    // POST: api/Invites
    [ResponseType(typeof(Invite))]
    public IHttpActionResult PostInvite(Invite invite)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.invites.Add(invite);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = invite.InviteID }, invite);
    }

    // DELETE: api/Invites/5
    [ResponseType(typeof(Invite))]
    public IHttpActionResult DeleteInvite(int id)
    {
        Invite invite = db.invites.Find(id);

        if (invite == null)
        {
            return NotFound();
        }

        db.invites.Remove(invite);
        db.SaveChanges();

        return Ok(invite);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

    private bool InviteExists(int id)
    {
        return db.invites.Count(e => e.InviteID == id) > 0;
    }
}
</code>```

my db context

```<code>public class InviteContext : DbContext
{
    public DbSet<Invite> invites { get; set; }
    public DbSet<Member> members { get; set; }
}
</code>```

edit
** Data received when querying Member table**

```<code>[
    {
        "MemberID": 1,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 2
    },
    {
        "MemberID": 2,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 2
    },
    {
        "MemberID": 3,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 3
    },
    {
        "MemberID": 4,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 4
    },
    {
        "MemberID": 5,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 5
    },
    {
        "MemberID": 6,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 5
    },
    {
        "MemberID": 7,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 5
    },
    {
        "MemberID": 8,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 6
    },
    {
        "MemberID": 9,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 6
    },
    {
        "MemberID": 10,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 6
    }
]
</code>```

答:
The problem may be due to lazy loading members from database. To test if that's the case the following code (do not use in production!):

```<code>// GET: api/Invites
public IEnumerable<Invite> Getinvites()
{
    var invites = db.invites.ToList()
        .ForEach(invite => invite.Members = db.members
                    .Where(m => m.InviteId == invite.InviteId)
                    .ToList())
    return invites;
}
</code>```

This will force an eager load of members collection for each invite. If, after running this code, you get the expected results you'll need to configure your database context to load data eagerly.

DO NOT USE THE CODE ABOVE IN PRODUCTION!! Not only is it suboptimal but it also puts a lot of stress on database.

Body:
I need help with my ASP.NET Web Api 2 project, I can make successfully send JSON data, I want to save Invites and the members who are invited.

Post Data Successfully saved on localdb

I used the scaffolding on Visual Studio 2017 and this is my first ever attempt on the .NET enviroment

{
    "InviteID": 6,
    "Subject": "sddsdsds",
    "DateTime": "54545:55",
    "Members": [
        {
            "MemberID": 8,
            "MemberName": "sdds",
            "IsAdmin": false,
            "MemberNumber": 0,
            "PhoneNumber": null,
            "InviteID": 6
        },
        {
            "MemberID": 9,
            "MemberName": "sdds",
            "IsAdmin": false,
            "MemberNumber": 0,
            "PhoneNumber": null,
            "InviteID": 6
        },
        {
            "MemberID": 10,
            "MemberName": "sdds",
            "IsAdmin": false,
            "MemberNumber": 0,
            "PhoneNumber": null,
            "InviteID": 6
        }
    ]
}

But when I try to retrieve the invites, the members array is null:

[
    {
        "InviteID": 2,
        "Subject": null,
        "DateTime": null,
        "Members": null
    },
    {
        "InviteID": 3,
        "Subject": null,
        "DateTime": null,
        "Members": null
    },
    {
        "InviteID": 4,
        "Subject": "sddsdsds",
        "DateTime": "54545:55",
        "Members": null
    },
    {
        "InviteID": 5,
        "Subject": "sddsdsds",
        "DateTime": "54545:55",
        "Members": null
    },
    {
        "InviteID": 6,
        "Subject": "sddsdsds",
        "DateTime": "54545:55",
        "Members": null
    }
]

My Invites model

public class Invite
{
    public int InviteID { get; set; }
    public string Subject { get; set; }
    public string DateTime { get; set; }
    public virtual List<Member> Members { get; set; }
}

My Member model

public class Member
{
    public int MemberID { get; set; }
    public string MemberName { get; set; }
    public bool IsAdmin { get; set; }
    public int MemberNumber { get; set; }
    public string PhoneNumber { get; set; }
    public int InviteID { get; set; }
    [JsonIgnore]
    public virtual Invite Iinvite { get; set; }
}

My controller

public class InvitesController : ApiController
{
    private InviteContext db = new InviteContext();

    public InvitesController()
    {
        db.Configuration.ProxyCreationEnabled = false;
    }

    // GET: api/Invites
    public IEnumerable<Invite> Getinvites()
    {
        return db.invites.ToList();
    }

    // GET: api/Invites/5
    [ResponseType(typeof(Invite))]
    public IHttpActionResult GetInvite(int id)
    {
        Invite invite = db.invites.Find(id);

        if (invite == null)
        {
            return NotFound();
        }

        return Ok(invite);
    }

    // PUT: api/Invites/5
    [ResponseType(typeof(void))]
    public IHttpActionResult PutInvite(int id, Invite invite)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != invite.InviteID)
        {
            return BadRequest();
        }

        db.Entry(invite).State = EntityState.Modified;

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!InviteExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

    // POST: api/Invites
    [ResponseType(typeof(Invite))]
    public IHttpActionResult PostInvite(Invite invite)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.invites.Add(invite);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = invite.InviteID }, invite);
    }

    // DELETE: api/Invites/5
    [ResponseType(typeof(Invite))]
    public IHttpActionResult DeleteInvite(int id)
    {
        Invite invite = db.invites.Find(id);

        if (invite == null)
        {
            return NotFound();
        }

        db.invites.Remove(invite);
        db.SaveChanges();

        return Ok(invite);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

    private bool InviteExists(int id)
    {
        return db.invites.Count(e => e.InviteID == id) > 0;
    }
}

my db context

public class InviteContext : DbContext
{
    public DbSet<Invite> invites { get; set; }
    public DbSet<Member> members { get; set; }
}

edit
** Data received when querying Member table**

[
    {
        "MemberID": 1,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 2
    },
    {
        "MemberID": 2,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 2
    },
    {
        "MemberID": 3,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 3
    },
    {
        "MemberID": 4,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 4
    },
    {
        "MemberID": 5,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 5
    },
    {
        "MemberID": 6,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 5
    },
    {
        "MemberID": 7,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 5
    },
    {
        "MemberID": 8,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 6
    },
    {
        "MemberID": 9,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 6
    },
    {
        "MemberID": 10,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 6
    }
]

Body:
The problem may be due to lazy loading members from database. To test if that's the case the following code (do not use in production!):

// GET: api/Invites
public IEnumerable<Invite> Getinvites()
{
    var invites = db.invites.ToList()
        .ForEach(invite => invite.Members = db.members
                    .Where(m => m.InviteId == invite.InviteId)
                    .ToList())
    return invites;
}

This will force an eager load of members collection for each invite. If, after running this code, you get the expected results you'll need to configure your database context to load data eagerly.

DO NOT USE THE CODE ABOVE IN PRODUCTION!! Not only is it suboptimal but it also puts a lot of stress on database.


问:
node js post request body undefined
I am new to nodejs. I am getting request but req.body is undefined. Please help thanks in advance.

Here is my code

Server.js

```<code>var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
db = require('./database/database.js'),
PORT = process.env.PORT || 3000,
router = express.Router();
//Routers
var userActionsRouter = require('./routes/user-actions.js');
var userRouter =        require('./routes/user.js');
var transactionRouter = require('./routes/transaction.js');
//Routes
app.use('/api/v2/user_actions/', userActionsRouter);
app.listen(PORT, function(){
    console.log('We are connected'+PORT);
})
</code>```

Routing file

```<code>var express = require('express'),
router = express.Router(),
userActionController = require('../controllers/user-actions-controller.js'),
app = express();
//Sign-In
router.post('/sign_in', userActionController.signIn);
//Sign-Out
router.post('/sign_out', userActionController.signOut);
module.exports = router;
</code>```

My user-actions-controller.js file

```<code>var express = require('express');
bodyParser = require('body-parser');
app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
module.exports.signIn = function(req, res){
 console.log('params: ' + JSON.stringify(req.params));//{}
 console.log('body: ' + JSON.stringify(req.body));// undefined
 console.log('query: ' + JSON.stringify(req.query));//{}
 console.log("data:" +JSON.stringify(req.data));// undefined
})
</code>```

答:
add your 'content-type'with 'application/json';

```<code>'content-type': 'application/json'
</code>```

Title: node js post request body undefined

Body:
I am new to nodejs. I am getting request but req.body is undefined. Please help thanks in advance.

Here is my code

Server.js

var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
db = require('./database/database.js'),
PORT = process.env.PORT || 3000,
router = express.Router();
//Routers
var userActionsRouter = require('./routes/user-actions.js');
var userRouter =        require('./routes/user.js');
var transactionRouter = require('./routes/transaction.js');
//Routes
app.use('/api/v2/user_actions/', userActionsRouter);
app.listen(PORT, function(){
    console.log('We are connected'+PORT);
})

Routing file

var express = require('express'),
router = express.Router(),
userActionController = require('../controllers/user-actions-controller.js'),
app = express();
//Sign-In
router.post('/sign_in', userActionController.signIn);
//Sign-Out
router.post('/sign_out', userActionController.signOut);
module.exports = router;

My user-actions-controller.js file

var express = require('express');
bodyParser = require('body-parser');
app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
module.exports.signIn = function(req, res){
 console.log('params: ' + JSON.stringify(req.params));//{}
 console.log('body: ' + JSON.stringify(req.body));// undefined
 console.log('query: ' + JSON.stringify(req.query));//{}
 console.log("data:" +JSON.stringify(req.data));// undefined
})

Body:
add your 'content-type'with 'application/json';

'content-type': 'application/json'


问:
TensorFlow/TFLearn: ValueError: Cannot feed value of shape (64,10) for Tensor u'target/Y:0', which has shape '(?, 2)'
I have been trying to train a dataset using TFLearn to implement a convolutional neural network.
I have a dataset of 10 classes with image size is 64*32, 3 channels of input and 2 outputs i.e image detected/not detected.

Here is my code.

```<code># Load the data set
def read_data():
    with open("deep_logo.pickle", 'rb') as f:
        save = pickle.load(f)
        X = save['train_dataset']
        Y = save['train_labels']
        X_test = save['test_dataset']
        Y_test = save['test_labels']
        del save

    return [X, X_test], [Y, Y_test]

def reformat(dataset, labels):
    dataset = dataset.reshape((-1, 64, 32,3)).astype(np.float32)
    labels = (np.arange(10) == labels[:, None]).astype(np.float32)
    return dataset, labels

dataset, labels = read_data()
X,Y = reformat(dataset[0], labels[0])
X_test, Y_test = reformat(dataset[2], labels[2])
print('Training set', X.shape, Y.shape)
print('Test set', X_test.shape, Y_test.shape)

#building convolutional layers

network = input_data(shape=[None, 64, 32, 3],data_preprocessing=img_prep,
data_augmentation=img_aug)

network = conv_2d(network, 32, 3, activation='relu')

network = max_pool_2d(network, 2)

network = conv_2d(network, 64, 3, activation='relu')

network = conv_2d(network, 128, 3, activation='relu')

network = max_pool_2d(network, 2)

network = fully_connected(network, 512, activation='relu')

network = dropout(network, 0.5)

# Step 8: Fully-connected neural network with two outputs to make the final
prediction
network = fully_connected(network, 2, activation='softmax')

network = regression(network, optimizer='adam',
                     loss='categorical_crossentropy',
                     learning_rate=0.001)

# Wrap the network in a model object
model = tflearn.DNN(network, tensorboard_verbose=0, checkpoint_path='logo-
classifier.tfl.ckpt')

# Training it . 100 training passes and monitor it as it goes.
model.fit(X,Y, n_epoch=100, shuffle=True, validation_set=(X_test, Y_test),
          show_metric=True, batch_size=64,
          snapshot_epoch=True,
          run_id='logo-classifier')

# Save model when training is complete to a file
model.save("logo-classifier.tfl")
print("Network trained and saved as logo-classifier.tfl!")
</code>```

I get the following error

ValueError: Cannot feed value of shape (64, 10) for Tensor 'TargetsData/Y:0', which has shape '(?, 2)'

I have X and X_test with parameters of images and Y and Y_test with labeles in the pickle file. I have tried solutions from similar question, but the didn't work for me.

Any help would be appericiated.

Thanks.

答: Youve specified your output tensor shape as (?,2) and your labels is of the shape (?,10). Your label and output tensor shape must be the same.</p>

Body:
I have been trying to train a dataset using TFLearn to implement a convolutional neural network.
I have a dataset of 10 classes with image size is 64*32, 3 channels of input and 2 outputs i.e image detected/not detected.

Here is my code.

# Load the data set
def read_data():
    with open("deep_logo.pickle", 'rb') as f:
        save = pickle.load(f)
        X = save['train_dataset']
        Y = save['train_labels']
        X_test = save['test_dataset']
        Y_test = save['test_labels']
        del save

    return [X, X_test], [Y, Y_test]

def reformat(dataset, labels):
    dataset = dataset.reshape((-1, 64, 32,3)).astype(np.float32)
    labels = (np.arange(10) == labels[:, None]).astype(np.float32)
    return dataset, labels

dataset, labels = read_data()
X,Y = reformat(dataset[0], labels[0])
X_test, Y_test = reformat(dataset[2], labels[2])
print('Training set', X.shape, Y.shape)
print('Test set', X_test.shape, Y_test.shape)

#building convolutional layers

network = input_data(shape=[None, 64, 32, 3],data_preprocessing=img_prep,
data_augmentation=img_aug)

network = conv_2d(network, 32, 3, activation='relu')

network = max_pool_2d(network, 2)

network = conv_2d(network, 64, 3, activation='relu')

network = conv_2d(network, 128, 3, activation='relu')

network = max_pool_2d(network, 2)

network = fully_connected(network, 512, activation='relu')

network = dropout(network, 0.5)

# Step 8: Fully-connected neural network with two outputs to make the final
prediction
network = fully_connected(network, 2, activation='softmax')

network = regression(network, optimizer='adam',
                     loss='categorical_crossentropy',
                     learning_rate=0.001)

# Wrap the network in a model object
model = tflearn.DNN(network, tensorboard_verbose=0, checkpoint_path='logo-
classifier.tfl.ckpt')

# Training it . 100 training passes and monitor it as it goes.
model.fit(X,Y, n_epoch=100, shuffle=True, validation_set=(X_test, Y_test),
          show_metric=True, batch_size=64,
          snapshot_epoch=True,
          run_id='logo-classifier')

# Save model when training is complete to a file
model.save("logo-classifier.tfl")
print("Network trained and saved as logo-classifier.tfl!")

I get the following error

ValueError: Cannot feed value of shape (64, 10) for Tensor 'TargetsData/Y:0', which has shape '(?, 2)'

I have X and X_test with parameters of images and Y and Y_test with labeles in the pickle file. I have tried solutions from similar question, but the didn't work for me.

Any help would be appericiated.

Thanks.


问:
Exposing a web site through web services
I know what I am asking is somehow weird. There is a web application (which we don't have access to its source code), and we want to expose a few of its features as web services.

I was thinking to use something like Selenium WebDriver, so I simulate web clicks on the application according to the web service request.

I want to know whether this is a better solution or pattern to do this.

I shall mention that the application is written using Java, Spring MVC (it is not SPA) and Spring Security. And there is a CAS server providing SSO.

答:
I think it is a lot of overhead using a webdriver but it depends on what you really want to achieve. With the info you provided I would rather go with a restTemplate implementation sending the appropriate http messages to the existing webapp, wrap it with a nice @service layer and build your web service (rest or soap) on top of it.

The authentication is a matter of configuration, you can pack this in a microservice with @EnableOAuth2Sso and your restTemplate bean, thanks to spring boot, will handle the underlining auth part for you.


问:
Django rest-auth registration. How to return user_id with the key when using token authentication
I am using Djando rest_auth.registration.

My corresponding entry in urls.py is

```<code>url(r'^rest-auth/registration/', include('rest_auth.registration.urls'))
</code>```

My authentication class is rest_framework.authentication.TokenAuthentication

This rest API call works perfectly well.

When I register via this API I get the below response.

```<code>{
  "key": "3735f13cd69051579156f98ffda338a2d7a89bb5"
}
</code>```

I also want to include the user_id field in the response. How do I go about doing that. I tried extending the method get_response_data from class RegisterView(CreateAPIView): but unable to do so. Can someone please advise the best practice to achieve this. Code would be ideal. Thanks.

I want to use the rest-auth/registration/ url provided out of box by rest_auth.registration. I do not want to create a separate new URL for this.

My Settings.py as follows

```<code>INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'sdAPI.apps.SdapiConfig',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'rest_framework_swagger',
'rest_auth.registration',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.google',
'django_extensions',
]

# auth and allauth settings
LOGIN_REDIRECT_URL = '/'
SOCIALACCOUNT_QUERY_EMAIL = True
SOCIALACCOUNT_PROVIDERS = {
'facebook': {
    'SCOPE': ['email', 'publish_stream'],
    'METHOD': 'oauth2'  # instead of 'oauth2'
    }
}

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.IsAuthenticated',
    ),
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
)
}

SITE_ID = 1
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
REST_SESSION_LOGIN = False
</code>```

My urls.py as follows

```<code>urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^user/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
url(r'^rest-auth/', include('rest_auth.urls')),
url(r'^rest-auth/registration/',include('rest_auth.registration.urls')),
]
</code>```

答:
I think you only need to override the TOKEN_SERIALIZER option in your REST_AUTH_SERIALIZERS configuration.

```<code>from rest_framework.authtoken.models import Token

class TokenSerializer(serializers.ModelSerializer):

    class Meta:
        model = Token
        fields = ('key', 'user')
</code>```

Then, set it in your settings.py as shown in the docs,

```<code>REST_AUTH_SERIALIZERS = {
    'LOGIN_SERIALIZER': 'path.to.custom.LoginSerializer',
    'TOKEN_SERIALIZER': 'path.to.custom.TokenSerializer',
    ...
}
</code>```

Body:
I am using Djando rest_auth.registration.

My corresponding entry in urls.py is

url(r'^rest-auth/registration/', include('rest_auth.registration.urls'))

My authentication class is rest_framework.authentication.TokenAuthentication

This rest API call works perfectly well.

When I register via this API I get the below response.

{
  "key": "3735f13cd69051579156f98ffda338a2d7a89bb5"
}

I also want to include the user_id field in the response. How do I go about doing that. I tried extending the method get_response_data from class RegisterView(CreateAPIView): but unable to do so. Can someone please advise the best practice to achieve this. Code would be ideal. Thanks.

I want to use the rest-auth/registration/ url provided out of box by rest_auth.registration. I do not want to create a separate new URL for this.

My Settings.py as follows

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'sdAPI.apps.SdapiConfig',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'rest_framework_swagger',
'rest_auth.registration',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.google',
'django_extensions',
]

# auth and allauth settings
LOGIN_REDIRECT_URL = '/'
SOCIALACCOUNT_QUERY_EMAIL = True
SOCIALACCOUNT_PROVIDERS = {
'facebook': {
    'SCOPE': ['email', 'publish_stream'],
    'METHOD': 'oauth2'  # instead of 'oauth2'
    }
}

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.IsAuthenticated',
    ),
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
)
}

SITE_ID = 1
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
REST_SESSION_LOGIN = False

My urls.py as follows

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^user/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
url(r'^rest-auth/', include('rest_auth.urls')),
url(r'^rest-auth/registration/',include('rest_auth.registration.urls')),
]

Body:
I think you only need to override the TOKEN_SERIALIZER option in your REST_AUTH_SERIALIZERS configuration.

from rest_framework.authtoken.models import Token

class TokenSerializer(serializers.ModelSerializer):

    class Meta:
        model = Token
        fields = ('key', 'user')

Then, set it in your settings.py as shown in the docs,

REST_AUTH_SERIALIZERS = {
    'LOGIN_SERIALIZER': 'path.to.custom.LoginSerializer',
    'TOKEN_SERIALIZER': 'path.to.custom.TokenSerializer',
    ...
}


问:
What's the difference between plotconfusion and Confusionmat function in MATLAB?
I tried to display my confusion matrix from actual and predicted values while using both functions plotconfusion and Confusionmat. Both give different results. It's really strange for me. It seems Confusionmat is the transpose of plotconfusion. What should I do to plot similar results of Confusionmat on plotconfusion?

```<code>plotconfusion:

59     0     0
0    68      0
0     3     48
</code>```

And

```<code>Confusionmat:

59     0     0
0    68      3
0     0     48
</code>```

答:
You've understood things correctly - the confusion matrix generated by plotconfusion is the transpose of the confusion matrix generated by confusionmat.

This is documented - in the doc for plotconfusion it says

the rows correspond to the predicted class (Output Class), and the columns show the true class (Target Class).

and in the doc for confusionmat it says

C(i,j) is a count of observations known to be in group i but predicted to be in group j

If you want to convert between the two, just transpose them using '.

Why is it like this? Mostly for not very good reasons. plotconfusion is from Neural Network Toolbox, whereas confusionmat is from Statistics Toolbox, and the two toolboxes have different histories, purposes and conventions.

Statistics Toolbox has always been developed directly by MathWorks. By contrast, Neural Network Toolbox was originally developed by external academic authors, and marketed and sold by MathWorks (although recently much development has been brought in-house). Early versions of Neural Network Toolbox were mostly focussed on the application of neural networks to control theory, not to predictive modelling. So the toolboxes had a different history and purpose, and built up a different set of conventions.

It would make sense nowadays to gradually make the toolboxes more consistent and unified in their design, but that hasn't been done yet.

Body:
I tried to display my confusion matrix from actual and predicted values while using both functions plotconfusion and Confusionmat. Both give different results. It's really strange for me. It seems Confusionmat is the transpose of plotconfusion. What should I do to plot similar results of Confusionmat on plotconfusion?

plotconfusion:

59     0     0
0    68      0
0     3     48

And

Confusionmat:

59     0     0
0    68      3
0     0     48


问:
NullpointerException while invoking SendKeys through Selenium using PageFactory with Page Object
I have three classes. One for getting all elements from the Webpage, one for performing actions with those elements and one for the test scripts. I get a null pointer exception when I call a function from the test script. I figured out this is because I use @FindBy annotation, but I don't know how to fix this.

Elements Class:

```<code>public class LoginPageElements {

    @FindBy(id="loginId")
    private static WebElement userNameTextBox;

    @FindBy(id="password")
    private static WebElement userPasswordTextBox;

    @FindBy(id="QTP_LoginButton")
    private static WebElement loginButton;

    public static WebElement getUserNameTextBox(WebDriver driver){
        WebElement a=driver.findElement(By.id("loginId"));
        return a;
    }

    public static WebElement getUserPasswordTextBox(){
        return userPasswordTextBox;
    }

    public static WebElement getLoginButton(){
        return loginButton;
    }
}
</code>```

Actions Class:

```<code>public class LoginPageActions {

        public static void login(WebDriver driver,String username,String password){
            WebElement a=LoginPageElements.getUserNameTextBox(driver);
            a.sendKeys(username);
            LoginPageElements.getUserPasswordTextBox().sendKeys(password);
            LoginPageElements.getLoginButton().click();
        }

    }
</code>```

Test script:

```<code>public class Sample {
     public static String driverPath = "D:/Selenium/Chrome Driver latest/chromedriver.exe";
     public static WebDriver driver;
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", driverPath);

    ChromeOptions options = new ChromeOptions();
    options.addArguments("test-type");
    options.addArguments("start-maximized");
    options.addArguments("--js-flags=--expose-gc");
    options.addArguments("--enable-precise-memory-info");
    options.addArguments("--disable-popup-blocking");
    options.addArguments("--disable-default-apps");
    options.addArguments("--enable-automation");
    options.addArguments("test-type=browser");
    options.addArguments("disable-infobars");
    options.addArguments("--disable-extensions");
    options.setExperimentalOption("useAutomationExtension", false);

    driver = new ChromeDriver(options);

    driver.get("http://10.235.80.106:8080");

    LoginPageActions.login(driver,"acb", "adasd");
}
</code>```

There is no exception when I pass the WebDriver object from the test script to the element class. The problem occurs when I use the elements initialized with FindBy annotations because of no WebDriver instantiation. How do I fix this? Thanks

答:
You can continue to use the @FindBy annotations you just need to make sure you initialise the WebElements. To do this you should initialise your LoginPageElements using PageFactory:

```<code>LoginPageElements loginPageElements = PageFactory.initElements(webDriver, LoginPageElements.class);
</code>```

where webDriver is an instance of the WebDriver you are using to run the selenium tests.

ContentLicense: CC BY-SA 4.0

Body:
I have three classes. One for getting all elements from the Webpage, one for performing actions with those elements and one for the test scripts. I get a null pointer exception when I call a function from the test script. I figured out this is because I use @FindBy annotation, but I don't know how to fix this.

Elements Class:

public class LoginPageElements {

    @FindBy(id="loginId")
    private static WebElement userNameTextBox;

    @FindBy(id="password")
    private static WebElement userPasswordTextBox;

    @FindBy(id="QTP_LoginButton")
    private static WebElement loginButton;

    public static WebElement getUserNameTextBox(WebDriver driver){
        WebElement a=driver.findElement(By.id("loginId"));
        return a;
    }

    public static WebElement getUserPasswordTextBox(){
        return userPasswordTextBox;
    }

    public static WebElement getLoginButton(){
        return loginButton;
    }
}

Actions Class:

public class LoginPageActions {

        public static void login(WebDriver driver,String username,String password){
            WebElement a=LoginPageElements.getUserNameTextBox(driver);
            a.sendKeys(username);
            LoginPageElements.getUserPasswordTextBox().sendKeys(password);
            LoginPageElements.getLoginButton().click();
        }

    }

Test script:

public class Sample {
     public static String driverPath = "D:/Selenium/Chrome Driver latest/chromedriver.exe";
     public static WebDriver driver;
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", driverPath);

    ChromeOptions options = new ChromeOptions();
    options.addArguments("test-type");
    options.addArguments("start-maximized");
    options.addArguments("--js-flags=--expose-gc");
    options.addArguments("--enable-precise-memory-info");
    options.addArguments("--disable-popup-blocking");
    options.addArguments("--disable-default-apps");
    options.addArguments("--enable-automation");
    options.addArguments("test-type=browser");
    options.addArguments("disable-infobars");
    options.addArguments("--disable-extensions");
    options.setExperimentalOption("useAutomationExtension", false);

    driver = new ChromeDriver(options);

    driver.get("http://10.235.80.106:8080");

    LoginPageActions.login(driver,"acb", "adasd");
}

There is no exception when I pass the WebDriver object from the test script to the element class. The problem occurs when I use the elements initialized with FindBy annotations because of no WebDriver instantiation. How do I fix this? Thanks

Body:
You can continue to use the @FindBy annotations you just need to make sure you initialise the WebElements. To do this you should initialise your LoginPageElements using PageFactory:

LoginPageElements loginPageElements = PageFactory.initElements(webDriver, LoginPageElements.class);

where webDriver is an instance of the WebDriver you are using to run the selenium tests.


问:
Compress image android

I have an app where you can take a picture or select an image from the gallery.
The photo taken/selected once must be uploaded to the server.

My question is, as there are different devices with different sizes and resolutions, should the compressed image be loaded to the original size on the server or should it be scaled up and then compressed?
 What is the best way for scale an image for all device?

Now I'm using this algorithm when user take a photo by the camera or by gallery

```<code>private void setPic() throws IOException {
        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(mCurrentPhotoPath, options);
        // Calculate inSampleSize
        int sampleSize = calculateInSampleSize(options, 720, 720);
        Log.d("UserPanel", "Samplesize: " + sampleSize);
        Log.d("SquareImage", ""+image.getWidth());
        options.inSampleSize = sampleSize;

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        options.inPreferredConfig= Bitmap.Config.ARGB_8888;
        Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, options);
        Log.d("UserPanel", "Bytebitmap: " + bitmap.getByteCount());
        ExifInterface exif = new ExifInterface(mCurrentPhotoPath);
        String orientString = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
        int orientation = orientString != null ? Integer.parseInt(orientString) : ExifInterface.ORIENTATION_NORMAL;

        int rotationAngle = 0;
        if (orientation == ExifInterface.ORIENTATION_ROTATE_90) rotationAngle = 90;
        if (orientation == ExifInterface.ORIENTATION_ROTATE_180) rotationAngle = 180;
        if (orientation == ExifInterface.ORIENTATION_ROTATE_270) rotationAngle = 270;

        Matrix matrix = new Matrix();
        matrix.setRotate(rotationAngle, (float) bitmap.getWidth() / 2, (float) bitmap.getHeight() / 2);
        Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, options.outWidth, options.outHeight, matrix, true);
        Log.d("UserPanel", "Bytebitmaprotate: " + rotatedBitmap.getByteCount());
        MediaStore.Images.Media.insertImage(getContentResolver(), rotatedBitmap, imageFileName, "");
        File fdelete = new File(mCurrentPhotoPath);
        if (fdelete.delete()) Log.d("UserPanel", "Delete");
        imageToServer = getStringImage(rotatedBitmap);
    }
</code>```

This is calculateSampleSize

```<code>public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        Log.d("UserPanel", "Width: " + width + " height: " + height);
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) >= reqHeight
                    && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }
</code>```

To compress the image I fixed a size of 100KB

```<code>private String getStringImage(Bitmap bmp) {
        int compressQuality = 100;
        int streamLength = 0;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        do{
            ByteArrayOutputStream bmpStream = new ByteArrayOutputStream();
            Log.d("compressBitmap", "Quality: " + compressQuality);
            bmp.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpStream);
            byte[] bmpPicByteArray = bmpStream.toByteArray();
            streamLength = bmpPicByteArray.length;
            compressQuality -= 5;
            Log.d("compressBitmap", "Size: " + streamLength/1024+" kb");
        }while (streamLength >= 100000);
        bmp.compress(Bitmap.CompressFormat.JPEG, compressQuality, baos);
        byte[] imageBytes = baos.toByteArray();
        Log.d("UserPanel", "Bytebitmap compress: " + imageBytes.length);
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    }
</code>```

答:
Try to compress image using this class</p>

```<code>import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CompressImage {

    Context mContext;

    public CompressImage(Context context) {
        this.mContext = context;
    }

    public String compressImage(String imageUri) throws IOException {

        String filePath = getRealPathFromURI(imageUri);
        if(filePath == null)
        {
            filePath = imageUri;
        }
        Bitmap scaledBitmap = null;

        BitmapFactory.Options options = new BitmapFactory.Options();

//      by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
//      you try the use the bitmap here, you will get null.
        options.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeFile(filePath, options);

        int actualHeight = options.outHeight;
        int actualWidth = options.outWidth;

//      max Height and width values of the compressed image is taken as 816x612

        float maxHeight = 816.0f;
        float maxWidth = 612.0f;
        float imgRatio = actualWidth / actualHeight;
        float maxRatio = maxWidth / maxHeight;

//      width and height values are set maintaining the aspect ratio of the image

        if (actualHeight > maxHeight || actualWidth > maxWidth) {
            if (imgRatio < maxRatio) {
                imgRatio = maxHeight / actualHeight;
                actualWidth = (int) (imgRatio * actualWidth);
                actualHeight = (int) maxHeight;
            } else if (imgRatio > maxRatio) {
                imgRatio = maxWidth / actualWidth;
                actualHeight = (int) (imgRatio * actualHeight);
                actualWidth = (int) maxWidth;
            } else {
                actualHeight = (int) maxHeight;
                actualWidth = (int) maxWidth;

            }
        }

//      setting inSampleSize value allows to load a scaled down version of the original image

        options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);

//      inJustDecodeBounds set to false to load the actual bitmap
        options.inJustDecodeBounds = false;

//      this options allow android to claim the bitmap memory if it runs low on memory
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inTempStorage = new byte[16 * 1024];

        try {
//          load the bitmap from its path
            bmp = BitmapFactory.decodeFile(filePath, options);
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();

        }
        try {
            scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();
        }

        float ratioX = actualWidth / (float) options.outWidth;
        float ratioY = actualHeight / (float) options.outHeight;
        float middleX = actualWidth / 2.0f;
        float middleY = actualHeight / 2.0f;

        Matrix scaleMatrix = new Matrix();
        scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

        Canvas canvas = new Canvas(scaledBitmap);
        canvas.setMatrix(scaleMatrix);
        canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));

//      check the rotation of the image and display it properly
        ExifInterface exif;
        try {
            exif = new ExifInterface(filePath);

            int orientation = exif.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION, 0);
            Log.d("EXIF", "Exif: " + orientation);
            Matrix matrix = new Matrix();
            if (orientation == 6) {
                matrix.postRotate(90);
                Log.d("EXIF", "Exif: " + orientation);
            } else if (orientation == 3) {
                matrix.postRotate(180);
                Log.d("EXIF", "Exif: " + orientation);
            } else if (orientation == 8) {
                matrix.postRotate(270);
                Log.d("EXIF", "Exif: " + orientation);
            }
            scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
                    scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
                    true);
        } catch (IOException e) {
            e.printStackTrace();
        }

        FileOutputStream out = null;
        String filename = imageUri;
        File oldfile = new File(imageUri);
        if (oldfile.exists()) {
            oldfile.delete();
        }
        try {
            out = new FileOutputStream(filename);

//          write the compressed bitmap at the destination specified by filename.
            scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return filename;

    }

    public String getFilename() throws IOException {
//        File file = new File(Environment.getExternalStorageDirectory().getPath(), "MyFolder/Images");
//        if (!file.exists()) {
//            file.mkdirs();
//        }
//        String uriSting = (file.getAbsolutePath() + "/" + System.currentTimeMillis() + ".jpg");

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());
        String imageFileName = "twice_" + timeStamp + "_";
        File storageDir = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(imageFileName, /* prefix */
                ".jpg", /* suffix */
                storageDir /* directory */
        );

//        ChatRoomFragment.picturePath= image.getAbsolutePath();
        return image.getAbsolutePath();

    }

    private String getRealPathFromURI(String contentURI) {
        Uri contentUri = Uri.parse(contentURI);
        Cursor cursor = mContext.getContentResolver().query(contentUri, null, null, null, null);
        if (cursor == null) {
            return contentUri.getPath();
        } else {
            cursor.moveToFirst();
            int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            return cursor.getString(index);
        }
    }

    public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        final float totalPixels = width * height;
        final float totalReqPixelsCap = reqWidth * reqHeight * 2;
        while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
            inSampleSize++;
        }

        return inSampleSize;
    }

}
</code>```

Title: Compress image android

Body:
I have an app where you can take a picture or select an image from the gallery.
The photo taken/selected once must be uploaded to the server.

My question is, as there are different devices with different sizes and resolutions, should the compressed image be loaded to the original size on the server or should it be scaled up and then compressed?
 What is the best way for scale an image for all device?

Now I'm using this algorithm when user take a photo by the camera or by gallery

private void setPic() throws IOException {
        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(mCurrentPhotoPath, options);
        // Calculate inSampleSize
        int sampleSize = calculateInSampleSize(options, 720, 720);
        Log.d("UserPanel", "Samplesize: " + sampleSize);
        Log.d("SquareImage", ""+image.getWidth());
        options.inSampleSize = sampleSize;

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        options.inPreferredConfig= Bitmap.Config.ARGB_8888;
        Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, options);
        Log.d("UserPanel", "Bytebitmap: " + bitmap.getByteCount());
        ExifInterface exif = new ExifInterface(mCurrentPhotoPath);
        String orientString = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
        int orientation = orientString != null ? Integer.parseInt(orientString) : ExifInterface.ORIENTATION_NORMAL;

        int rotationAngle = 0;
        if (orientation == ExifInterface.ORIENTATION_ROTATE_90) rotationAngle = 90;
        if (orientation == ExifInterface.ORIENTATION_ROTATE_180) rotationAngle = 180;
        if (orientation == ExifInterface.ORIENTATION_ROTATE_270) rotationAngle = 270;

        Matrix matrix = new Matrix();
        matrix.setRotate(rotationAngle, (float) bitmap.getWidth() / 2, (float) bitmap.getHeight() / 2);
        Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, options.outWidth, options.outHeight, matrix, true);
        Log.d("UserPanel", "Bytebitmaprotate: " + rotatedBitmap.getByteCount());
        MediaStore.Images.Media.insertImage(getContentResolver(), rotatedBitmap, imageFileName, "");
        File fdelete = new File(mCurrentPhotoPath);
        if (fdelete.delete()) Log.d("UserPanel", "Delete");
        imageToServer = getStringImage(rotatedBitmap);
    }

This is calculateSampleSize

public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        Log.d("UserPanel", "Width: " + width + " height: " + height);
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) >= reqHeight
                    && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

To compress the image I fixed a size of 100KB

private String getStringImage(Bitmap bmp) {
        int compressQuality = 100;
        int streamLength = 0;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        do{
            ByteArrayOutputStream bmpStream = new ByteArrayOutputStream();
            Log.d("compressBitmap", "Quality: " + compressQuality);
            bmp.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpStream);
            byte[] bmpPicByteArray = bmpStream.toByteArray();
            streamLength = bmpPicByteArray.length;
            compressQuality -= 5;
            Log.d("compressBitmap", "Size: " + streamLength/1024+" kb");
        }while (streamLength >= 100000);
        bmp.compress(Bitmap.CompressFormat.JPEG, compressQuality, baos);
        byte[] imageBytes = baos.toByteArray();
        Log.d("UserPanel", "Bytebitmap compress: " + imageBytes.length);
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    }

Body:
Try to compress image using this class

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CompressImage {

    Context mContext;

    public CompressImage(Context context) {
        this.mContext = context;
    }

    public String compressImage(String imageUri) throws IOException {

        String filePath = getRealPathFromURI(imageUri);
        if(filePath == null)
        {
            filePath = imageUri;
        }
        Bitmap scaledBitmap = null;

        BitmapFactory.Options options = new BitmapFactory.Options();

//      by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
//      you try the use the bitmap here, you will get null.
        options.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeFile(filePath, options);

        int actualHeight = options.outHeight;
        int actualWidth = options.outWidth;

//      max Height and width values of the compressed image is taken as 816x612

        float maxHeight = 816.0f;
        float maxWidth = 612.0f;
        float imgRatio = actualWidth / actualHeight;
        float maxRatio = maxWidth / maxHeight;

//      width and height values are set maintaining the aspect ratio of the image

        if (actualHeight > maxHeight || actualWidth > maxWidth) {
            if (imgRatio < maxRatio) {
                imgRatio = maxHeight / actualHeight;
                actualWidth = (int) (imgRatio * actualWidth);
                actualHeight = (int) maxHeight;
            } else if (imgRatio > maxRatio) {
                imgRatio = maxWidth / actualWidth;
                actualHeight = (int) (imgRatio * actualHeight);
                actualWidth = (int) maxWidth;
            } else {
                actualHeight = (int) maxHeight;
                actualWidth = (int) maxWidth;

            }
        }

//      setting inSampleSize value allows to load a scaled down version of the original image

        options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);

//      inJustDecodeBounds set to false to load the actual bitmap
        options.inJustDecodeBounds = false;

//      this options allow android to claim the bitmap memory if it runs low on memory
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inTempStorage = new byte[16 * 1024];

        try {
//          load the bitmap from its path
            bmp = BitmapFactory.decodeFile(filePath, options);
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();

        }
        try {
            scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();
        }

        float ratioX = actualWidth / (float) options.outWidth;
        float ratioY = actualHeight / (float) options.outHeight;
        float middleX = actualWidth / 2.0f;
        float middleY = actualHeight / 2.0f;

        Matrix scaleMatrix = new Matrix();
        scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

        Canvas canvas = new Canvas(scaledBitmap);
        canvas.setMatrix(scaleMatrix);
        canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));

//      check the rotation of the image and display it properly
        ExifInterface exif;
        try {
            exif = new ExifInterface(filePath);

            int orientation = exif.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION, 0);
            Log.d("EXIF", "Exif: " + orientation);
            Matrix matrix = new Matrix();
            if (orientation == 6) {
                matrix.postRotate(90);
                Log.d("EXIF", "Exif: " + orientation);
            } else if (orientation == 3) {
                matrix.postRotate(180);
                Log.d("EXIF", "Exif: " + orientation);
            } else if (orientation == 8) {
                matrix.postRotate(270);
                Log.d("EXIF", "Exif: " + orientation);
            }
            scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
                    scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
                    true);
        } catch (IOException e) {
            e.printStackTrace();
        }

        FileOutputStream out = null;
        String filename = imageUri;
        File oldfile = new File(imageUri);
        if (oldfile.exists()) {
            oldfile.delete();
        }
        try {
            out = new FileOutputStream(filename);

//          write the compressed bitmap at the destination specified by filename.
            scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return filename;

    }

    public String getFilename() throws IOException {
//        File file = new File(Environment.getExternalStorageDirectory().getPath(), "MyFolder/Images");
//        if (!file.exists()) {
//            file.mkdirs();
//        }
//        String uriSting = (file.getAbsolutePath() + "/" + System.currentTimeMillis() + ".jpg");

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());
        String imageFileName = "twice_" + timeStamp + "_";
        File storageDir = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(imageFileName, /* prefix */
                ".jpg", /* suffix */
                storageDir /* directory */
        );

//        ChatRoomFragment.picturePath= image.getAbsolutePath();
        return image.getAbsolutePath();

    }

    private String getRealPathFromURI(String contentURI) {
        Uri contentUri = Uri.parse(contentURI);
        Cursor cursor = mContext.getContentResolver().query(contentUri, null, null, null, null);
        if (cursor == null) {
            return contentUri.getPath();
        } else {
            cursor.moveToFirst();
            int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            return cursor.getString(index);
        }
    }

    public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        final float totalPixels = width * height;
        final float totalReqPixelsCap = reqWidth * reqHeight * 2;
        while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
            inSampleSize++;
        }

        return inSampleSize;
    }

}


问:
RabbitMQ, docker, single queue, multiple consumers
We are using Docker, Spring and RabbitMq in our system. I'm new to AMQP and I'm trying to figure out how the exchanges, queues, bindings and connections work in our system.
We have multiple dockerized applications.

In short, when the applications start, they each start to listen to the same queue, and I don't understand how they all can expect to receive the same message. There were some similar questions in stackoverflow that gave me impression that our current system is possibly flawed.

In more detail:

When the docker containers start, multiple applications in different containers use RabbitAdmin to

```<code>declare the same exchange: rabbitAdmin.declareExchange(exchange)
declare the same queue: rabbitAdmin.declareQueue(queue)
bind those together: rabbitAdmin.declareBinding(BindingBuilder.bind(queue).to(exhange).with("theSameKey");
</code>```

They do this because they want to listen to the same messages.
As far as I understand, only one of the dockerized programs manages to create the exchange and the queue, and the rest of them try but that has no effect.

After that, each of these applications create and start SimpleMessageContainers for the queue:

```<code>simpleMessageContainer.setMessageListener(messageListener)
simpleMessageContainer.addQueueNames(queue.getName())
simpleMessageContainer.start()
</code>```

Using rabbitmqctl and rabbitmq's web interface, I can see that a single queue has multiple consumers on different channels, corresponding to different docker containers.

Isn't it so that the messageListener resides within the application but RabbitMq creates a Consumer for the queue at the broker when addQueueNames is called, and this Consumer then forwards messages through the connection to the application local messageListener?

Since multiple applications within different docker containers do that same, there are several Consumers for the same queue,  just like I'm seeing with rabbitmqctl.

What I don't understand is that doesn't RabbitMq pass messages that end up in the queue to the channels/consumers in a round robin fashion, so that only one of the dockerized application will receive it?
The exhanges are of direct and topic type with no fan-out exchanges.
If all the dockerized applications wanted to receive the same message, shouldn't then all of them create an own queue for the same exhance with an own queue name but with the same routing key?

I fail to see how the current implementation possibly works properly.

答:
In short, when the applications start, they each start to listen to the same queue, and I don't understand how they all can expect to receive the same message.

They will never receive the same message. Only one will pick a message.

To perform what you ask - all receive same message - it must be a Topic, not a Queue.

BTW: there is nothing specific about Docker or containers, multiple consumers can run in many ways. As example in classic clustered environment.

Body:
We are using Docker, Spring and RabbitMq in our system. I'm new to AMQP and I'm trying to figure out how the exchanges, queues, bindings and connections work in our system.
We have multiple dockerized applications.

In short, when the applications start, they each start to listen to the same queue, and I don't understand how they all can expect to receive the same message. There were some similar questions in stackoverflow that gave me impression that our current system is possibly flawed.

In more detail:

When the docker containers start, multiple applications in different containers use RabbitAdmin to

declare the same exchange: rabbitAdmin.declareExchange(exchange)
declare the same queue: rabbitAdmin.declareQueue(queue)
bind those together: rabbitAdmin.declareBinding(BindingBuilder.bind(queue).to(exhange).with("theSameKey");

They do this because they want to listen to the same messages.
As far as I understand, only one of the dockerized programs manages to create the exchange and the queue, and the rest of them try but that has no effect.

After that, each of these applications create and start SimpleMessageContainers for the queue:

simpleMessageContainer.setMessageListener(messageListener)
simpleMessageContainer.addQueueNames(queue.getName())
simpleMessageContainer.start()

Using rabbitmqctl and rabbitmq's web interface, I can see that a single queue has multiple consumers on different channels, corresponding to different docker containers.

Isn't it so that the messageListener resides within the application but RabbitMq creates a Consumer for the queue at the broker when addQueueNames is called, and this Consumer then forwards messages through the connection to the application local messageListener?

Since multiple applications within different docker containers do that same, there are several Consumers for the same queue,  just like I'm seeing with rabbitmqctl.

What I don't understand is that doesn't RabbitMq pass messages that end up in the queue to the channels/consumers in a round robin fashion, so that only one of the dockerized application will receive it?
The exhanges are of direct and topic type with no fan-out exchanges.
If all the dockerized applications wanted to receive the same message, shouldn't then all of them create an own queue for the same exhance with an own queue name but with the same routing key?

I fail to see how the current implementation possibly works properly.


问:
How to open a specific activity when the app is running in background?
I need to open a specific activity when the app is running in background (not killed) using Firebase notification system. As per the doc, Notification tray will open the default activity and send the intent to it.

To open a specific activity, I added an  <Intent> to Manifest file:

```<code> <intent-filter>
        <action android:name="OPEN_ACTIVITY_1" />
        <category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</code>```

Sending data through Postman as a Post request:

```<code>{
  "notification" : {
      "OPEN_ACTIVITY_1":".activity.TemActivity_",
      "body" : "update !"
   },
  "data": {
      "type":0,
      "question":"open the activity"
 },
 "to": "dDmXZa9k6-o:APA91bEx91oyYnOyzK3kX839EqbvA2CgY74s-
fLUs8MCYZzVmnp-RpgyI3zicEFVS37K7A4kPpbbqYU9hMBEbs-
PrBXlSTYTOBVd7O3CNvl1vaTEbGIHjLLRTWvEK2VRCvJkhQTXWtr3"
}
</code>```

However, I am getting the notificaiton and when I am clicking the notificaiton tray. It's always opening the default intent activity. What Am I doing wrong here to open the TeamActivity_ (Using android annotation)

Edit-1

```<code>public class MessagingService extends FirebaseMessagingService {

public String TAG = "Data";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    System.out.println("data");
  }
}
</code>```

My token is valid because I can see the notification tray.

答:
Let me give you a simple example.

In AndroidManifest (Let's say you want to open SampleActivity_)

```<code>    <activity android:name=".activity.SampleActivity_"
        android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
        android:theme="@style/AppTheme">

            <intent-filter>
                <action android:name="OPEN_ACTIVITY_1"/>
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

        </activity>
</code>```

Now make a Post request

```<code>{
 "notification" : {
       "click_action":"OPEN_ACTIVITY_1",
       "body" : "new Symulti update !"
 },
  "data": {
      "type":0,
      "question":"what are you doing?"
},
   "to": "cfXBKN_vhFw:APA91bH268KeCeFLlp0OHH-
          UNPgR_njeNmJET0PvrcrHe6VLN-
          w6UQCCO_LbN0TeNhpjqDDStNnt4t0FGQ6S5puz49QSdsK1BKb8R7Q1uYNpP_
          UqsRIETuOh1TRst
          JAsfJS7VI7Atpfx"
}
</code>```

I have tested it and working perfectly!

Only when app is running in background

Body:
I need to open a specific activity when the app is running in background (not killed) using Firebase notification system. As per the doc, Notification tray will open the default activity and send the intent to it.

To open a specific activity, I added an  <Intent> to Manifest file:

 <intent-filter>
        <action android:name="OPEN_ACTIVITY_1" />
        <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

Sending data through Postman as a Post request:

{
  "notification" : {
      "OPEN_ACTIVITY_1":".activity.TemActivity_",
      "body" : "update !"
   },
  "data": {
      "type":0,
      "question":"open the activity"
 },
 "to": "dDmXZa9k6-o:APA91bEx91oyYnOyzK3kX839EqbvA2CgY74s-
fLUs8MCYZzVmnp-RpgyI3zicEFVS37K7A4kPpbbqYU9hMBEbs-
PrBXlSTYTOBVd7O3CNvl1vaTEbGIHjLLRTWvEK2VRCvJkhQTXWtr3"
}

However, I am getting the notificaiton and when I am clicking the notificaiton tray. It's always opening the default intent activity. What Am I doing wrong here to open the TeamActivity_ (Using android annotation)

Edit-1

public class MessagingService extends FirebaseMessagingService {

public String TAG = "Data";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    System.out.println("data");
  }
}

My token is valid because I can see the notification tray.

Body:
Let me give you a simple example.

In AndroidManifest (Let's say you want to open SampleActivity_)

    <activity android:name=".activity.SampleActivity_"
        android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
        android:theme="@style/AppTheme">

            <intent-filter>
                <action android:name="OPEN_ACTIVITY_1"/>
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

        </activity>

Now make a Post request

{
 "notification" : {
       "click_action":"OPEN_ACTIVITY_1",
       "body" : "new Symulti update !"
 },
  "data": {
      "type":0,
      "question":"what are you doing?"
},
   "to": "cfXBKN_vhFw:APA91bH268KeCeFLlp0OHH-
          UNPgR_njeNmJET0PvrcrHe6VLN-
          w6UQCCO_LbN0TeNhpjqDDStNnt4t0FGQ6S5puz49QSdsK1BKb8R7Q1uYNpP_
          UqsRIETuOh1TRst
          JAsfJS7VI7Atpfx"
}

I have tested it and working perfectly!

Only when app is running in background


问:
Web.xml issue cannot find declaration
This is the start of my web.xml in which the errors occur

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee; http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
</code>```

Eclipse shows these 2 errors :

Error 1 : cvc-elt.1: Cannot find the declaration of element 'web-app'. web.xml /"app.module"/src/main/webapp/WEB-INF   line 5  XML Problem

Error 2 : Referenced file contains errors (jar:file:/C:/Program Files/eclipse/plugins/org.jboss.tools.as.catalog_3.2.4.v20170308-1740.jar!/schema/xsd/jboss-ejb3-spec-2_0.xsd).

答:
Try using:

```<code> <web-app xmlns="http://java.sun.com/xml/ns/javaee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
      version="2.5">
</code>```

Title: Web.xml issue cannot find declaration

Body:
This is the start of my web.xml in which the errors occur

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee; http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">

Eclipse shows these 2 errors :

Error 1 : cvc-elt.1: Cannot find the declaration of element 'web-app'. web.xml /"app.module"/src/main/webapp/WEB-INF   line 5  XML Problem

Error 2 : Referenced file contains errors (jar:file:/C:/Program Files/eclipse/plugins/org.jboss.tools.as.catalog_3.2.4.v20170308-1740.jar!/schema/xsd/jboss-ejb3-spec-2_0.xsd).

Body:
Try using:

 <web-app xmlns="http://java.sun.com/xml/ns/javaee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
      version="2.5">