问:
How to databind a gridview from an other aspx file that is opened as a pop up window in asp.net?
My problem is the following. I have an aspx webform(ErrorList.aspx). This webform has a gridview control and a sqldatasource control. The sqldatasource control has the select statement from the table and the gridview displays the result. The last column contains an imagebutton. Imagebutton's code has this :
OnClientClick="addFileWindow(this);"
You can see there is an onclientclick part and a javascript function is called here. Function's code is here :

```<code>function addFileWindow(ib) {

            var id = ib;
            var azon = id.title;

            $("#Azon_row_lbl").hide();
            $("#Azon_row_lbl").text(azon);

            window.open("addNewFile.aspx", "", "scrollbars=yes, resizable=yes, width=600, height=300");

            return false;
        }
</code>```

So if you click on the imagebutton a pop up window will be opened.
It contains a fileupload manager control and an upload button and an error label. Error label will be displayed if there is no selected file. Error label will be on hide status if there is a selected file. If everything is alright and there is a selected file the program will update the database cell with the name of the file and the file will be uploaded to the server into the uploaded files folder in the project. Its working. So this is not problem for me. Here is the code of the addNewFile.aspx:
Client side :

```<code><title>File upload</title>

<script src="Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>

<script type="text/javascript">
    $(function () {
        if (window.opener != null && !window.opener.closed) {

            var parent = $(window.opener.document).contents();
            $("#myDiv1").html("<u>Here is the ID of the record of the new file: </u>");
            $("#myDiv2").html(parent.find("#Azon_row_lbl").html());

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

```<code><form id="form1" runat="server">

    <div id="myDiv1" runat="server" style="color: white;"></div>
    <div id="myDiv2" runat="server" style="color: white;"></div>

    <asp:Label ID="lbl_id" runat="server"></asp:Label>
    <br /><br />

    <asp:FileUpload ID="fu_ter_ell_update_attch" runat="server"></asp:FileUpload>

    <br /><br />

    <asp:Button ID="Upload_file_bttn" runat="server" Text="Upload" OnClick="Upload_file_bttn_Click" Height="33px" style="font-weight: 700; color: #FFFFFF; background-color: #000000;" Width="77px" />

    <br /><br />

    <asp:Label ID="Error_label" runat="server" Visible="false" Text="There is no selected file!" style="font-weight: 700; color: #FF0000"></asp:Label>

</form>

 <script type="text/javascript">

     $("#<%= Upload_file_bttn.ClientID %>").click(function () {

         var ID = $('#myDiv2').text();
         var filename = $('#<%= fu_ter_ell_update_attch.ClientID %>').val();

         if (filename != "")
         {
             var res = filename.split("\\");
             //   res[res.length-1]   this reference contains the name of the file . extension for example apple.jpg
             var file_exist = "";

             $.ajax({
                 type: 'POST',
                 contentType: "application/json; charset=utf-8",
                 url: 'addNewFile.aspx/DataBase_Has_This_FileName_Or_Not',
                 data: "{'FileName':'" + res[res.length - 1] + "'}",
                 async: false,
                 success: function (response) {
                     file_exist = response.d;
                 },
                 error: function () {
                     alert("Error");
                     return false;
                 }
             });

             if (file_exist == true)
             {
                 alert("Database has this filename already. Change it and try to upload again.");
                 return false;
             }
             else
             {
                 $.ajax({
                     type: 'POST',
                     contentType: "application/json; charset=utf-8",
                     url: 'addNewFile.aspx/Attach_FileName_Into_Row',
                     data: "{'ID':'" + ID + "','FileName':'" + res[res.length - 1] + "'}",
                     async: false,
                     success: function (response) {

                     },
                     error: function () {
                         alert("Error");
                         return false;
                     }
                 });
             }

         }

     });

</script>
</code>```

Server side :

```<code>protected void Page_Load(object sender, EventArgs e)
{

}

[WebMethod]
public static bool DataBase_Has_This_FileName_Or_Not(string FileName)
{
    bool retvalue = false;

    string selectStatement = "SELECT * FROM [DNTShiftReport].[dbo].[ter_ell_hiany_DNT] WHERE [Filename] = @Filename";

    string connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DNTShiftReportConnectionString"].ConnectionString;

    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        using (SqlCommand comm = new SqlCommand(selectStatement, conn))
        {
            try
            {
                comm.Parameters.Add("@Filename", SqlDbType.NVarChar).Value = FileName;

                conn.Open();

                using (SqlDataReader dr = comm.ExecuteReader())
                {
                    if (dr.HasRows)
                    {
                        retvalue = true;
                    }
                }
            }
            catch (Exception e) { Console.WriteLine("Error: " + e.Message); }
            if (conn.State == System.Data.ConnectionState.Open) conn.Close();
        }
    }

    return retvalue;
}

[WebMethod]
public static void Attach_FileName_Into_Row(string ID, string FileName)
{
    string connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DNTShiftReportConnectionString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(connectionString))
    {

        con.Open();

        using (SqlCommand comm = con.CreateCommand())
        {
            comm.CommandText = "UPDATE [ter_ell_hiany_DNT] SET [Filename] = @filename WHERE [ID] = @upd_id";
            comm.Parameters.Add("@filename", SqlDbType.NVarChar).Value = FileName;
            comm.Parameters.Add("@upd_id", SqlDbType.Int).Value = Convert.ToInt32(ID);
            comm.ExecuteNonQuery();
            con.Close();
        }
    }
}

protected void Upload_file_bttn_Click(object sender, EventArgs e)
{
    if (fu_ter_ell_update_attch.HasFile)
    {

        Error_label.Visible = false;

        string filename = Path.GetFileName(fu_ter_ell_update_attch.FileName);
        string saveDir = @"\DNTShiftReport\Uploaded_files\";
        string appPath = Server.MapPath(saveDir);
        string fullpath = appPath + filename;
        fu_ter_ell_update_attch.SaveAs(fullpath);

        Session["POP_UP_CLOSED"] = "CLOSED";
        ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.open('close.html', '_self', null);", true); // close the pop up window.

    }
    else
    {
        Error_label.Visible = true;
    }
}
</code>```

So my problem is that, database is updated, file is uploaded, but the gridview should be databinded automatically when the pop up window is closed by the button. I cant databind the gridview on the addNewFile.aspx because the gridview's location is the ErrorList.aspx. I tried every solution that I find in the google in the last 3 days but nothing is working.

答:
It is completely client side problem. Possible solution:

Instead of

```<code>window.open("addNewFile.aspx", "", "scrollbars=yes, resizable=yes, width=600, height=300");
</code>```

you can have

```<code>var addNewFileWindow = window.open("addNewFile.aspx", "", "scrollbars=yes, resizable=yes, width=600, height=300");
addNewFileWindow.onBeforeUnload = function(){
// handle window closing
// just reload the page
window.location.reload()
}
</code>```

Body:
My problem is the following. I have an aspx webform(ErrorList.aspx). This webform has a gridview control and a sqldatasource control. The sqldatasource control has the select statement from the table and the gridview displays the result. The last column contains an imagebutton. Imagebutton's code has this :
OnClientClick="addFileWindow(this);"
You can see there is an onclientclick part and a javascript function is called here. Function's code is here :

function addFileWindow(ib) {

            var id = ib;
            var azon = id.title;

            $("#Azon_row_lbl").hide();
            $("#Azon_row_lbl").text(azon);

            window.open("addNewFile.aspx", "", "scrollbars=yes, resizable=yes, width=600, height=300");

            return false;
        }

So if you click on the imagebutton a pop up window will be opened.
It contains a fileupload manager control and an upload button and an error label. Error label will be displayed if there is no selected file. Error label will be on hide status if there is a selected file. If everything is alright and there is a selected file the program will update the database cell with the name of the file and the file will be uploaded to the server into the uploaded files folder in the project. Its working. So this is not problem for me. Here is the code of the addNewFile.aspx:
Client side :

<title>File upload</title>

<form id="form1" runat="server">

    <asp:Label ID="lbl_id" runat="server"></asp:Label>

    <asp:FileUpload ID="fu_ter_ell_update_attch" runat="server"></asp:FileUpload>

    <asp:Button ID="Upload_file_bttn" runat="server" Text="Upload" OnClick="Upload_file_bttn_Click" Height="33px" style="font-weight: 700; color: #FFFFFF; background-color: #000000;" Width="77px" />

    <asp:Label ID="Error_label" runat="server" Visible="false" Text="There is no selected file!" style="font-weight: 700; color: #FF0000"></asp:Label>

</form>

Server side :

protected void Page_Load(object sender, EventArgs e)
{

}

[WebMethod]
public static bool DataBase_Has_This_FileName_Or_Not(string FileName)
{
    bool retvalue = false;

    string selectStatement = "SELECT * FROM [DNTShiftReport].[dbo].[ter_ell_hiany_DNT] WHERE [Filename] = @Filename";

    string connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DNTShiftReportConnectionString"].ConnectionString;

    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        using (SqlCommand comm = new SqlCommand(selectStatement, conn))
        {
            try
            {
                comm.Parameters.Add("@Filename", SqlDbType.NVarChar).Value = FileName;

                conn.Open();

                using (SqlDataReader dr = comm.ExecuteReader())
                {
                    if (dr.HasRows)
                    {
                        retvalue = true;
                    }
                }
            }
            catch (Exception e) { Console.WriteLine("Error: " + e.Message); }
            if (conn.State == System.Data.ConnectionState.Open) conn.Close();
        }
    }

    return retvalue;
}

[WebMethod]
public static void Attach_FileName_Into_Row(string ID, string FileName)
{
    string connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DNTShiftReportConnectionString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(connectionString))
    {

        con.Open();

        using (SqlCommand comm = con.CreateCommand())
        {
            comm.CommandText = "UPDATE [ter_ell_hiany_DNT] SET [Filename] = @filename WHERE [ID] = @upd_id";
            comm.Parameters.Add("@filename", SqlDbType.NVarChar).Value = FileName;
            comm.Parameters.Add("@upd_id", SqlDbType.Int).Value = Convert.ToInt32(ID);
            comm.ExecuteNonQuery();
            con.Close();
        }
    }
}

protected void Upload_file_bttn_Click(object sender, EventArgs e)
{
    if (fu_ter_ell_update_attch.HasFile)
    {

        Error_label.Visible = false;

        string filename = Path.GetFileName(fu_ter_ell_update_attch.FileName);
        string saveDir = @"\DNTShiftReport\Uploaded_files\";
        string appPath = Server.MapPath(saveDir);
        string fullpath = appPath + filename;
        fu_ter_ell_update_attch.SaveAs(fullpath);

        Session["POP_UP_CLOSED"] = "CLOSED";
        ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.open('close.html', '_self', null);", true); // close the pop up window.

    }
    else
    {
        Error_label.Visible = true;
    }
}

So my problem is that, database is updated, file is uploaded, but the gridview should be databinded automatically when the pop up window is closed by the button. I cant databind the gridview on the addNewFile.aspx because the gridview's location is the ErrorList.aspx. I tried every solution that I find in the google in the last 3 days but nothing is working.

Body:
It is completely client side problem. Possible solution:

Instead of

window.open("addNewFile.aspx", "", "scrollbars=yes, resizable=yes, width=600, height=300");

you can have

var addNewFileWindow = window.open("addNewFile.aspx", "", "scrollbars=yes, resizable=yes, width=600, height=300");
addNewFileWindow.onBeforeUnload = function(){
// handle window closing
// just reload the page
window.location.reload()
}


来源: stackexchange

问:
Recommended add-ons/plugins for Microsoft Visual Studio
Can anyone recommend any good add-ons or plugins for Microsoft Visual Studio?

Freebies are preferred, but if it is worth the cost then that's fine.

答: +1 for CodeRush & Refactor Pro. I've been using CodeRush since its Delphi incarnations, and it's utterly wonderful. The mantra of "Code at the speed of thought" is very close to reality  ;)</p>

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: David McGraw

OwnerDisplayName: moobaa

ContentLicense: CC BY-SA 2.5


问:
Shuffling biased random numbers
While thinking about this question and conversing with the participants, the idea came up that shuffling a finite set of clearly biased random numbers makes them random because you don't know the order in which they were chosen.  Is this true and if so can someone point to some resources?

EDIT:  I think I might have been a little unclear. Suppose a bad random numbers generator. Take n values. These are biased(the rng is bad). Is there a way through shuffling to make the output of the rng over multiple trials statistically match the output of a known good rng?

答: Just shuffling a set of numbers of already random numbers won't do anything to the probability distribution of course. That would mean false. Perhaps I misunderstand your question though?</p>

OwnerDisplayName: JPunyon

Title: Shuffling biased random numbers

LastEditorDisplayName: JPunyon

OwnerDisplayName: Noldorin


问:
How to tell how much memory an Android app has left to use?
I'm writing an image manipulation tool and, for image quality reasons, want to edit the image in as large a size as possible.

I need to be careful that I don't run out of memory while my app is running. In addition, I want to take advantage of devices with lots of memory. For example, I'd like to support medium size images on less powerful devices like the G1 and let more powerful devices like the Samsung Galaxy S support large images.

Is there a reliable way to gauge how much memory my app can use?

My current idea is that, when deciding on the image size to load, the device could calculate the image size that brings memory usage for the app as close to about 70% as possible (i.e. not 100% as you don't want the app crashing on small allocations later or because of memory fragmentation)

I've found I can use the following code to return a percentage of the available memory:

```<code>double totalMemoryUsed = (Runtime.getRuntime().totalMemory() + android.os.Debug.getNativeHeapAllocatedSize());
int percentUsed = (int)(totalMemoryUsed / Runtime.getRuntime().maxMemory() * 100);
</code>```

New bitmaps add to the native heap allocated part. This seems reliable in that my app will predictably crash with an out of memory error when percentUsed goes above 100%. Are there any caveats to the above calculation I need to be aware of?

答:
Are there any caveats to the above
  calculation I need to be aware of?

My first thought is that you really can only rely on the accuracy of a calculation like that at the instant when you perform it.  Android has all sorts of services and other applications that are running in the background.  At any given instant, the amount of memory currently in use is going to change.  There is no way to tell by how much until you perform a calculation again.  Additionally, no two phones are going to be alike so you really can't accurately estimate it.

You would almost need a thread or async task recalculating this on a constant basis which I'm not sure is a good idea.

I would stray away from this, and consider building your app using a different strategy.  But good luck to you if you continue to pursure it.

Body:
I'm writing an image manipulation tool and, for image quality reasons, want to edit the image in as large a size as possible.

I need to be careful that I don't run out of memory while my app is running. In addition, I want to take advantage of devices with lots of memory. For example, I'd like to support medium size images on less powerful devices like the G1 and let more powerful devices like the Samsung Galaxy S support large images.

Is there a reliable way to gauge how much memory my app can use?

My current idea is that, when deciding on the image size to load, the device could calculate the image size that brings memory usage for the app as close to about 70% as possible (i.e. not 100% as you don't want the app crashing on small allocations later or because of memory fragmentation)

I've found I can use the following code to return a percentage of the available memory:

double totalMemoryUsed = (Runtime.getRuntime().totalMemory() + android.os.Debug.getNativeHeapAllocatedSize());
int percentUsed = (int)(totalMemoryUsed / Runtime.getRuntime().maxMemory() * 100);

New bitmaps add to the native heap allocated part. This seems reliable in that my app will predictably crash with an out of memory error when percentUsed goes above 100%. Are there any caveats to the above calculation I need to be aware of?


问:
Android Studio - Gradle incremental build
In the last few days I have been trying to improve the build time for our project with no luck. I don't mind having to wait 1m40s for a clean build, but if I insert one line in a single java file, I get the same build time as in a clean build. I must be doing something wrong but I simply can't find any documentation or stack overflow question that points me in the right direction. I managed to gather a bunch of information that I will centralize here in the hope that someone with a better understanding of the topic explain me why I get these abysmal build times.

Here it goes:

I understand that this option in my build.gradle file is what I seek.

```<code>android {
    dexOptions {
        incremental true
    }
...
</code>```

Glorious incremental build. However, this doesn't work for me apparently because my project uses the multidex feature for retrocompatibility with android versions before Lollipop.

Proguard to the rescue! With Proguard I am able to minify my executable and remove all the unused methods. I got a couple of errors with proguard minify but was able to set it properly and get it working. Great! Dex generation takes about 20s for every build. Unfortunately, nothing is for free, and the proguard gradle task takes about 2m50s to run. Even worse than my initial case.

Is there a solution to this problem?

答:
I tried this option today (13 Nov 2017) and got the following build warning:

Warning:The android.dexOptions.incremental property is deprecated and it has no effect on the build process.

I then googled for the warning message and the answer confirmed that since a newer Gradle release, the entry is deprecated. See android.dexOptions.incremental property is deprecated

ContentLicense: CC BY-SA 3.0

Body:
In the last few days I have been trying to improve the build time for our project with no luck. I don't mind having to wait 1m40s for a clean build, but if I insert one line in a single java file, I get the same build time as in a clean build. I must be doing something wrong but I simply can't find any documentation or stack overflow question that points me in the right direction. I managed to gather a bunch of information that I will centralize here in the hope that someone with a better understanding of the topic explain me why I get these abysmal build times.

Here it goes:

I understand that this option in my build.gradle file is what I seek.

android {
    dexOptions {
        incremental true
    }
...

Glorious incremental build. However, this doesn't work for me apparently because my project uses the multidex feature for retrocompatibility with android versions before Lollipop.

Proguard to the rescue! With Proguard I am able to minify my executable and remove all the unused methods. I got a couple of errors with proguard minify but was able to set it properly and get it working. Great! Dex generation takes about 20s for every build. Unfortunately, nothing is for free, and the proguard gradle task takes about 2m50s to run. Even worse than my initial case.

Is there a solution to this problem?


问:
how to count up variables in java
my problem is the following: I want to set all panes white, just like this:

```<code>    paneVfeld1.setStyle("-fx-background-color: white");
    paneVfeld2.setStyle("-fx-background-color: white");
    paneVfeld3.setStyle("-fx-background-color: white");
    paneVfeld4.setStyle("-fx-background-color: white");
    paneVfeld5.setStyle("-fx-background-color: white");
    paneVfeld6.setStyle("-fx-background-color: white");
    paneVfeld7.setStyle("-fx-background-color: white");
    paneVfeld8.setStyle("-fx-background-color: white");
    paneVfeld9.setStyle("-fx-background-color: white");
    paneVfeld10.setStyle("-fx-background-color: white");
</code>```

But i seriously can´t do this for all my 42 panes, how can i shorten that, with an Array?, anything else?, thx for the help :)

答:
You don't need manually put fields to array or list or especially use reflection(it's a bad practice almost in all cases) Simple find Parent where all your panes reside and apply action to all its children.

```<code>  Parent parent = //parent where all your panes resides;
  parent.getChildrenUnmodifiable()
              .forEach(pane -> pane.setStyle("-fxbackground-color: white"));
</code>```

Title: how to count up variables in java

Body:
my problem is the following: I want to set all panes white, just like this:

    paneVfeld1.setStyle("-fx-background-color: white");
    paneVfeld2.setStyle("-fx-background-color: white");
    paneVfeld3.setStyle("-fx-background-color: white");
    paneVfeld4.setStyle("-fx-background-color: white");
    paneVfeld5.setStyle("-fx-background-color: white");
    paneVfeld6.setStyle("-fx-background-color: white");
    paneVfeld7.setStyle("-fx-background-color: white");
    paneVfeld8.setStyle("-fx-background-color: white");
    paneVfeld9.setStyle("-fx-background-color: white");
    paneVfeld10.setStyle("-fx-background-color: white");

But i seriously can´t do this for all my 42 panes, how can i shorten that, with an Array?, anything else?, thx for the help :)

Body:
You don't need manually put fields to array or list or especially use reflection(it's a bad practice almost in all cases) Simple find Parent where all your panes reside and apply action to all its children.

  Parent parent = //parent where all your panes resides;
  parent.getChildrenUnmodifiable()
              .forEach(pane -> pane.setStyle("-fxbackground-color: white"));


问:
cakephp-3.4 immutable http\request api API
In cakephp 3.3 I could use statement like this in controller:

```<code>$this->request->data = array_merge($this->request->query,$this->request->data);
</code>```

How can I achieve the same effect using new immutable http\request api API i n cake 3.4/3.5?

答:
So it's quite bad practice to overwrite (or even append to) the request, since this is what the client has sent - if you really still want to go that way, one could use reflection to set the value... Did I mention this is bad practice?

Like.. really bad practice :)

```<code>$reflectionClass = new ReflectionObject($this->request);
$reflectionProperty = $reflectionClass->getProperty('data');
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($this->request, -YourNewArray-);
</code>```

I guess I don't have to repeat that what already has been said, but if it saves you the problem of upgrading between versions.. this might fix it.

Body:
In cakephp 3.3 I could use statement like this in controller:

$this->request->data = array_merge($this->request->query,$this->request->data);

How can I achieve the same effect using new immutable http\request api API i n cake 3.4/3.5?

Body:
So it's quite bad practice to overwrite (or even append to) the request, since this is what the client has sent - if you really still want to go that way, one could use reflection to set the value... Did I mention this is bad practice?

Like.. really bad practice :)

$reflectionClass = new ReflectionObject($this->request);
$reflectionProperty = $reflectionClass->getProperty('data');
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($this->request, -YourNewArray-);

I guess I don't have to repeat that what already has been said, but if it saves you the problem of upgrading between versions.. this might fix it.


问:
Show app and device info in email message body - swift
How does this convert to swift? Minimum I need is the app name, app version and locale or country appended to the email message.

```<code>NSString *appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
UIDevice *currentDevice = [UIDevice currentDevice];
NSString *model = [currentDevice model];
NSString *systemVersion = [currentDevice systemVersion];
NSArray *languageArray = [NSLocale preferredLanguages];
NSString *language = [languageArray objectAtIndex:0];
NSLocale *locale = [NSLocale currentLocale];
NSString *country = [locale localeIdentifier];
NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
NSString *emailBody = [NSString stringWithFormat:@"\n\n\n\n\n\n\n\n\nApp Name: %@ \nModel: %@ \nSystem Version: %@ \nLanguage: %@ \nCountry: %@ \nApp Version: %@", appName, model, systemVersion, language, country, appVersion];
</code>```

So far I've found

```<code>let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as! String
</code>```

though have had no luck adding that to message body.

This is what I have so far.

```<code>@IBAction func sendMail(_ sender: AnyObject) {

    let recipients = ["support@enquinn.rocks"]
    let title = "App feedback"
    let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as! String

    let message = ""

    let mc: MFMailComposeViewController = MFMailComposeViewController()

    mc.mailComposeDelegate = self

    mc.setToRecipients(recipients)
    mc.setSubject(title)
    mc.setMessageBody(message, isHTML: false)

    self.present(mc, animated: true, completion: nil)
</code>```

答:
You're on the right path. If you're on Swift 4 you can use a multi-string literal and format your message like so:

```<code>let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as! String
let appVersion = "5"

let message = """
App name: \(appName)
Version: \(appVersion)
"""
</code>```

Swift 3 version:

```<code>let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as! String
let appVersion = "5"

var message = "App name: \(appName)\n"
message += "Version: \(appVersion)"
</code>```

I just hardcoded your appVersion in the example above since you asked specifically how to insert your variables into your message. Hope that helps.

Body:
How does this convert to swift? Minimum I need is the app name, app version and locale or country appended to the email message.

NSString *appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
UIDevice *currentDevice = [UIDevice currentDevice];
NSString *model = [currentDevice model];
NSString *systemVersion = [currentDevice systemVersion];
NSArray *languageArray = [NSLocale preferredLanguages];
NSString *language = [languageArray objectAtIndex:0];
NSLocale *locale = [NSLocale currentLocale];
NSString *country = [locale localeIdentifier];
NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
NSString *emailBody = [NSString stringWithFormat:@"\n\n\n\n\n\n\n\n\nApp Name: %@ \nModel: %@ \nSystem Version: %@ \nLanguage: %@ \nCountry: %@ \nApp Version: %@", appName, model, systemVersion, language, country, appVersion];

So far I've found

let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as! String

though have had no luck adding that to message body.

This is what I have so far.

@IBAction func sendMail(_ sender: AnyObject) {

    let recipients = ["support@enquinn.rocks"]
    let title = "App feedback"
    let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as! String

    let message = ""

    let mc: MFMailComposeViewController = MFMailComposeViewController()

    mc.mailComposeDelegate = self

    mc.setToRecipients(recipients)
    mc.setSubject(title)
    mc.setMessageBody(message, isHTML: false)

    self.present(mc, animated: true, completion: nil)

Body:
You're on the right path. If you're on Swift 4 you can use a multi-string literal and format your message like so:

let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as! String
let appVersion = "5"

let message = """
App name: \(appName)
Version: \(appVersion)
"""

Swift 3 version:

let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as! String
let appVersion = "5"

var message = "App name: \(appName)\n"
message += "Version: \(appVersion)"

I just hardcoded your appVersion in the example above since you asked specifically how to insert your variables into your message. Hope that helps.


问:
Windows Phone 7 Frame Rate Performance
Reading Jeff Willcox on frame rate counters, I realized my application rarely hit the 60 fps. I'm not satisfied with the global performance of my app (compared to its iPhone counterpart), but the numbers seems weird to me.

When the app is doing nothing, even just after launch, it's even sometimes at 0 fps. And the higher I hit is 50 fps.

Overall, my application is not blazing fast, but not really slow. So how can I interpret the numbers ? How can I spot the issue that makes my app have a bad fps ?

答:
A low frame rate doesn't necessarily indicate poor performance.

If you're testing on an actual device and you see poor performance when then an investigation may indicate a problem that may be related to an issue which also impacts frame rate.

Hmmm. That sentence may not be clear.

Don't worry too much about getting a high frame rate all the time. Focus on actual performance experienced by the user.

If the actual performance is poor and the frame rate is low, that's when you should worry about the frame rate.

What's important is testing on an actual device and what performance is like there.

Title: Windows Phone 7 Frame Rate Performance


问:
numpy polynomial TypeError
I'm using python 3.6.3. I want to call polynomial with list of values but I got a TypeError.

```<code>Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from numpy.polynomial import Polynomial
>>> p = Polynomial([-3, 2, 0, 1])
>>> p(0)
-3.0
>>> p([1, 2, 3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Michel\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\polynomial\_polybase.py", line 292, in __call__
    arg = off + scl*arg
TypeError: 'numpy.float64' object cannot be interpreted as an integer
>>> p([1.0, 2.0, 3.0])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Michel\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\polynomial\_polybase.py", line 292, in __call__
    arg = off + scl*arg
TypeError: 'numpy.float64' object cannot be interpreted as an integer
>>>
</code>```

I cannot find any related subject on the Net.
Any idea of what missing ?

答:
You can construct Polynomial by passing list of values:

```<code>f = Polynomial([1, 2, 3])  # means 1 + 2 * x + 3 * x^2
</code>```

You can count value of polynomial by passing number as argument:

```<code>In [8]: f(1.5)
Out[8]: 10.75
</code>```

However you can't pass list as argument.
If you want to retrieve values for each element of list you should use this code or something similar:

```<code>In [9]: [f(i) for i in [1.0, 2.0, 3.0]]
Out[9]: [6.0, 17.0, 34.0]
</code>```

Title: numpy polynomial TypeError

Body:
I'm using python 3.6.3. I want to call polynomial with list of values but I got a TypeError.

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from numpy.polynomial import Polynomial
>>> p = Polynomial([-3, 2, 0, 1])
>>> p(0)
-3.0
>>> p([1, 2, 3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Michel\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\polynomial\_polybase.py", line 292, in __call__
    arg = off + scl*arg
TypeError: 'numpy.float64' object cannot be interpreted as an integer
>>> p([1.0, 2.0, 3.0])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Michel\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\polynomial\_polybase.py", line 292, in __call__
    arg = off + scl*arg
TypeError: 'numpy.float64' object cannot be interpreted as an integer
>>>

I cannot find any related subject on the Net.
Any idea of what missing ?

Body:
You can construct Polynomial by passing list of values:

f = Polynomial([1, 2, 3])  # means 1 + 2 * x + 3 * x^2

You can count value of polynomial by passing number as argument:

In [8]: f(1.5)
Out[8]: 10.75

However you can't pass list as argument.
If you want to retrieve values for each element of list you should use this code or something similar:

In [9]: [f(i) for i in [1.0, 2.0, 3.0]]
Out[9]: [6.0, 17.0, 34.0]


问:
sudo pip: why, why not and alternatives
Going around I read a lot about how sudo pip is a very bad habit/solution. Some reasons people gave were:

It could run malicious code.

It will break permission structs.

Sudo is used to install a package "system wide".

It is Satan!1!!one

An alternative I found is running pip with --user (e.g. pip install --user package). I saw that python in Debian works a little different (I have Stretch), mostly because of path used (--user is standard in Debian if omitted, btw). In conclusion, I found a lot of inconsistent things.

Taking for granted that using sudo and pip together are wrong, can someone explain me why, and most of all, when is it wrong? Major issues I encountered were all about permissions, so my guess is that sudo "just" ruin ownership.

Are there any other solutions besides using --user or virtualenv?

答:
Unless you want or have to install a binary, service or dependency globally, you would not want to use sudo pip.  As you surmise correctly, it installs your dependency globally, and this may cause inconsistencies while developing.

The more conventional thing to do nowadays is to use a virtualenv with which to install your dependencies.  This way, anything you do with installation is local to that specific virtualenv instance of Python.

Title: sudo pip: why, why not and alternatives


问:
Ignoring Duplicate Records SQL
In need of some help :)

So I have a table of records with the following columns:

```<code>Key (PK, FK, int) DT (smalldatetime) Value (real)
</code>```

The DT is a datetime for every half hour of the day with an associated value

E.g.

```<code>Key       DT                       VALUE
1000      2010-01-01 08:00:00      80
1000      2010-01-01 08:30:00      75
1000      2010-01-01 09:00:00      100
</code>```

I have a Query that finds the max value every 24 hour period and its associated time however, on one day the max value occurs twice and hence duplicates the date which is causing processing issues. I have tried using rownumber() which works but I can't use a calculated column in my where clause?
Currently I have:

```<code>SELECT       cast(T1.DT as date) as 'Date',Cast(T1.DT as time(0)) as 'HH', ROW_NUMBER() over (PARTITION BY  cast(DT as date) ORDER BY DT) AS 'RowNumber'
FROM        TABLE_1 AS T1
INNER JOIN  (
                SELECT CAST([DT] as date) as 'DATE'
                ,       MAX([VALUE]) as 'MAX_HH'
                FROM    TABLE_1
                WHERE   DT > '6-nov-2016' and [KEY] = '1000'
                GROUP BY CAST([DT] as date)
            ) AS MAX_DT
        ON  MAX_DT.[DATE] = CAST(T1.[DT] as date)
        AND T1.VALUE = MAX_DT.MAX_HH
WHERE       DT > '6-nov-2016' and [KEY] = '1000'
ORDER BY DT
</code>```

This results in

```<code>Key       DT               VALUE       HH
1000      2010-01-01       80          07:00:00
1000      2010-02-01       100         17:30:00
1000      2010-02-01       100         18:00:00
</code>```

I need to remove the duplicate date (I Have no preference which HH it takes)

I think I've explained that terribly, let me know if it makes no sense and i'll try and re write

Any ideas?

答:
i would do something like this
i didnt try it but i think it s correct.</p>

```<code>SELECT  cast(T1.DT as date) as 'Date',Cast(T1.DT as time(0)) as 'HH', VALUE
FROM TABLE_1 T1
       WHERE [DT] IN (
       --select the max date from Table_1 for each day
            SELECT MAX([DT]) max_date FROM TABLE_1
            WHERE (CAST([DT] as date) ,value) IN
            (
             SELECT CAST([DT] as date) as 'CAST_DATE'
              ,MAX([VALUE]) as 'MAX_HH'
              FROM    TABLE_1
              WHERE   DT > '6-nov-2016' and [KEY] = '1000'
             GROUP BY CAST([DT] as date
            )group by [DT]
           )
 WHERE       DT > '6-nov-2016' and [KEY] = '1000'
</code>```

Title: Ignoring Duplicate Records SQL

Body:
In need of some help :)

So I have a table of records with the following columns:

Key (PK, FK, int) DT (smalldatetime) Value (real)

The DT is a datetime for every half hour of the day with an associated value

E.g.

Key       DT                       VALUE
1000      2010-01-01 08:00:00      80
1000      2010-01-01 08:30:00      75
1000      2010-01-01 09:00:00      100

I have a Query that finds the max value every 24 hour period and its associated time however, on one day the max value occurs twice and hence duplicates the date which is causing processing issues. I have tried using rownumber() which works but I can't use a calculated column in my where clause?
Currently I have:

SELECT       cast(T1.DT as date) as 'Date',Cast(T1.DT as time(0)) as 'HH', ROW_NUMBER() over (PARTITION BY  cast(DT as date) ORDER BY DT) AS 'RowNumber'
FROM        TABLE_1 AS T1
INNER JOIN  (
                SELECT CAST([DT] as date) as 'DATE'
                ,       MAX([VALUE]) as 'MAX_HH'
                FROM    TABLE_1
                WHERE   DT > '6-nov-2016' and [KEY] = '1000'
                GROUP BY CAST([DT] as date)
            ) AS MAX_DT
        ON  MAX_DT.[DATE] = CAST(T1.[DT] as date)
        AND T1.VALUE = MAX_DT.MAX_HH
WHERE       DT > '6-nov-2016' and [KEY] = '1000'
ORDER BY DT

This results in

Key       DT               VALUE       HH
1000      2010-01-01       80          07:00:00
1000      2010-02-01       100         17:30:00
1000      2010-02-01       100         18:00:00

I need to remove the duplicate date (I Have no preference which HH it takes)

I think I've explained that terribly, let me know if it makes no sense and i'll try and re write

Any ideas?

Body:
i would do something like this
i didnt try it but i think it s correct.

SELECT  cast(T1.DT as date) as 'Date',Cast(T1.DT as time(0)) as 'HH', VALUE
FROM TABLE_1 T1
       WHERE [DT] IN (
       --select the max date from Table_1 for each day
            SELECT MAX([DT]) max_date FROM TABLE_1
            WHERE (CAST([DT] as date) ,value) IN
            (
             SELECT CAST([DT] as date) as 'CAST_DATE'
              ,MAX([VALUE]) as 'MAX_HH'
              FROM    TABLE_1
              WHERE   DT > '6-nov-2016' and [KEY] = '1000'
             GROUP BY CAST([DT] as date
            )group by [DT]
           )
 WHERE       DT > '6-nov-2016' and [KEY] = '1000'


问:
Show manytomany field in Django list view
I am trying to show the values of a manytomany field called teachers in a Django ListView.

At present my model looks like this:

```<code>class Classform(models.Model):

    # Fields
    name = models.CharField(max_length=255)
    slug = extension_fields.AutoSlugField(populate_from='name', blank=True)
    created = models.DateTimeField(auto_now_add=True, editable=False)
    last_updated = models.DateTimeField(auto_now=True, editable=False)

    # Relationship Fields
    school = models.ForeignKey('eduly.School', default=1)
    teachers = models.ManyToManyField('eduly.Teacher', )
</code>```

My ListView looks like this:

```<code>class ClassformListView(GroupRequiredMixin, ListView):
    model = Classform
    group_required = [u"school_admin"]
    login_url = "/login/"
    raise_exception = True
</code>```

And my template for the list view looks like this:

```<code><tr>
<td>{{object.pk}}</td>
<td><a href="{{object.get_absolute_url}}">{{object}}</a></td>
<td>{{ object.name }}</td>
<td>{{ object.teachers }}</td>
<td>{{ object.created }}</td>
<td>{{ object.last_updated }}</td>
</tr>
</code>```

When this code runs the displayed value for object.teachers is appname.Teacher.None

I have noticed that Django has created a table called appname_classform and also a table called 'appname_classform_teachers' (presumably for the manytomany field) but I am not sure how I need to change object.teachers to get the name of the teachers. The 'appname_classform_teachers' contains valid entries for teachers in the app name_teachers table.

答:
Use object.teachers.all instead to get the actual queryset.

-- EDIT --
To render these in a custom way:

```<code>{% for objs_teacher in object.teachers.all %}
    <p>{{ objs_teacher.first_name }}</p>
    <p>{{ objs_teacher.last_name }}</p>
    ...
{% endfor %}
</code>```

You can access the indevidual fields in the loop to make it look how you want.

Body:
I am trying to show the values of a manytomany field called teachers in a Django ListView.

At present my model looks like this:

class Classform(models.Model):

    # Fields
    name = models.CharField(max_length=255)
    slug = extension_fields.AutoSlugField(populate_from='name', blank=True)
    created = models.DateTimeField(auto_now_add=True, editable=False)
    last_updated = models.DateTimeField(auto_now=True, editable=False)

    # Relationship Fields
    school = models.ForeignKey('eduly.School', default=1)
    teachers = models.ManyToManyField('eduly.Teacher', )

My ListView looks like this:

class ClassformListView(GroupRequiredMixin, ListView):
    model = Classform
    group_required = [u"school_admin"]
    login_url = "/login/"
    raise_exception = True

And my template for the list view looks like this:

{{object.pk}}
{{object}}
{{ object.name }}
{{ object.teachers }}
{{ object.created }}
{{ object.last_updated }}

When this code runs the displayed value for object.teachers is appname.Teacher.None

I have noticed that Django has created a table called appname_classform and also a table called 'appname_classform_teachers' (presumably for the manytomany field) but I am not sure how I need to change object.teachers to get the name of the teachers. The 'appname_classform_teachers' contains valid entries for teachers in the app name_teachers table.

Body:
Use object.teachers.all instead to get the actual queryset.

-- EDIT --
To render these in a custom way:

{% for objs_teacher in object.teachers.all %}
    <p>{{ objs_teacher.first_name }}</p>
    <p>{{ objs_teacher.last_name }}</p>
    ...
{% endfor %}

You can access the indevidual fields in the loop to make it look how you want.


问:
Doctrine schema:update generates the same SQL again and again
Running bin/console doctrine:schema:update --force again and again, it always output 39 queries executed even after clearing cache/restarting php-fpm. So it always execute the same SQL requests again and again...

The SQL looks likes (from --dump-sql)

```<code>ALTER TABLE apply_queue CHANGE cv_id cv_id INT DEFAULT NULL, CHANGE team_id team_id INT DEFAULT NULL;
....
</code>```

And a lot of lines similar to this.

The ApplyQueue class look like:

```<code>/**
 * AppBundle\Entity\ApplyQueue.
 *
 * @ORM\Entity(repositoryClass="AppBundle\Entity\ApplyQueueRepository")
 * @ORM\Table(name="apply_queue")
 */
class ApplyQueue
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Cv")
     * @ORM\JoinColumn(name="cv_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $cv;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Team")
     * @ORM\JoinColumn(name="team_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $team;

    ...
</code>```

}

DBAL config :

```<code>doctrine:
    dbal:
        driver:   "%database_driver%"
        host:     "%database_host%"
        port:     "%database_port%"
        dbname:   "%database_name%"
        user:     "%database_user%"
        password: "%database_password%"
        charset: utf8mb4
        default_table_options:
            charset: utf8mb4
            collate: utf8mb4_unicode_ci
        types:
            json: Sonata\Doctrine\Types\JsonType
            review_status: AppBundle\Model\Enum\ReviewStatusEnumType
        mapping_types:
            review_status: string
</code>```

The structure of the table:

This is an "old" project that has been upgraded to Symfony 3.4 and MariaDB 10.2.

Thanks

答:
MariaDB 10.2 is not yet supported by Doctrine, causing this problem.

See linked PR : https://github.com/doctrine/dbal/pull/2825

Body:
Running bin/console doctrine:schema:update --force again and again, it always output 39 queries executed even after clearing cache/restarting php-fpm. So it always execute the same SQL requests again and again...

The SQL looks likes (from --dump-sql)

ALTER TABLE apply_queue CHANGE cv_id cv_id INT DEFAULT NULL, CHANGE team_id team_id INT DEFAULT NULL;
....

And a lot of lines similar to this.

The ApplyQueue class look like:

/**
 * AppBundle\Entity\ApplyQueue.
 *
 * @ORM\Entity(repositoryClass="AppBundle\Entity\ApplyQueueRepository")
 * @ORM\Table(name="apply_queue")
 */
class ApplyQueue
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Cv")
     * @ORM\JoinColumn(name="cv_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $cv;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Team")
     * @ORM\JoinColumn(name="team_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $team;

    ...

}

DBAL config :

doctrine:
    dbal:
        driver:   "%database_driver%"
        host:     "%database_host%"
        port:     "%database_port%"
        dbname:   "%database_name%"
        user:     "%database_user%"
        password: "%database_password%"
        charset: utf8mb4
        default_table_options:
            charset: utf8mb4
            collate: utf8mb4_unicode_ci
        types:
            json: Sonata\Doctrine\Types\JsonType
            review_status: AppBundle\Model\Enum\ReviewStatusEnumType
        mapping_types:
            review_status: string

The structure of the table:

This is an "old" project that has been upgraded to Symfony 3.4 and MariaDB 10.2.

Thanks


问:
Add css to button
how could add css style to this button.
Button html:

```<code><html>
    <body>
        <button onclick="myFunction()">Player</button>
        <script>
            function myFunction() {
                alert('what ever');
            }
        </script>
    </body>
</html>
</code>```

CSS i want to add

```<code><style>
.button {
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}
</style>
</code>```

If there is answered question, please send link. Thank you

答:
In your case, you're two solutions :

First :  use classe, if you've differents buttons in your pages :
you can just add class attribute in your HTML element like that :

```<code><html>
    <body>
        <button class="btn" onclick="myFunction()">Player</button>
        <script>
            function myFunction() {
                alert('what ever');
            }
        </script>
    </body>
</html>
</code>```

And define the style in your class in your CSS :

```<code><style>
.btn {
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}
</style>
</code>```

Second : If all buttons are the same style, you can just add style for all element button :

Not change your HTML :

```<code><html>
    <body>
        <button onclick="myFunction()">Player</button>
        <script>
            function myFunction() {
                alert('what ever');
            }
        </script>
    </body>
</html>
</code>```

But, in your CSS, just change the reference, for select elements button :

```<code><style>
button {
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}
</style>
</code>```

You can learn more explain about selector (.myClass, #myId, element) here in the mozilla developper website.

Don't forget, for optimize your web code, use as little code as possible, for reduce weight of pages, and to correctly use the different selectors (classes or id as not mandatory for CSS style : that depend to your utility) :)

Title: Add css to button

Body:
how could add css style to this button.
Button html:

        <button onclick="myFunction()">Player</button>

CSS i want to add

If there is answered question, please send link. Thank you

Body:
In your case, you're two solutions :

First :  use classe, if you've differents buttons in your pages :
you can just add class attribute in your HTML element like that :

<html>
    <body>
        <button class="btn" onclick="myFunction()">Player</button>
        <script>
            function myFunction() {
                alert('what ever');
            }
        </script>
    </body>
</html>

And define the style in your class in your CSS :

<style>
.btn {
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}
</style>

Second : If all buttons are the same style, you can just add style for all element button :

Not change your HTML :

<html>
    <body>
        <button onclick="myFunction()">Player</button>
        <script>
            function myFunction() {
                alert('what ever');
            }
        </script>
    </body>
</html>

But, in your CSS, just change the reference, for select elements button :

<style>
button {
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}
</style>

You can learn more explain about selector (.myClass, #myId, element) here in the mozilla developper website.

Don't forget, for optimize your web code, use as little code as possible, for reduce weight of pages, and to correctly use the different selectors (classes or id as not mandatory for CSS style : that depend to your utility) :)


问:
Call the method of a component inside another component
I am new in react native. I have two components(screen A and screen B) as below. I need to call the  _showModalHistory method of screen B inside screen A.
Here is the code of screen A (Component A):

```<code> import B from './B.js';

    class A extends Component {
      render() {
            return (
                this.refs.B._showModalHistory();
                  );
              }
        }
</code>```

In screen B (Component B) also I have the following code:

```<code>      export default class B extends Component {

          constructor(props) {
                super();
                this.subscription = 0;
                this.state = {
                };
                changePage = props.cb;

                this.state = {
                  isModalVisible: false,
                  isModalVisibleHistory: false,
                };
            }

          _showModalHistory = () => this.setState({ isModalVisibleHistory: true });

          render() {
                return (
            <Modal isVisible={this.state.isModalVisibleHistory}>
            <View style={styles.contianer}>
            <History></History>
            </View>
            </Modal>
    );}
    }
</code>```

I tried to use ref in screen A, in order to reach the method of screen B but, it shows me a  the error of "

Cannot read properity '_showModalHistory' of undefine".

Could you please check what is wrong with my code? should I add anything to perform the ref?

答:
You need to first render your B component inside A. Then set the ref as shown below.

```<code> class A extends Component {

      // Some on click listener.

      onClick() {
         this.B._showModalHistory();
      }

      render() {
            return (
                <B ref={component => { this.B = component; }} />
            );
      }
 }
</code>```

Body:
I am new in react native. I have two components(screen A and screen B) as below. I need to call the  _showModalHistory method of screen B inside screen A.
Here is the code of screen A (Component A):

 import B from './B.js';

    class A extends Component {
      render() {
            return (
                this.refs.B._showModalHistory();
                  );
              }
        }

In screen B (Component B) also I have the following code:

      export default class B extends Component {

          constructor(props) {
                super();
                this.subscription = 0;
                this.state = {
                };
                changePage = props.cb;

                this.state = {
                  isModalVisible: false,
                  isModalVisibleHistory: false,
                };
            }

          _showModalHistory = () => this.setState({ isModalVisibleHistory: true });

          render() {
                return (
            <Modal isVisible={this.state.isModalVisibleHistory}>
            <View style={styles.contianer}>
            <History></History>
            </View>
            </Modal>
    );}
    }

I tried to use ref in screen A, in order to reach the method of screen B but, it shows me a  the error of "

Cannot read properity '_showModalHistory' of undefine".

Could you please check what is wrong with my code? should I add anything to perform the ref?

Body:
You need to first render your B component inside A. Then set the ref as shown below.

 class A extends Component {

      // Some on click listener.

      onClick() {
         this.B._showModalHistory();
      }

      render() {
            return (
                <B ref={component => { this.B = component; }} />
            );
      }
 }


问:
showing maximum number per columns with php myadmin
Can someone help me to finish the program that I make? I stopped almost a week because I didn't find the answer.

This is the problem:

I have a table with columns named vr, vs and vt. I want to display the maximum value of the vr, vt and vs columns, so not the vr, vs or vt columns only. but compares the maximum value of columns vr, vt, and vs.

Maybe anyone here can help me, I will be very grateful for helping me.

答:
Use Greatest function for chossing from the columns</p>

```<code>SELECT GREATEST(vr,vs,vt) FROM yourtable;
</code>```

Body:
Use Greatest function for chossing from the columns

SELECT GREATEST(vr,vs,vt) FROM yourtable;


问:
Ogm Filter for ver 3.0.1 isn't compatible with filter from earlier version (2.3.1)
We widely use Filters in our base libraries. After upgrading neo4j (from 3.2.0 to 3.3.0) and ogm accordingly (from 2.1.3 to 3.0.1) I found out that constructor Filter(propertyName, propertyValue) doesn't exist anymore.

Now I got a compilation error in our old code:

Filter filter = new Filter(key, ob)--> The constructor Filter(String,
  Object) is undefined

Probably, I could try to change the constructors call, but I don't know which one of ComparisonOperator is default in the case. Can't find any doc describing the convention. Which one should I use when, for example, I try to "find by property" in database?

答:
Yes this constructor has been removed in OGM 3 to make the code mode explicit. In this case the replacement for

```<code>new Filter(propertyName, propertyValue)
</code>```

would be

```<code>new Filter(propertyName, ComparisonOperator.EQUALS, propertyValue);
</code>```

Maybe you can deal with it by using a regex like :

```<code>new Filter\(([^,]+)\s*,\s*([^\)^,]+)\)
</code>```

replaced by

```<code>new Filter\($1, ComparisonOperator.EQUALS, $2)
</code>```

Body:
Yes this constructor has been removed in OGM 3 to make the code mode explicit. In this case the replacement for

new Filter(propertyName, propertyValue)

would be

new Filter(propertyName, ComparisonOperator.EQUALS, propertyValue);

Maybe you can deal with it by using a regex like :

new Filter\(([^,]+)\s*,\s*([^\)^,]+)\)

replaced by

new Filter\($1, ComparisonOperator.EQUALS, $2)


问:
format swagger document text style solution
I have a swagger fragment like this

```<code>responses: { '200': { description: 'Agent data', schema: { type: object, properties: { agentRecord: { type: object, properties: { username: { type: string }, vpnname: { type: string }, google_id: { type: string } } }, googleRecord: { type: object }, agentACLs: { type: object } } } }, default: { description: 'Unexpected error', schema: { $ref: '#/definitions/Error' } } }
</code>```

but I want it to be like

```<code>    "responses": {
      "200": {
        "description": "Successful response",
        "schema": {
          "$ref": "#/definitions/Success"
        }
      },
</code>```

How to convert text style from (1) to (2)? I couldn't find any solution in the internet.

UPDATE

I am not developing a program I just want to eliminate handy work and convert one text style to text with another style.

答: Paste your YAML into http://editor.swagger.io and then select the menu item Edit > Convert to YAML. This will pretty-print your YAML.

Body:
I have a swagger fragment like this

responses: { '200': { description: 'Agent data', schema: { type: object, properties: { agentRecord: { type: object, properties: { username: { type: string }, vpnname: { type: string }, google_id: { type: string } } }, googleRecord: { type: object }, agentACLs: { type: object } } } }, default: { description: 'Unexpected error', schema: { $ref: '#/definitions/Error' } } }

but I want it to be like

    "responses": {
      "200": {
        "description": "Successful response",
        "schema": {
          "$ref": "#/definitions/Success"
        }
      },

How to convert text style from (1) to (2)? I couldn't find any solution in the internet.

UPDATE

I am not developing a program I just want to eliminate handy work and convert one text style to text with another style.


问:
How to launch Chrome in Selenium correctly
I can not launch Chrome in Selenium.

```<code>driver=webdriver.Chrome()
</code>```

Traceback (most recent call last):

```<code>  File "<stdin>", line 1, in <module>

  File "/usr/anaconda/lib/python2.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 67, in __init__
    desired_capabilities=desired_capabilities)

  File "/usr/anaconda/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 87, in __init__
    self.start_session(desired_capabilities, browser_profile)

  File "/usr/anaconda/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 141, in start_session
    'desiredCapabilities': desired_capabilities,
  File "/usr/anaconda/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 201, in execute
    self.error_handler.check_response(response)

  File "/usr/anaconda/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 181, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: crashed
  (Driver info: chromedriver=2.33.506092 (733a02544d189eeb751fe0d7ddca79a0ee28cce4),platform=Linux 3.19.8-100.fc20.x86_64 x86_64)
</code>```

I use "chromedriver_linux64.zip 2017-10-03 21:09:52 3.90MB" from
url.

答:
If you're going to use an old version of Chrome - you will need to match the version of chromedriver to it.  In your case you are using Chrome 38, which was last officially supported by ChromeDriver 2.13, which you can find here

If your users are using newer versions of Chrome, I would recommend updating your distro and installed chrome to match them.

Body:
I can not launch Chrome in Selenium.

driver=webdriver.Chrome()

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

  File "/usr/anaconda/lib/python2.7/site-packages/selenium/webdriver/chrome/webdriver.py", line 67, in __init__
    desired_capabilities=desired_capabilities)

  File "/usr/anaconda/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 87, in __init__
    self.start_session(desired_capabilities, browser_profile)

  File "/usr/anaconda/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 141, in start_session
    'desiredCapabilities': desired_capabilities,
  File "/usr/anaconda/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 201, in execute
    self.error_handler.check_response(response)

  File "/usr/anaconda/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 181, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: crashed
  (Driver info: chromedriver=2.33.506092 (733a02544d189eeb751fe0d7ddca79a0ee28cce4),platform=Linux 3.19.8-100.fc20.x86_64 x86_64)

I use "chromedriver_linux64.zip 2017-10-03 21:09:52 3.90MB" from
url.


答:
To select the max from the three values you can use.

Using IF()

```<code>SELECT
nama,
jam,
IF ( (vr >= vs and vr >= vt), vr , IF ( (vs >= vr and vs >= vt ), vs, vt) ) as maxValue
FROM mytable
</code>```

Or GREATEST()

```<code>SELECT
nama,
jam,
GREATEST(vr,vs,vt) as maxValue
FROM mytable
</code>```

Title: showing maximum number per columns with php myadmin

Body:
Can someone help me to finish the program that I make? I stopped almost a week because I didn't find the answer.

This is the problem:

I have a table with columns named vr, vs and vt. I want to display the maximum value of the vr, vt and vs columns, so not the vr, vs or vt columns only. but compares the maximum value of columns vr, vt, and vs.

Maybe anyone here can help me, I will be very grateful for helping me.

Body:
To select the max from the three values you can use.

Using IF()

SELECT
nama,
jam,
IF ( (vr >= vs and vr >= vt), vr , IF ( (vs >= vr and vs >= vt ), vs, vt) ) as maxValue
FROM mytable

Or GREATEST()

SELECT
nama,
jam,
GREATEST(vr,vs,vt) as maxValue
FROM mytable


问:
Spring security oauth/token returns 401
I am trying to create a simple app with Spring and Spring Security.
When I hit the default localhost:8080/oauth/token endpoint with username and password in the body I expect to get a token or an error if a given user does not exist.
I get 401 though. Why is that?
Here are some of my config files:

```<code>@EnableResourceServer
@Configuration
public static class ResourceServer extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(PUBLIC_URIS).permitAll();
    }

}

@EnableAuthorizationServer
@Configuration
public static class AuthorizationServer extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManagerBean;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient(CLIENT_ID)
                .authorizedGrantTypes(GRANT_TYPE)
                .scopes(SCOPE);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManagerBean);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients();
    }
</code>```

Security class:

```<code>@Configuration
@EnableWebSecurity
public class Security extends WebSecurityConfigurerAdapter {

@Autowired
private UserService usersService;
private PasswordEncoder passwordEncoder = new StandardPasswordEncoder();

@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
    return new SecurityEvaluationContextExtension();
}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(usersService).passwordEncoder(passwordEncoder);
}
</code>```

}

And web.xml:

```<code><web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     version="3.1">

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
    <filter-name>CORS</filter-name>
    <filter-class>pl.kabat.security.configuration.SimpleCORSFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>CORS</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
</code>```

答:
From the HTTP specs:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401

"The HTTP 401 Unauthorized client error status response code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource."

In other words, what you're getting is exactly an authentication error.

Title: Spring security oauth/token returns 401

Body:
I am trying to create a simple app with Spring and Spring Security.
When I hit the default localhost:8080/oauth/token endpoint with username and password in the body I expect to get a token or an error if a given user does not exist.
I get 401 though. Why is that?
Here are some of my config files:

@EnableResourceServer
@Configuration
public static class ResourceServer extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(PUBLIC_URIS).permitAll();
    }

}

@EnableAuthorizationServer
@Configuration
public static class AuthorizationServer extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManagerBean;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient(CLIENT_ID)
                .authorizedGrantTypes(GRANT_TYPE)
                .scopes(SCOPE);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManagerBean);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients();
    }

Security class:

@Configuration
@EnableWebSecurity
public class Security extends WebSecurityConfigurerAdapter {

@Autowired
private UserService usersService;
private PasswordEncoder passwordEncoder = new StandardPasswordEncoder();

@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
    return new SecurityEvaluationContextExtension();
}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(usersService).passwordEncoder(passwordEncoder);
}

}

And web.xml:

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     version="3.1">

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
    <filter-name>CORS</filter-name>
    <filter-class>pl.kabat.security.configuration.SimpleCORSFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>CORS</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>


问:
Node.js website with SSL, getting "Refused to connect" error
I've successfully created the SSL certificate and the key for my website via OpenSSL. I uploaded them in a folder on the server. I get no errors when I start the server.

But when I try to load the website in the browser using https://, I get the "refused to connect" error.

Here is the code I am using to create the https server:

```<code>var app = require('../app');
    var debug = require('debug')('gameserver:server');
    const https = require('https');
    const fs = require('fs');

    const options = {
        port: normalizePort(process.env.PORT || '80'),
        key: fs.readFileSync('../keys/key.key'),
        cert: fs.readFileSync('../keys/cert.crt')
    };

    var server = https.createServer(options);
    require('../config/socket')(server);

    server.listen(port);
    server.on('error', onError);
    server.on('listening', onListening);

    function normalizePort(val) {
        var port = parseInt(val, 10);

        if (isNaN(port)) {
            return val;
        }

        if (port >= 0) {
            return port;
        }

        return false;
    }

    function onError(error) {
        if (error.syscall !== 'listen') {
            throw error;
        }

        var bind = typeof port === 'string'
            ? 'Pipe ' + port
            : 'Port ' + port;

        switch (error.code) {
            case 'EACCES':
                console.error(bind + ' requires elevated privileges');
                process.exit(1);
                break;
            case 'EADDRINUSE':
                console.error(bind + ' is already in use');
                process.exit(1);
                break;
            default:
                throw error;
        }
    }

    function onListening() {
        var addr = server.address();
        var bind = typeof addr === 'string'
            ? 'pipe ' + addr
            : 'port ' + addr.port;
        debug('Listening on ' + bind);
    }
</code>```

Any suggestions?

答:
Your keys/cert are valid ?

The following command should display the same results:

```<code>openssl rsa -noout -modulus -in mykey.key | openssl md5 ; openssl x509 -noout -modulus -in mykey.crt | openssl md5 ;
</code>```

Or maybe node manage only .pem key file, simply concat the .key and the .crt in the .pem then use the .pem instead of the .key:

```<code>cat server.crt server.key > server.pem
</code>```

Then verify the pem :

```<code>openssl verify -CAfile server.pem server.crt;
</code>```

Body:
I've successfully created the SSL certificate and the key for my website via OpenSSL. I uploaded them in a folder on the server. I get no errors when I start the server.

But when I try to load the website in the browser using https://, I get the "refused to connect" error.

Here is the code I am using to create the https server:

var app = require('../app');
    var debug = require('debug')('gameserver:server');
    const https = require('https');
    const fs = require('fs');

    const options = {
        port: normalizePort(process.env.PORT || '80'),
        key: fs.readFileSync('../keys/key.key'),
        cert: fs.readFileSync('../keys/cert.crt')
    };

    var server = https.createServer(options);
    require('../config/socket')(server);

    server.listen(port);
    server.on('error', onError);
    server.on('listening', onListening);

    function normalizePort(val) {
        var port = parseInt(val, 10);

        if (isNaN(port)) {
            return val;
        }

        if (port >= 0) {
            return port;
        }

        return false;
    }

    function onError(error) {
        if (error.syscall !== 'listen') {
            throw error;
        }

        var bind = typeof port === 'string'
            ? 'Pipe ' + port
            : 'Port ' + port;

        switch (error.code) {
            case 'EACCES':
                console.error(bind + ' requires elevated privileges');
                process.exit(1);
                break;
            case 'EADDRINUSE':
                console.error(bind + ' is already in use');
                process.exit(1);
                break;
            default:
                throw error;
        }
    }

    function onListening() {
        var addr = server.address();
        var bind = typeof addr === 'string'
            ? 'pipe ' + addr
            : 'port ' + addr.port;
        debug('Listening on ' + bind);
    }

Any suggestions?

Body:
Your keys/cert are valid ?

The following command should display the same results:

openssl rsa -noout -modulus -in mykey.key | openssl md5 ; openssl x509 -noout -modulus -in mykey.crt | openssl md5 ;

Or maybe node manage only .pem key file, simply concat the .key and the .crt in the .pem then use the .pem instead of the .key:

cat server.crt server.key > server.pem

Then verify the pem :

openssl verify -CAfile server.pem server.crt;


问:
I try to use trigger for auto change field values when this field values = 0 and get MySQL Error
```<code>+------------+------------------+
| AMPHUR_NAME| AMPHUR_NAME_ENG  |
+------------+------------------+
| 1235855    | test12345        |
| 0          | zero             |  << I Want it.
+------------+------------------+
</code>```

I Want update when AMPHUR_NAME = 0 and auto change AMPHUR_NAME_ENG = zero.
I try to use trigger in phpmyadmin.

I get this error:

```<code>#1442 - Can't update table 'amphur' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
</code>```

From the code:

```<code>CREATE TRIGGER `test` AFTER UPDATE ON `amphur`
FOR EACH ROW
IF new.AMPHUR_NAME = 0
THEN
           UPDATE amphur SET amphur.AMPHUR_NAME_ENG = 'zero';
END IF
</code>```

答:
You can't update the same table when the table is used in a trigger.

You need to update the NEW.AMPHUR_NAME_ENG.

So your trigger code should be something like this.

Query

```<code>CREATE TRIGGER `test` AFTER UPDATE ON `amphur`
FOR EACH ROW
IF NEW.AMPHUR_NAME = 0
THEN
   SET NEW.AMPHUR_NAME_ENG = 'zero';
END IF
</code>```

Body:
+------------+------------------+
| AMPHUR_NAME| AMPHUR_NAME_ENG  |
+------------+------------------+
| 1235855    | test12345        |
| 0          | zero             |  << I Want it.
+------------+------------------+

I Want update when AMPHUR_NAME = 0 and auto change AMPHUR_NAME_ENG = zero.
I try to use trigger in phpmyadmin.

I get this error:

#1442 - Can't update table 'amphur' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

From the code:

CREATE TRIGGER `test` AFTER UPDATE ON `amphur`
FOR EACH ROW
IF new.AMPHUR_NAME = 0
THEN
           UPDATE amphur SET amphur.AMPHUR_NAME_ENG = 'zero';
END IF

Body:
You can't update the same table when the table is used in a trigger.

You need to update the NEW.AMPHUR_NAME_ENG.

So your trigger code should be something like this.

Query

CREATE TRIGGER `test` AFTER UPDATE ON `amphur`
FOR EACH ROW
IF NEW.AMPHUR_NAME = 0
THEN
   SET NEW.AMPHUR_NAME_ENG = 'zero';
END IF


问:
Rectifying two errors in School Library Management program in C++
I was looking for a Library Management System  program on which to make a school project. I found a good one on internet. The code can be seen here: https://codereview.stackexchange.com/q/68713/153350   on code review stack exchange. I'm planning to making my project on it.

So, I ran the above code but it shows 3 errors. One's regarding multiple declaration of a variable, which I was able to rectify.

But I don't understand what to do about the other two errors.
 They both occur in the following line of code in the body of the function, void write_student():

```<code> f.write((char*)&st, sizeof(student));
</code>```

The first error says:

```<code>Undefined symbol 'st'
</code>```

and the other says:

```<code>Could not find a match for 'ostream::write(undefined, unsigned int)'
</code>```

Can someone provide help on what's wrong and how I can fix those errors?
Thank you.

答:
You have these declarations...

```<code>//***************************************************************
// Global declaration for stream object, object
//****************************************************************
fstream f, f1;
book b;
student s;
</code>```

...and this function involved:

```<code>void write_student(){
    char ch;
    f.open("student.dat", ios::out|ios::app);
    do{
        s.create_student();
        f.write((char*)&st, sizeof(student));
        cout<<"\n\nDo you want to add more students...(y/n?)";
        cin>>ch;
    }while(ch=='y'||ch=='Y');
    f.close();
}
</code>```

You pass &st instead of &s to f.write.
Substitute the line in subject with

```<code>f.write((char*)&s, sizeof(student));
</code>```

in order to make it work.

Body:
I was looking for a Library Management System  program on which to make a school project. I found a good one on internet. The code can be seen here: https://codereview.stackexchange.com/q/68713/153350   on code review stack exchange. I'm planning to making my project on it.

So, I ran the above code but it shows 3 errors. One's regarding multiple declaration of a variable, which I was able to rectify.

But I don't understand what to do about the other two errors.
 They both occur in the following line of code in the body of the function, void write_student():

 f.write((char*)&st, sizeof(student));

The first error says:

Undefined symbol 'st'

and the other says:

Could not find a match for 'ostream::write(undefined, unsigned int)'

Can someone provide help on what's wrong and how I can fix those errors?
Thank you.

Body:
You have these declarations...

//***************************************************************
// Global declaration for stream object, object
//****************************************************************
fstream f, f1;
book b;
student s;

...and this function involved:

void write_student(){
    char ch;
    f.open("student.dat", ios::out|ios::app);
    do{
        s.create_student();
        f.write((char*)&st, sizeof(student));
        cout<<"\n\nDo you want to add more students...(y/n?)";
        cin>>ch;
    }while(ch=='y'||ch=='Y');
    f.close();
}

You pass &st instead of &s to f.write.
Substitute the line in subject with

f.write((char*)&s, sizeof(student));

in order to make it work.


问:
Deprecated constructor for BigDecimal.setScale(int, int) and RoundingMode enums
I'm trying to specify the precision of a BigDecimal value with the following: new BigDecimal(12.99).setScale(2, BigDecimal.ROUND_HALF_EVEN. However, the compiler is telling me that setScale(int, int) is deprecated.

When I've tried to use the RoundingMode enums, it's telling me that the enum may not have been initialised. How do I correctly use the enums to instantiate the BigDecimals with setScale(int, RoundingMode)?

Thanks!

答:
You should not "instantiate" an enum but use its constants. Have you tried:

```<code>new BigDecimal(12.99).setScale(2, RoundingMode.HALF_EVEN);
</code>```

Note that you could also use the string constructor:

```<code>new BigDecimal("12.99");
</code>```

Body:
You should not "instantiate" an enum but use its constants. Have you tried:

new BigDecimal(12.99).setScale(2, RoundingMode.HALF_EVEN);

Note that you could also use the string constructor:

new BigDecimal("12.99");


问:
Failure to login using Facebook Sdk: java.lang.RuntimeException: Failure delivering result
Inside MainActivity

```<code>public class MainActivity extends AppCompatActivity {
    private BottomNavigationView mBottomNavigationView;
    String[] fragmentTitles;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragmentTitles = getResources().getStringArray(R.array.bottom_nav);
        mBottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
        mBottomNavigationView.setOnChildClickedListener(new OnChildClickedListener() {
            @Override
            public void onChildClicked(int child) {
                selectFragment(child);
            }
        });
        //setSupportActionBar((Toolbar) findViewById(R.id.toolbar));

        if(savedInstanceState == null) {
            selectFragment(0);
            //getSupportActionBar().setTitle("Home");
        }
    }

    private void selectFragment(int child) {
        switch (child){
            case 0:
                getSupportFragmentManager()
                        .beginTransaction()
                        .setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
                        .replace(R.id.content, HomeFragment.newInstance(fragmentTitles[child], child))
                        .commit();
                break;
            case 1:
                getSupportFragmentManager()
                        .beginTransaction()
                        .setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
                        .replace(R.id.content, SearchFragment.newInstance(fragmentTitles[child], child))
                        .commit();
                break;
            case 2:
                getSupportFragmentManager()
                        .beginTransaction()
                        .setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
                        .replace(R.id.content, ProfileFragment.newInstance(fragmentTitles[child], child))
                        .commit();

        }

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //super.onActivityResult(requestCode, resultCode, data);
        for (Fragment fragment : getSupportFragmentManager().getFragments()) {
            fragment.onActivityResult(requestCode, resultCode, data);
        }
    }
}
</code>```

Inside Fragment.java

```<code>    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        final View view = inflater.inflate(R.layout.fragment_profile, container, false);
        FacebookSdk.sdkInitialize(mContext);
        loginButton=(LoginButton)view.findViewById(R.id.fb_login_bn);
        //textView=(TextView)findViewById(R.id.textView);
        callbackManager=CallbackManager.Factory.create();
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                final String token =  loginResult.getAccessToken().getToken().toString();
                Toast.makeText(mContext,token,Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel() {
                //textView.setText("Login Canceled");
            }

            @Override
            public void onError(FacebookException error) {

            }
        });
        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.startActivityForResult(data, resultCode);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }
</code>```

logcat

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: picker.novasyslabs.com.picker, PID: 23337
                  java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=64206, result=-1, data=Intent { (has extras) }} to activity {picker.novasyslabs.com.picker/picker.novasyslabs.com.picker.Activities.MainActivity}: java.lang.NullPointerException
                      at android.app.ActivityThread.deliverResults(ActivityThread.java:3391)
                      at android.app.ActivityThread.handleSendResult(ActivityThread.java:3434)
                      at android.app.ActivityThread.access$1300(ActivityThread.java:138)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:149)
                      at android.app.ActivityThread.main(ActivityThread.java:5045)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:515)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:610)
                      at dalvik.system.NativeStart.main(Native Method)
                   Caused by: java.lang.NullPointerException
                      at picker.novasyslabs.com.picker.Activities.MainActivity.onActivityResult(MainActivity.java:78)
                      at android.app.Activity.dispatchActivityResult(Activity.java:5423)
                      at android.app.ActivityThread.deliverResults(ActivityThread.java:3387)
                      at android.app.ActivityThread.handleSendResult(ActivityThread.java:3434)
                      at android.app.ActivityThread.access$1300(ActivityThread.java:138)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:149)
                      at android.app.ActivityThread.main(ActivityThread.java:5045)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:515)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:610)
                      at dalvik.system.NativeStart.main(Native Method)
I/Process: Sending signal. PID: 23337 SIG: 9
Application terminated.
</code>```

I have posted the logcat.
I want to log in with facebook inside ProfileFragment but when I'm trying to login inside Fragment then it asks for login and password and login is success from facebook then i can back to fragment at the moment Application Terminates and I'm not getting what to do to solve this problem.
Please help to solve this.
Thanks!

答:
Add following code in oncreateView

You need to call setFragment method on loginButton in oncreateview method.

```<code>loginButton=(LoginButton)view.findViewById(R.id.fb_login_bn);
loginButton.setFragment(this);
</code>```

Body:
Inside MainActivity

public class MainActivity extends AppCompatActivity {
    private BottomNavigationView mBottomNavigationView;
    String[] fragmentTitles;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragmentTitles = getResources().getStringArray(R.array.bottom_nav);
        mBottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
        mBottomNavigationView.setOnChildClickedListener(new OnChildClickedListener() {
            @Override
            public void onChildClicked(int child) {
                selectFragment(child);
            }
        });
        //setSupportActionBar((Toolbar) findViewById(R.id.toolbar));

        if(savedInstanceState == null) {
            selectFragment(0);
            //getSupportActionBar().setTitle("Home");
        }
    }

    private void selectFragment(int child) {
        switch (child){
            case 0:
                getSupportFragmentManager()
                        .beginTransaction()
                        .setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
                        .replace(R.id.content, HomeFragment.newInstance(fragmentTitles[child], child))
                        .commit();
                break;
            case 1:
                getSupportFragmentManager()
                        .beginTransaction()
                        .setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
                        .replace(R.id.content, SearchFragment.newInstance(fragmentTitles[child], child))
                        .commit();
                break;
            case 2:
                getSupportFragmentManager()
                        .beginTransaction()
                        .setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
                        .replace(R.id.content, ProfileFragment.newInstance(fragmentTitles[child], child))
                        .commit();

        }

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //super.onActivityResult(requestCode, resultCode, data);
        for (Fragment fragment : getSupportFragmentManager().getFragments()) {
            fragment.onActivityResult(requestCode, resultCode, data);
        }
    }
}

Inside Fragment.java

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        final View view = inflater.inflate(R.layout.fragment_profile, container, false);
        FacebookSdk.sdkInitialize(mContext);
        loginButton=(LoginButton)view.findViewById(R.id.fb_login_bn);
        //textView=(TextView)findViewById(R.id.textView);
        callbackManager=CallbackManager.Factory.create();
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                final String token =  loginResult.getAccessToken().getToken().toString();
                Toast.makeText(mContext,token,Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel() {
                //textView.setText("Login Canceled");
            }

            @Override
            public void onError(FacebookException error) {

            }
        });
        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.startActivityForResult(data, resultCode);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }

logcat

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: picker.novasyslabs.com.picker, PID: 23337
                  java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=64206, result=-1, data=Intent { (has extras) }} to activity {picker.novasyslabs.com.picker/picker.novasyslabs.com.picker.Activities.MainActivity}: java.lang.NullPointerException
                      at android.app.ActivityThread.deliverResults(ActivityThread.java:3391)
                      at android.app.ActivityThread.handleSendResult(ActivityThread.java:3434)
                      at android.app.ActivityThread.access$1300(ActivityThread.java:138)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:149)
                      at android.app.ActivityThread.main(ActivityThread.java:5045)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:515)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:610)
                      at dalvik.system.NativeStart.main(Native Method)
                   Caused by: java.lang.NullPointerException
                      at picker.novasyslabs.com.picker.Activities.MainActivity.onActivityResult(MainActivity.java:78)
                      at android.app.Activity.dispatchActivityResult(Activity.java:5423)
                      at android.app.ActivityThread.deliverResults(ActivityThread.java:3387)
                      at android.app.ActivityThread.handleSendResult(ActivityThread.java:3434)
                      at android.app.ActivityThread.access$1300(ActivityThread.java:138)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:149)
                      at android.app.ActivityThread.main(ActivityThread.java:5045)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:515)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:610)
                      at dalvik.system.NativeStart.main(Native Method)
I/Process: Sending signal. PID: 23337 SIG: 9
Application terminated.

I have posted the logcat.
I want to log in with facebook inside ProfileFragment but when I'm trying to login inside Fragment then it asks for login and password and login is success from facebook then i can back to fragment at the moment Application Terminates and I'm not getting what to do to solve this problem.
Please help to solve this.
Thanks!

Body:
Add following code in oncreateView

You need to call setFragment method on loginButton in oncreateview method.

loginButton=(LoginButton)view.findViewById(R.id.fb_login_bn);
loginButton.setFragment(this);


问:
Can the vsphhere Hypervisor be encrytpted

I know that vmware's Vsphere VM's can be encrypted using a KMS server but can the actual drive which vsphere is hosted on be encrypted? In Microsoft the hyper-visor host can be encrypted if bit-locker is enabled.

答:
Based on Kyle Rudy's vmware link the following is good to note:
https://blogs.vmware.com/vsphere/2017/05/secure-boot-esxi-6-5-hypervisor-assurance.html

TPM and TXT

The question always comes up in customer conversations of “Does this require TPM or TXT??”. The answer is no. They are mutually exclusive. Secure Boot for ESXi is purely a function of the UEFI firmware and the validation of cryptographically signed code. Period.

Note that TPM 1.2 and TPM 2.0 are two vastly different implementations. They are not backwards compatible. There is support, via 3rd parties like HyTrust, for TPM 1.2 in ESXi 6.5.

TPM 2.0 is not supported in 6.5.
Standard BIOS firmware vs UEFI firmware

Typically, switching your hosts from their standard (legacy) BIOS firmware to UEFI firmware in some operating systems will cause issues. With ESXi, you can switch with no modification to ESXi. If you have installed 6.5 using standard BIOS and you want to try out Secure Boot then in the host firmware you can switch and ESXi will come up.