问:
Unable to import the database via PLESK
I'm trying to import my database via PLESK and still have the same errors:

enter image description here

ERROR 2006 (HY000) at line 1898: MySQL server has gone away

Traceback (most recent call last):

File "/usr/local/psa/admin/sbin/dbbackup", line 6, in

File "/usr/local/psa/lib/modules/python/dbbackup/dbbackup.py", line
100, in main restore(options, password)

File "/usr/local/psa/lib/modules/python/dbbackup/dbbackup.py", line
89, in restore

raise Exception("program 'mysql' finished with non-zero exit code:
%d" % p.returncode)

Exception: program 'mysql' finished with non-zero exit code: 1

I tried to enlarge memory_limit and upload_max_filesize in PLESK PHP Settings but it still doesn't work. I've also checked version of my MySQL (5.5.2) because I found it might be not supported by the latest version of Plesk, but it seems to be OK.

I am beginner in such subjects and I really don't know what to do. Please, rescue me :(

答:
Hi Todra,

if you desire to increase the "wait-timeout", you have to define for example in your "my.cnf":

AFTER => [mysqld]

interactive_timeout=60
 wait_timeout=60

In addition, you might consider to set as well:

```<code>mysql -uadmin -p`cat /etc/psa/.psa.shadow` -e"SET GLOBAL wait_timeout=60; SET GLOBAL interactive_timeout=60"
</code>```

Title: Unable to import the database via PLESK

Body:
Hi Todra,

if you desire to increase the "wait-timeout", you have to define for example in your "my.cnf":

AFTER => [mysqld]

interactive_timeout=60
 wait_timeout=60

In addition, you might consider to set as well:

mysql -uadmin -p`cat /etc/psa/.psa.shadow` -e"SET GLOBAL wait_timeout=60; SET GLOBAL interactive_timeout=60"


来源: stackexchange

问:
jquery dialog text disappear only for 2nd time opening
I have following jquery code to pop up a dialog. It works fine for the first time. However, when the dialog closed, and I opened it again, the dialog text area is empty (no text displayed) with only three buttons. Now, if I reopen it again (3rd time, 4th time ...), everything works fine again (text was shown). As you can tell from the name, the function buttonClicked() to pop up the dialog is triggered by clicking a button. So anyone has any clue?</p>

```<code><link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

        function buttonClicked() {
           var dialog = $( "#dialog" ).dialog({
                modal: true,
                autoOpen: false,
                buttons: {
                    "Cancel":  function() {
                        $(this).closest('.ui-dialog-content').dialog('close');
                    },
                    "Button2": function() {
                        // do something
                        $(this).closest('.ui-dialog-content').dialog('close');
                    },
                    "Button1":  function() {
                        ... // do something
                        $(this).closest('.ui-dialog-content').dialog('close');
                    }
                }
            });

            dialog .dialog( "open" );
        }

          <div id = "dialog" name="dialog" style="display:none; ">
          <style>
            .ui-dialog-titlebar-close .ui-icon-closethick {
              position: relative !important;
              margin-top: -9px  !important;
              margin-left: -16px  !important;
            }
          </style>
          <p>I am the text shown in the dialog!!</p></div>
</code>```

答:
```<code>$( function() {
       $("#dialog").dialog({
            modal: true,
            autoOpen: false,
            buttons: {
                "Cancel":  function() {
                    $(this).closest('.ui-dialog-content').dialog('close');
                },
                "Button2": function() {
                    // do something
                    $(this).closest('.ui-dialog-content').dialog('close');
                },
                "Button1":  function() {
                    ... // do something
                    $(this).closest('.ui-dialog-content').dialog('close');
                }
            }
        });
      $('#yourBtn').click(function(){
          $("#dialog").dialog('open');
      })

    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have following jquery code to pop up a dialog. It works fine for the first time. However, when the dialog closed, and I opened it again, the dialog text area is empty (no text displayed) with only three buttons. Now, if I reopen it again (3rd time, 4th time ...), everything works fine again (text was shown). As you can tell from the name, the function buttonClicked() to pop up the dialog is triggered by clicking a button. So anyone has any clue?

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">

        function buttonClicked() {
           var dialog = $( "#dialog" ).dialog({
                modal: true,
                autoOpen: false,
                buttons: {
                    "Cancel":  function() {
                        $(this).closest('.ui-dialog-content').dialog('close');
                    },
                    "Button2": function() {
                        // do something
                        $(this).closest('.ui-dialog-content').dialog('close');
                    },
                    "Button1":  function() {
                        ... // do something
                        $(this).closest('.ui-dialog-content').dialog('close');
                    }
                }
            });

            dialog .dialog( "open" );
        }

I am the text shown in the dialog!!


Title: how to group data of 4 years seasonly using pandas

Body:
i have a csv file containing 4 years of data, i need to group my data per season over the 4 years : here's a look of my data :

timestamp,heure,lat,lon,impact,type
2006-01-01 00:00:00,13:58:43,33.837,-9.205,10.3,1
2006-01-02 00:00:00,00:07:28,34.5293,-10.2384,17.7,1
2007-02-01 00:00:00,23:01:03,35.0617,-1.435,-17.1,2
2007-02-02 00:00:00,01:14:29,36.5685,0.9043,36.8,1
2008-01-01 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1
2008-01-02 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1
....
2011-12-31 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1

and here's my desired output :

winter     (the mean value of impacts)
summer     (the mean value of impacts)
autumn      ....
spring      .....

so i am expecting 4 rows summarizing all month in 4 seasons .
i started as below :

data['impact'] = data['impact'].abs()
yearly = data.groupby(data.index.month)['impact'].mean()

any ideas ??

Body:
With crude months... Assumes the timestamps are in the index.

mlist = [[12, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
slist = ['winter', 'spring', 'summer', 'autum']
sdict = {k: v for v, ks in zip(slist, mlist) for k in ks}

df.groupby(df.index.month.map(sdict.get)).impact.mean()

Setup

import pandas as pd
from io import StringIO

txt = """timestamp,heure,lat,lon,impact,type
2006-01-01 00:00:00,13:58:43,33.837,-9.205,10.3,1
2006-01-02 00:00:00,00:07:28,34.5293,-10.2384,17.7,1
2007-02-01 00:00:00,23:01:03,35.0617,-1.435,-17.1,2
2007-02-02 00:00:00,01:14:29,36.5685,0.9043,36.8,1
2008-01-01 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1
2008-01-02 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1
2011-12-31 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1
"""

df = pd.read_csv(StringIO(txt), parse_dates=[0], index_col=0)


问:
How to choose between a Software Service and a Software Agent?
We have a system with a service that has a frontend so that users can manually use the service.  Users read information from a UI for the service and initiate actions through the UI by the service.  Nothing unusual here.

However, we would like to continue to allow the manual use of this service by users but we would also like to automate the user, e.g. have a software agent we write  access the same info and initiate the same type of actions.

Of course, the software agent wouldn't need to use the UI, it could query the view API and send commands to the write API. We can do this as we have a nice separation between our front-end UI and backend service.

My question is should we be automating a user by creating an agent like this OR should we be reimplementing the user as another service that interacts with the original service (e.g. an event-driven service)?

Either way the agent or service will be encapsulated within our system. The question is whether this component should use the service as the user would (but not through the UI) or implement equivalent functionality as a service

Thanks in advance for any thoughts, suggestions or pointers.

Cheers,
Ashley.

PS I am using the term "software agent" here because the component is somewhat replicating how a user would work, i.e. responding to information and executing actions.  I don't mean this agent is an AI or mobile etc.

答: If automating the user is a feature of your application it makes sense to model it as a service to encapsulate that behavior. If the automation is for development/testing only, you might want to just script it.</p>


问:
response.write is not working asp.net
On button click event after inserting data I want to show message that data is inserted successfully.
Here is my code

```<code>if (com2.ExecuteNonQuery() >= 1)
        {
            Response.Write("<script LANGUAGE='JavaScript' >alert('Request Submitted Successfully!')</script>");
        }
        else
        {
            Response.Write("<script LANGUAGE='JavaScript' >alert('There is some error. Please enter again')</script>");
        }
</code>```

It was working fine until I put code for empty textboxs after insertion in same event soon after above code. here is code

```<code>foreach (var control in this.Controls)
        {
            TextBox tb = control as TextBox;
            if (tb != null)
            {
                tb.Text = string.Empty;
            }
        }
        Response.Redirect("Default.aspx");
</code>```

now textbox empty after data insertion, data is also inserting but no popup message is showing. Where is problem

答:
Your Response.Redirect("Default.aspx") is run at the server level so you'll never give the client side a chance to render the javascript and therefore you won't ever see what your Response.Write is outputting.

Why don't you have an <asp:Label> control that will show the message you're looking for.

So, instead of a javascript message you could do:

```<code>tb.Text = String.Empty; //clear the textbox
label.Text = "Success Message.";  //show the message
</code>```

It's been awhile since I've used WebForms but this should work if you have Viewstate enabled.  You might also want to look into UpdatePanels for this.

Title: response.write is not working asp.net

Body:
On button click event after inserting data I want to show message that data is inserted successfully.
Here is my code

if (com2.ExecuteNonQuery() >= 1)
        {
            Response.Write("");
        }
        else
        {
            Response.Write("");
        }

It was working fine until I put code for empty textboxs after insertion in same event soon after above code. here is code

foreach (var control in this.Controls)
        {
            TextBox tb = control as TextBox;
            if (tb != null)
            {
                tb.Text = string.Empty;
            }
        }
        Response.Redirect("Default.aspx");

now textbox empty after data insertion, data is also inserting but no popup message is showing. Where is problem

Body:
Your Response.Redirect("Default.aspx") is run at the server level so you'll never give the client side a chance to render the javascript and therefore you won't ever see what your Response.Write is outputting.

Why don't you have an <asp:Label> control that will show the message you're looking for.

So, instead of a javascript message you could do:

tb.Text = String.Empty; //clear the textbox
label.Text = "Success Message.";  //show the message

It's been awhile since I've used WebForms but this should work if you have Viewstate enabled.  You might also want to look into UpdatePanels for this.


问:
How to use the polygon tool in ITK SNAP for 3D/voxel?
I know the paintbrush tool can segment out voxel 3D volume but how do I do this with the polygon tool? I want all slices to have the save segmentations.</p>

答: You can accomplish that by drawing your polygon on the first slice, accepting it, scrolling to the last slice, "paste last polygon", and then using Tool menu, option Interpolate Labels. Default options should give you the desired result.</p>


问:
AWS RDS SQL Server unable to drop database
I tried to migrate a SQL Server database by Export Data-tier Application (.bacpac file) from an Amazon RDS instance to other, but import didn't succeed. So now I want to delete the database (which is empty), when I try to:

```<code>DROP DATABASE mydatabase;
</code>```

I get the error:

Cannot drop the database 'mydatabase', because it does not exist or
  you do not have permission

Some context:

I've tried using SQL Server Management Studio, and choosing close connections: same error.

I'm logged as master user.

I can create and drop other databases, but not this one.

I just have these effective permissions on this database: CONNECT, SHOWPLAN, VIEW DATABASE STATE, VIEW DEFINITION (don't know why or how is this possible).

Any help is greatly appreciated!

答:
I ran into this same issue. After trying to restore a database via SSMS using a .bacpac, it fails and leaves you with a database that you appear to not have permissions to drop.

A workaround, is to use the rdsadmin rename function to rename it to something else, which then seems to fix the permission issue and allows you to drop it.

```<code>EXEC rdsadmin.dbo.rds_modify_db_name N'<OldName>', N'<NewName>'
</code>```

Then just drop the DB. Hope that helps someone else in the same predicament.

Body:
I tried to migrate a SQL Server database by Export Data-tier Application (.bacpac file) from an Amazon RDS instance to other, but import didn't succeed. So now I want to delete the database (which is empty), when I try to:

DROP DATABASE mydatabase;

I get the error:

Cannot drop the database 'mydatabase', because it does not exist or
  you do not have permission

Some context:

I've tried using SQL Server Management Studio, and choosing close connections: same error.

I'm logged as master user.

I can create and drop other databases, but not this one.

I just have these effective permissions on this database: CONNECT, SHOWPLAN, VIEW DATABASE STATE, VIEW DEFINITION (don't know why or how is this possible).

Any help is greatly appreciated!

Body:
I ran into this same issue. After trying to restore a database via SSMS using a .bacpac, it fails and leaves you with a database that you appear to not have permissions to drop.

A workaround, is to use the rdsadmin rename function to rename it to something else, which then seems to fix the permission issue and allows you to drop it.

EXEC rdsadmin.dbo.rds_modify_db_name N'<OldName>', N'<NewName>'

Then just drop the DB. Hope that helps someone else in the same predicament.


问:
How to find a number that isn't there?
We have a custom number field on a training record, the number is recorded sequentially but there are gaps.  How do I find those gaps?  Consider this pseudocode

```<code>SELECT MIN(X)
FROM DUAL
WHERE X BETWEEN 1 AND 999999
  AND X NOT IN (SELECT AG_TRNID
                FROM PS_TRAINING
                WHERE AG_TRNID = X)
</code>```

This doesn't work, "X" is unknown.

Thanks!
Bruce

答:
In the end I created a table with all possible values and select the minimum from it that doesn't exist in the base table.  It works well.   I had hoped for a sql statement to avoid creating yet another object but couldn't.

Yes this is Oracle, I neglected to mention.

Thank you all for the suggestions and assistance, it is much appreciated!

Title: How to find a number that isn't there?

Body:
We have a custom number field on a training record, the number is recorded sequentially but there are gaps.  How do I find those gaps?  Consider this pseudocode

SELECT MIN(X)
FROM DUAL
WHERE X BETWEEN 1 AND 999999
  AND X NOT IN (SELECT AG_TRNID
                FROM PS_TRAINING
                WHERE AG_TRNID = X)

This doesn't work, "X" is unknown.

Thanks!
Bruce


问:
How to turn a string of letters into integer?
Specifically, I'm taking a word that a user inputs, which is equivalent to a number (that the user wouldn't know).

my code:

```<code>animal = raw_input( > )  #and a user inputs cat
dog = 30
cat = 10
frog = 5
print 10 + int(animal) #with the hope that will output 20
</code>```

Not sure how to do it..

答:
You can use dictionaries to do this:</p>

```<code>animal = raw_input( > ) #and a user inputs cat

d = {'dog' : 30, 'cat' : 10, 'frog' : 5}

print 10 + d[animal]
</code>```

Body:
Specifically, I'm taking a word that a user inputs, which is equivalent to a number (that the user wouldn't know).

my code:

animal = raw_input( > )  #and a user inputs cat
dog = 30
cat = 10
frog = 5
print 10 + int(animal) #with the hope that will output 20

Not sure how to do it..

Body:
You can use dictionaries to do this:

animal = raw_input( > ) #and a user inputs cat

d = {'dog' : 30, 'cat' : 10, 'frog' : 5}

print 10 + d[animal]


问:
Spring Resttemplate: Parsing using @JsonIgnore causes values to be null
So, I am using Spring Boot 1.5.3 and am trying to a part  of the following Json - - namely AccountId and Username- (actually, it is an oData v2 interface getting from a SAP Netweaver instance) into a class using restTemplate.exchange:

```<code>{
   "d":{
      "__metadata":{
         "id":"...",
         "uri":"...",
         "type":"...."
      },
      "AccountID":"0100000001",
      "Username":"test@test.com",
      "Partners":{
         "__deferred":{
            "uri":"Navigationproperty"
         }
      }
   }
}
</code>```

My class is set up like this, because for a start I only want to get the account id and name:

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
public class PortalAccount implements Serializable{

    public PortalAccount() {
    }

    @JsonProperty("AccountID")
    public String accountID;

    @JsonProperty("Username")
    public String username;

    public String getPortalAccountID() {
        return accountID;
    }

    public void setPortalAccountID(String portalAccountID) {
        this.accountID = portalAccountID;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String toString() {
        return "Account{" +
                "accountID='" + accountID + '\'' +
                ", username='" + username +'\'' +
                '}';
    }
}
</code>```

and here's the way I try to call it:

```<code>        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = this.createHeaders();
        ResponseEntity<String> response;
        response  = restTemplate.exchange(uri,HttpMethod.GET,new HttpEntity<Object>(httpHeaders),String.class);
        ObjectMapper mapper = new ObjectMapper();

        PortalAccount acc = mapper.readValue(response.getBody(), PortalAccount.class);
</code>```

I first tried to parse it directly like in the docs using ResponseEntity<PortalAccount>, but this just lead to an empty class (accountid = null, username = null), So i tried the way above using ResponseEntity<String> to see what I get when just parsing the response into the string representation. That way, I could make sure the json above is correctly returned, which it is.So, the values are definitely there, it has to be a matter of parsing, but I sadly don't get my way around this problem.

I hope you could help me out here!

edit: As one answer mentions, getForObject might work, but this leads for me to other problems, as I have to use basic authentication, so its not really viable.I also tried casing-issues, naming the Variables accountID or AccountID, which did not work out.

答:
You can try using the getForObject method instead exchange.

Here is an example:

```<code>@JsonIgnoreProperties(ignoreUnknown = true)

public class Page {

    private String name;
    private String about;
    private String phone;
    private String website;

    public String getName() {
        return name;
    }

    public String getAbout() {
        return about;
    }

    public String getPhone() {
        return phone;
    }

    public String getWebsite() {
        return website;
    }

}

RestTemplate restTemplate = new RestTemplate();
Page page = restTemplate.getForObject("http://graph.facebook.com/pivotalsoftware", Page.class);
System.out.println("Name:    " + page.getName());
System.out.println("About:   " + page.getAbout());
System.out.println("Phone:   " + page.getPhone());
System.out.println("Website: " + page.getWebsite());
</code>```

Body:
So, I am using Spring Boot 1.5.3 and am trying to a part  of the following Json - - namely AccountId and Username- (actually, it is an oData v2 interface getting from a SAP Netweaver instance) into a class using restTemplate.exchange:

{
   "d":{
      "__metadata":{
         "id":"...",
         "uri":"...",
         "type":"...."
      },
      "AccountID":"0100000001",
      "Username":"test@test.com",
      "Partners":{
         "__deferred":{
            "uri":"Navigationproperty"
         }
      }
   }
}

My class is set up like this, because for a start I only want to get the account id and name:

@JsonIgnoreProperties(ignoreUnknown = true)
public class PortalAccount implements Serializable{

    public PortalAccount() {
    }

    @JsonProperty("AccountID")
    public String accountID;

    @JsonProperty("Username")
    public String username;

    public String getPortalAccountID() {
        return accountID;
    }

    public void setPortalAccountID(String portalAccountID) {
        this.accountID = portalAccountID;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String toString() {
        return "Account{" +
                "accountID='" + accountID + '\'' +
                ", username='" + username +'\'' +
                '}';
    }
}

and here's the way I try to call it:

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = this.createHeaders();
        ResponseEntity<String> response;
        response  = restTemplate.exchange(uri,HttpMethod.GET,new HttpEntity<Object>(httpHeaders),String.class);
        ObjectMapper mapper = new ObjectMapper();

        PortalAccount acc = mapper.readValue(response.getBody(), PortalAccount.class);

I first tried to parse it directly like in the docs using ResponseEntity<PortalAccount>, but this just lead to an empty class (accountid = null, username = null), So i tried the way above using ResponseEntity<String> to see what I get when just parsing the response into the string representation. That way, I could make sure the json above is correctly returned, which it is.So, the values are definitely there, it has to be a matter of parsing, but I sadly don't get my way around this problem.

I hope you could help me out here!

edit: As one answer mentions, getForObject might work, but this leads for me to other problems, as I have to use basic authentication, so its not really viable.I also tried casing-issues, naming the Variables accountID or AccountID, which did not work out.

Body:
You can try using the getForObject method instead exchange.

Here is an example:

@JsonIgnoreProperties(ignoreUnknown = true)

public class Page {

    private String name;
    private String about;
    private String phone;
    private String website;

    public String getName() {
        return name;
    }

    public String getAbout() {
        return about;
    }

    public String getPhone() {
        return phone;
    }

    public String getWebsite() {
        return website;
    }

}

RestTemplate restTemplate = new RestTemplate();
Page page = restTemplate.getForObject("http://graph.facebook.com/pivotalsoftware", Page.class);
System.out.println("Name:    " + page.getName());
System.out.println("About:   " + page.getAbout());
System.out.println("Phone:   " + page.getPhone());
System.out.println("Website: " + page.getWebsite());


问:
Pointers and Address in C
I write a C program. I have 2 pointers *a and *b. Now, I impose *a = 20 and *b = 10. After that I impose a = b in subroutine but the value seem doesn't change. I expect that *a = 10 and *b = 10. Please help me find a solution for this. Thank you.

```<code>#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void Copy(int *a1, int *a2)
{
    a1 = a2;
}

void Test()
{
    // a = 20
    int *a = (int *)malloc(sizeof(int));
    *a = 20;

    // b = 10
    int *b = (int *)malloc(sizeof(int));
    *b = 10;

    Copy(a, b); // a = b
    printf("\na = %d", *a);
    printf("\nb = %d", *b);
}

int main(int argc, char *argv[]){
    Test();
    fflush(stdin);
    printf("\nPress any key to continue");
    getchar();
    return 0;
}
</code>```

答:
Function arguments are passed by value. So inside the function Copy you are modifying a copy of the pointer not the original pointer you had in the Test function. So when you leave the Copy function the pointers outside are not modified.

Change the Copy to receive a int **, so you can change inside the value of pointers

```<code>void Copy(int **a1, int **a2)
{
    *a1 = *a2;
}
</code>```

And call the function in this way:

```<code>void Test() {
    ...
    Copy (&a, &b);
    ...
}
</code>```

Title: Pointers and Address in C

Body:
I write a C program. I have 2 pointers *a and *b. Now, I impose *a = 20 and *b = 10. After that I impose a = b in subroutine but the value seem doesn't change. I expect that *a = 10 and *b = 10. Please help me find a solution for this. Thank you.

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void Copy(int *a1, int *a2)
{
    a1 = a2;
}

void Test()
{
    // a = 20
    int *a = (int *)malloc(sizeof(int));
    *a = 20;

    // b = 10
    int *b = (int *)malloc(sizeof(int));
    *b = 10;

    Copy(a, b); // a = b
    printf("\na = %d", *a);
    printf("\nb = %d", *b);
}

int main(int argc, char *argv[]){
    Test();
    fflush(stdin);
    printf("\nPress any key to continue");
    getchar();
    return 0;
}

Body:
Function arguments are passed by value. So inside the function Copy you are modifying a copy of the pointer not the original pointer you had in the Test function. So when you leave the Copy function the pointers outside are not modified.

Change the Copy to receive a int **, so you can change inside the value of pointers

void Copy(int **a1, int **a2)
{
    *a1 = *a2;
}

And call the function in this way:

void Test() {
    ...
    Copy (&a, &b);
    ...
}


问:
Fetching incomplete object with Hibernate Mapping as native query
Consider an Entity which has four fields (yes it is not a valid Java code, just for demonstration):

```<code>@Entity
Sale {
    id, date, name, kind
}
</code>```

I can select his entity with entity manager easily as:

```<code>em.find(Sale.class, id)
</code>```

However if I wanted to make a simpler query and fill this object, I could do it via native query as Simple object:

```<code>em.createNativeQuery("SELECT s.id, s.date FROM sale s", Sale.class)
</code>```

The problem is that as there are missing fields, I am getting errors of missing columns: SQLException: Column name not found.

Is there a way to tell Hibernate to ignore the missing columns so that we can fetch only columns we need?

Edit: one of the answer suggested selecting NULL for each missing columns. The problem is that there might be probably around 40 columns and I certainly do not want to name them all.

答:
Try something like this:

```<code>em.createNamedQuery("SELECT id, date, cast(null as char(1)) name, cast(null as char(1)) kind from sale", Sale.class);
</code>```

Please note that char may need to change based on the data types of name and kind.

Body:
Consider an Entity which has four fields (yes it is not a valid Java code, just for demonstration):

@Entity
Sale {
    id, date, name, kind
}

I can select his entity with entity manager easily as:

em.find(Sale.class, id)

However if I wanted to make a simpler query and fill this object, I could do it via native query as Simple object:

em.createNativeQuery("SELECT s.id, s.date FROM sale s", Sale.class)

The problem is that as there are missing fields, I am getting errors of missing columns: SQLException: Column name not found.

Is there a way to tell Hibernate to ignore the missing columns so that we can fetch only columns we need?

Edit: one of the answer suggested selecting NULL for each missing columns. The problem is that there might be probably around 40 columns and I certainly do not want to name them all.

Body:
Try something like this:

em.createNamedQuery("SELECT id, date, cast(null as char(1)) name, cast(null as char(1)) kind from sale", Sale.class);

Please note that char may need to change based on the data types of name and kind.


问:
How do i work with windows media player from another form?
So i have 2 forms, one is called "musica" and its playing a music (this form is invisible) and the other is called "Form1" and gives the option to stop and start the music with radio buttons.

The problem is that the radio buttons are working, but the video continues even if i click on "radionButton2" and if i use the "stop()" function on "musica_load" the music stops so i don't think the problem is from there either.

What is my mistake here?

Form1 code:

```<code>musica mus = new musica();
private void radioButton1_CheckedChanged(object sender, EventArgs e)
    {
        if (radioButton1.Checked == true)
        {
            mus.play();

        }
    }

    private void radioButton2_CheckedChanged(object sender, EventArgs e)
    {
        if (radioButton2.Checked == true)
        {
            mus.stop();

        }
    }
</code>```

musica code:

```<code>    public void play()
    {
            axWindowsMediaPlayer1.Ctlcontrols.play();
    }
    public void stop()
    {
            axWindowsMediaPlayer1.Ctlcontrols.stop();
    }
</code>```

答: Answer: The problem was that i was opennig both forms simultaneously at the start of the program and for some reason they can't work between each other, if i open the musica.cs in Form1_load everything works!

Body:
So i have 2 forms, one is called "musica" and its playing a music (this form is invisible) and the other is called "Form1" and gives the option to stop and start the music with radio buttons.

The problem is that the radio buttons are working, but the video continues even if i click on "radionButton2" and if i use the "stop()" function on "musica_load" the music stops so i don't think the problem is from there either.

What is my mistake here?

Form1 code:

musica mus = new musica();
private void radioButton1_CheckedChanged(object sender, EventArgs e)
    {
        if (radioButton1.Checked == true)
        {
            mus.play();

        }
    }

    private void radioButton2_CheckedChanged(object sender, EventArgs e)
    {
        if (radioButton2.Checked == true)
        {
            mus.stop();

        }
    }

musica code:

    public void play()
    {
            axWindowsMediaPlayer1.Ctlcontrols.play();
    }
    public void stop()
    {
            axWindowsMediaPlayer1.Ctlcontrols.stop();
    }


问:
Diffrence between XAMPP 5.6 and 7.1.4
I wonder why Apache still offers and promotes version 5.6 of XAMPP when they got newer versions like 7.1.4?
As you can see herethere are different PhP Versions in each Version but is legacy the only reason someone would use an older xampp version or are any other aspects that I am missing?</p>

答:
Because XAMPP v5.6 offers PHP v5.6; XAMPP v7.1.4 comes with PHP v7.0.18 not all developers have their environments past that version of PHP---and for legacy purposes too (for older PHP apps that have yet to migrate to the latest and greatest PHP version)

Hope this helps!

Best,

-Rush

ContentLicense: CC BY-SA 4.0

Title: Diffrence between XAMPP 5.6 and 7.1.4


问:
Doctrine select all users that manage other users via column
Maybe I am missing something completely, but I cannot get it working. I only want to select User objects that are linked to User objects.

User:

```<code>class User implements AdvancedUserInterface, \Serializable
{
/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

// other fields ...

/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\User")
 */
private $firstManager;

/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\User")
 */
private $secondManager;

}
</code>```

I want to select those who are firstManager or secondManager for a User. Sounds simple eh?

I thought, this would do:

```<code>public function findAllManagers()
{
    $qb = $this->createQueryBuilder('user')
        ->join('user.firstManager', 'first_manager')
        ->join('user.secondManager', 'second_manager')
        ->orWhere('first_manager = user')
        ->orWhere('second_manager = user');
    $qb = $qb->getQuery();

    return $qb->getResult();
}
</code>```

But only got one result, not all three I needed. I think this is valid SQL?

答:
->join() results in an INNER JOIN. As you can read here, this will only give results, that are "in the center". If you have multiple JOINs, this will only give results of all those joined tables. In your case, this means users that are firstManager and secondManager.

If you change to ->leftJoin(), this will give you all users (with additional info), so it is a good place to start. Then you can filter those out that are neither firstManager or secondManager.

Something like this should work (untested)

```<code>$result = $this->createQueryBuilder('user')
   ->leftJoin('user.firstManager', 'fm')
   ->leftJoin('user.secondManager', 'sm')
   ->where('fm.id IS NOT NULL')
   ->orWhere('sm.id IS NOT NULL')
   ->getQuery()
   ->getResult()
;
</code>```

Body:
Maybe I am missing something completely, but I cannot get it working. I only want to select User objects that are linked to User objects.

User:

class User implements AdvancedUserInterface, \Serializable
{
/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

// other fields ...

/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\User")
 */
private $firstManager;

/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\User")
 */
private $secondManager;

}

I want to select those who are firstManager or secondManager for a User. Sounds simple eh?

I thought, this would do:

public function findAllManagers()
{
    $qb = $this->createQueryBuilder('user')
        ->join('user.firstManager', 'first_manager')
        ->join('user.secondManager', 'second_manager')
        ->orWhere('first_manager = user')
        ->orWhere('second_manager = user');
    $qb = $qb->getQuery();

    return $qb->getResult();
}

But only got one result, not all three I needed. I think this is valid SQL?

Body:
->join() results in an INNER JOIN. As you can read here, this will only give results, that are "in the center". If you have multiple JOINs, this will only give results of all those joined tables. In your case, this means users that are firstManager and secondManager.

If you change to ->leftJoin(), this will give you all users (with additional info), so it is a good place to start. Then you can filter those out that are neither firstManager or secondManager.

Something like this should work (untested)

$result = $this->createQueryBuilder('user')
   ->leftJoin('user.firstManager', 'fm')
   ->leftJoin('user.secondManager', 'sm')
   ->where('fm.id IS NOT NULL')
   ->orWhere('sm.id IS NOT NULL')
   ->getQuery()
   ->getResult()
;


问:
Ajax request gets 500 (Internal Server Error) on cordova
I have an ajax request, when I make the request in the browser it works fine, when i make it inside cordova apk, I get internal error,
I've look into both headers, the only diference is in the ORIGIN;

This is the one not working, with origin:file://

POST http://XXX:50000/RESTAdapter/s4p/mobile/login 500 (Internal Server Error)

Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate
Accept-Language:en-US
Connection:keep-alive
Content-Length:59
Content-Type:application/json
Cookie:saplb_*=(J2EE9465620)9465650
Host:-------
Origin:file://
User-Agent:Mozilla/5.0 (Linux; Android 7.0; Android SDK built for x86 Build/NYC; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/51.0.2704.90 Mobile Safari/537.36
X-DevTools-Emulate-Network-Conditions-Client-Id:364FC1A3-AE91-465B-821A-9EA13D731E5E
X-Requested-With:io.cordova.hellocordova

答: Your AJAX request arrives to the server and you get an error there, on your server. Due to the error, the response is a 500. If you know that this works in some cases and does not work in other cases, then check the differences between the different requests and see what is the stack trace of the error. When you have done that, you will know what the problem is. And from there on, you will be in an infinitely better position than now to fix the issue.</p>


问:
How can I edit Chrome MIME type mappings?
I opened a image/x-png type image in new tab, but Chrome just downloaded it.
I googled it and found that Chrome doesn't interpret image/x-png as image file.

So, I want to edit my Chrome's MIME type mappings. Is it possible?

答: There is a Chrome extension that can change the content-type and the disposition for any pattern, so it can be used to force png to display instead of download (but it is good for many other cases, I am using it to render txt as HTML): Modify Content-Type Chrome Extension</p>


问:
Unity collider prefab doesn't work on one side
I have a collider prefab (a cube, with a box collider the size of the cube). In one scene, my player collides perfectly with it, but in another scene, the player glitches and phases through one side of the collider but not the other. Rotating it changes the side that it glitches out on, so it always faces the same global direction.

What could be causing this? I've made sure the prefab for both the player and collider object are exactly the same across scenes, and nothing effects the collisions besides the player controller script which moves the player and has a condition for OnCollisionExit that sets the rigidbody's velocity to 0.

Added the code below. The input is with joysticks (think the joysticks in a helicopter). Like I said, the collision works perfectly usually, but for some reason only in this scene it doesn't. I suspect it's some kind of hierarchy or rigidbody problem but I've checked seemingly everything.

https://github.com/ben-humphries/FRC-Driving-Simulation

```<code>using UnityEngine;
using UnityEngine.UI;

public class ChassisController : MonoBehaviour {

    public UIController uiController;

    public Canvas PauseCanvas;

    public float speedLinear = 10f;
    public float speedAngular = 100f;
    public float joyDeadZone = 0.5f;

    public float rotationOffset = 3f;

    public bool squaredMovement = false;

    public DriveModes driveMode = DriveModes.Tank;

    [HideInInspector]
    public bool paused = false;

    private Rigidbody rigidbody;

    Vector3 lastLinearPosition;
    float lastAngularPosition;

    void Start () {

        rigidbody = GetComponent<Rigidbody> ();

        lastLinearPosition = Vector3.zero;
        lastAngularPosition = 0f;
        paused = false;

    }

    void FixedUpdate () {

        if (!paused) {

            /*
         * INPUT
         */

            if (driveMode == DriveModes.Tank) {

                if (Mathf.Abs (Input.GetAxis ("VerticalLeft")) > joyDeadZone) {

                    Vector3 rotatePoint = (transform.position) + transform.TransformDirection (Vector3.right) * rotationOffset;
                    Vector3 rotateAxis = transform.TransformDirection (Vector3.up);

                    Debug.DrawRay (rotatePoint, rotateAxis * 10f, Color.red);

                    transform.RotateAround (rotatePoint, rotateAxis, -speedAngular * Input.GetAxis ("VerticalLeft") * Time.fixedDeltaTime * (squaredMovement ? Mathf.Abs (Input.GetAxis ("VerticalLeft")) : 1));

                }
                if (Mathf.Abs (Input.GetAxis ("VerticalRight")) > joyDeadZone) {
                    Vector3 rotatePoint = (transform.position) + transform.TransformDirection (Vector3.left) * rotationOffset;
                    Vector3 rotateAxis = transform.TransformDirection (Vector3.up);

                    Debug.DrawRay (rotatePoint, rotateAxis * 10f, Color.red);

                    transform.RotateAround (rotatePoint, rotateAxis, speedAngular * Input.GetAxis ("VerticalRight") * Time.fixedDeltaTime * (squaredMovement ? Mathf.Abs (Input.GetAxis ("VerticalRight")) : 1));

                }

            } else if (driveMode == DriveModes.Mecanum) {

                if (Mathf.Abs (Input.GetAxis ("VerticalRight")) > joyDeadZone) {
                    transform.Translate (Vector3.forward * -speedLinear * Input.GetAxis ("VerticalRight") * Time.fixedDeltaTime * (squaredMovement ? Mathf.Abs (Input.GetAxis ("VerticalRight")) : 1));
                }

                if (Mathf.Abs (Input.GetAxis ("HorizontalRight")) > joyDeadZone) {
                    transform.Translate (Vector3.right * speedLinear / 5f * Input.GetAxis ("HorizontalRight") * Time.fixedDeltaTime * (squaredMovement ? Mathf.Abs (Input.GetAxis ("HorizontalRight")) : 1));
                }

                if (Mathf.Abs (Input.GetAxis ("TwistRight")) > joyDeadZone) {
                    transform.Rotate (0, speedAngular * Input.GetAxis ("TwistRight") * Time.fixedDeltaTime * (squaredMovement ? Mathf.Abs (Input.GetAxis ("TwistRight")) : 1), 0);

                }

            }

            float linearVelocity = Mathf.Round (((transform.position - lastLinearPosition) / Time.fixedDeltaTime).magnitude * 100f) / 100f;
            lastLinearPosition = transform.position;

            float angularVelocity = Mathf.Round ((transform.eulerAngles.y - lastAngularPosition) / Time.fixedDeltaTime * Mathf.Deg2Rad  * 100f) / 100f;
            lastAngularPosition = transform.eulerAngles.y;

            uiController.UpdateVelocities (linearVelocity, angularVelocity);

        }
    }

    void OnCollisionExit(Collision col){

        rigidbody.isKinematic = true;

        rigidbody.velocity = Vector3.zero;
        rigidbody.angularVelocity = Vector3.zero;

        rigidbody.isKinematic = false;

    }
    public enum DriveModes{
        Tank,
        Mecanum
    }

    public void setDriveMode(){

        int index = PauseCanvas.transform.GetChild (1).GetComponent<Dropdown> ().value;

        if (index == 0) {
            driveMode = DriveModes.Tank;
        } else if (index == 1) {
            driveMode = DriveModes.Mecanum;
        }

        uiController.UpdateDriveMode (index == 0 ? "Tank" : "Mecanum");
    }
}
</code>```

答:
When GameObject has Rigidbody and Collider and you want collision, do not move the Object by transform.Translate or rotate it with transform.Rotate or  transform.RotateAround. When you do this there will be no collision.

The right way to move GameObject with a Rigidbody and Collision is with the Rigidbody.MovePosition function.

The correct way to rotate it is to use the Rigidbody.MoveRotation function.

Example of Rigidbody.MovePosition:

```<code>float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");

Vector3 tempVect = new Vector3(h, 0, v);
tempVect = tempVect.normalized * speed * Time.deltaTime;
rb.MovePosition(transform.position + tempVect);
</code>```

Example of Rigidbody.MoveRotation:

```<code>Quaternion deltaRotation = Quaternion.Euler(eulerAngleVelocity * Time.deltaTime);
rb.MoveRotation(rb.rotation * deltaRotation);
</code>```

You need to replace transform.Translate, transform.Rotate and transform.RotateAround with these.

Body:
I have a collider prefab (a cube, with a box collider the size of the cube). In one scene, my player collides perfectly with it, but in another scene, the player glitches and phases through one side of the collider but not the other. Rotating it changes the side that it glitches out on, so it always faces the same global direction.

What could be causing this? I've made sure the prefab for both the player and collider object are exactly the same across scenes, and nothing effects the collisions besides the player controller script which moves the player and has a condition for OnCollisionExit that sets the rigidbody's velocity to 0.

Added the code below. The input is with joysticks (think the joysticks in a helicopter). Like I said, the collision works perfectly usually, but for some reason only in this scene it doesn't. I suspect it's some kind of hierarchy or rigidbody problem but I've checked seemingly everything.

https://github.com/ben-humphries/FRC-Driving-Simulation

using UnityEngine;
using UnityEngine.UI;

public class ChassisController : MonoBehaviour {

    public UIController uiController;

    public Canvas PauseCanvas;

    public float speedLinear = 10f;
    public float speedAngular = 100f;
    public float joyDeadZone = 0.5f;

    public float rotationOffset = 3f;

    public bool squaredMovement = false;

    public DriveModes driveMode = DriveModes.Tank;

    [HideInInspector]
    public bool paused = false;

    private Rigidbody rigidbody;

    Vector3 lastLinearPosition;
    float lastAngularPosition;

    void Start () {

        rigidbody = GetComponent<Rigidbody> ();

        lastLinearPosition = Vector3.zero;
        lastAngularPosition = 0f;
        paused = false;

    }

    void FixedUpdate () {

        if (!paused) {

            /*
         * INPUT
         */

            if (driveMode == DriveModes.Tank) {

                if (Mathf.Abs (Input.GetAxis ("VerticalLeft")) > joyDeadZone) {

                    Vector3 rotatePoint = (transform.position) + transform.TransformDirection (Vector3.right) * rotationOffset;
                    Vector3 rotateAxis = transform.TransformDirection (Vector3.up);

                    Debug.DrawRay (rotatePoint, rotateAxis * 10f, Color.red);

                    transform.RotateAround (rotatePoint, rotateAxis, -speedAngular * Input.GetAxis ("VerticalLeft") * Time.fixedDeltaTime * (squaredMovement ? Mathf.Abs (Input.GetAxis ("VerticalLeft")) : 1));

                }
                if (Mathf.Abs (Input.GetAxis ("VerticalRight")) > joyDeadZone) {
                    Vector3 rotatePoint = (transform.position) + transform.TransformDirection (Vector3.left) * rotationOffset;
                    Vector3 rotateAxis = transform.TransformDirection (Vector3.up);

                    Debug.DrawRay (rotatePoint, rotateAxis * 10f, Color.red);

                    transform.RotateAround (rotatePoint, rotateAxis, speedAngular * Input.GetAxis ("VerticalRight") * Time.fixedDeltaTime * (squaredMovement ? Mathf.Abs (Input.GetAxis ("VerticalRight")) : 1));

                }

            } else if (driveMode == DriveModes.Mecanum) {

                if (Mathf.Abs (Input.GetAxis ("VerticalRight")) > joyDeadZone) {
                    transform.Translate (Vector3.forward * -speedLinear * Input.GetAxis ("VerticalRight") * Time.fixedDeltaTime * (squaredMovement ? Mathf.Abs (Input.GetAxis ("VerticalRight")) : 1));
                }

                if (Mathf.Abs (Input.GetAxis ("HorizontalRight")) > joyDeadZone) {
                    transform.Translate (Vector3.right * speedLinear / 5f * Input.GetAxis ("HorizontalRight") * Time.fixedDeltaTime * (squaredMovement ? Mathf.Abs (Input.GetAxis ("HorizontalRight")) : 1));
                }

                if (Mathf.Abs (Input.GetAxis ("TwistRight")) > joyDeadZone) {
                    transform.Rotate (0, speedAngular * Input.GetAxis ("TwistRight") * Time.fixedDeltaTime * (squaredMovement ? Mathf.Abs (Input.GetAxis ("TwistRight")) : 1), 0);

                }

            }

            float linearVelocity = Mathf.Round (((transform.position - lastLinearPosition) / Time.fixedDeltaTime).magnitude * 100f) / 100f;
            lastLinearPosition = transform.position;

            float angularVelocity = Mathf.Round ((transform.eulerAngles.y - lastAngularPosition) / Time.fixedDeltaTime * Mathf.Deg2Rad  * 100f) / 100f;
            lastAngularPosition = transform.eulerAngles.y;

            uiController.UpdateVelocities (linearVelocity, angularVelocity);

        }
    }

    void OnCollisionExit(Collision col){

        rigidbody.isKinematic = true;

        rigidbody.velocity = Vector3.zero;
        rigidbody.angularVelocity = Vector3.zero;

        rigidbody.isKinematic = false;

    }
    public enum DriveModes{
        Tank,
        Mecanum
    }

    public void setDriveMode(){

        int index = PauseCanvas.transform.GetChild (1).GetComponent<Dropdown> ().value;

        if (index == 0) {
            driveMode = DriveModes.Tank;
        } else if (index == 1) {
            driveMode = DriveModes.Mecanum;
        }

        uiController.UpdateDriveMode (index == 0 ? "Tank" : "Mecanum");
    }
}

Body:
When GameObject has Rigidbody and Collider and you want collision, do not move the Object by transform.Translate or rotate it with transform.Rotate or  transform.RotateAround. When you do this there will be no collision.

The right way to move GameObject with a Rigidbody and Collision is with the Rigidbody.MovePosition function.

The correct way to rotate it is to use the Rigidbody.MoveRotation function.

Example of Rigidbody.MovePosition:

float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");

Vector3 tempVect = new Vector3(h, 0, v);
tempVect = tempVect.normalized * speed * Time.deltaTime;
rb.MovePosition(transform.position + tempVect);

Example of Rigidbody.MoveRotation:

Quaternion deltaRotation = Quaternion.Euler(eulerAngleVelocity * Time.deltaTime);
rb.MoveRotation(rb.rotation * deltaRotation);

You need to replace transform.Translate, transform.Rotate and transform.RotateAround with these.


问:
Bootstrap checkbox size wrong with smaller body font
I have set my default font size to be based on 10px via 62.5%, and then set the body to be 1.4rem. This seems to cause issues with the custom checkbox controls and they no longer align correctly.

I'm using Bootstrap 4's SASS files combined with my own. Is there something in the variables file that I'm missing to fix this? Or maybe some overrides I need to do? I've tried messing with various padding, margins, font sizes, etc. but the way they have this working isn't obvious.

Here is what I have set for the default font sizes for the site:

```<code>html {
  font-size: 62.5%;
}
body {
  font-size: 1.4rem;
}
</code>```

And here is the HTML

```<code><div class="container-fluid">
  <div class="row align-items-end">
    <div class="col">
      <div class="form-group">
        <label for="worker">Worker</label>
        <select class="form-control" id="worker">
          <option>Jane Doe</option>
          <option>John Smith</option>
        </select>
      </div>
    </div>
    <div class="col">
      <div class="form-group">
        <label class="custom-control custom-checkbox">
          <input type="checkbox" class="custom-control-input">
          <span class="custom-control-indicator"></span>
          <span class="custom-control-description">Check this custom checkbox</span>
        </label>
      </div>
    </div>
  </div>
</div>
</code>```

JSFiddle

To sum up, basically I need the ability to change the body font size and yet still have the checkbox to still work correctly and be the same height as the input fields when they are next to each other.

答:
A simple solution would be to change the styles for the checkbox:

```<code>.custom-control-indicator {
    height: 1.4rem;
    width: 1.4rem;
    top: calc(1.4rem * 0.25);
}
</code>```

Change the 1.4rem as required to the same size as the body font-size (you can also set this up to work automatically using SASS variables

Body:
I have set my default font size to be based on 10px via 62.5%, and then set the body to be 1.4rem. This seems to cause issues with the custom checkbox controls and they no longer align correctly.

I'm using Bootstrap 4's SASS files combined with my own. Is there something in the variables file that I'm missing to fix this? Or maybe some overrides I need to do? I've tried messing with various padding, margins, font sizes, etc. but the way they have this working isn't obvious.

Here is what I have set for the default font sizes for the site:

html {
  font-size: 62.5%;
}
body {
  font-size: 1.4rem;
}

And here is the HTML

        Worker
        <select class="form-control" id="worker">
          <option>Jane Doe</option>
          <option>John Smith</option>
        </select>

          <input type="checkbox" class="custom-control-input">

          Check this custom checkbox

JSFiddle

To sum up, basically I need the ability to change the body font size and yet still have the checkbox to still work correctly and be the same height as the input fields when they are next to each other.

Body:
A simple solution would be to change the styles for the checkbox:

.custom-control-indicator {
    height: 1.4rem;
    width: 1.4rem;
    top: calc(1.4rem * 0.25);
}

Change the 1.4rem as required to the same size as the body font-size (you can also set this up to work automatically using SASS variables


问:
Any better Fibonacci series generator using pure Oracle SQL?
I wonder if there is any way to generate Fibonacci numbers that beat in simplicity and efficiency this one I wrote:

```<code>WITH d (seq) AS
       (SELECT     LEVEL
        FROM       DUAL
        CONNECT BY LEVEL < 195)
SELECT   seq
        ,fib
FROM     d
MODEL
  DIMENSION BY(seq)
  MEASURES(0 AS fib)
  RULES
    (fib [1] = 0,
    fib [2] = 1,
    fib [seq BETWEEN 3 AND 194] = fib[CV(seq) - 2] + fib[CV(seq) - 1],
    fib [seq > 194] = NULL)
ORDER BY 1
/
Execution Plan
----------------------------------------------------------
Plan hash value: 2245903385

---------------------------------------------------------------------------------------
| Id  | Operation                      | Name | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT               |      |     1 |    13 |     2   (0)| 00:00:01 |
|   1 |  SQL MODEL ORDERED             |      |     1 |    13 |            |          |
|   2 |   VIEW                         |      |     1 |    13 |     2   (0)| 00:00:01 |
|*  3 |    CONNECT BY WITHOUT FILTERING|      |       |       |            |          |
|   4 |     FAST DUAL                  |      |     1 |       |     2   (0)| 00:00:01 |
---------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   3 - filter(LEVEL<195)

Statistics
----------------------------------------------------------
          0  recursive calls
          0  db block gets
          0  consistent gets
          0  physical reads
          0  redo size
       4798  bytes sent via SQL*Net to client
        500  bytes received via SQL*Net from client
         14  SQL*Net roundtrips to/from client
          1  sorts (memory)
          0  sorts (disk)
        194  rows processed

SQL>
</code>```

Note: LEVEL < 195 was not arbitrarily chosen, higher values make the algorithm lose precision so I decided not to include them in order to keep correct results only.

答:
Something like this should be (much?) faster:

```<code>with
     constants ( x, y, z ) as (
       select 0.5 * ( 1 + sqrt(5) ),
              0.5 * ( 1 - sqrt(5) ),
              sqrt(5)
       from   dual
     )
select level as seq, round( ( power(x, level - 1) - power(y, level - 1) ) / z ) as fib
from   constants
connect by level < 195
;
</code>```

The point being, you don't need to use the recursive formula; the terms can be written in closed form. Since computers can't do arithmetic with real numbers, only with rational number approximations, I needed to add a ROUND(...) but even so this should be faster than recursive approaches.

EDIT: At the OP's request I traced the execution of this code. I don't see the recursive calls the OP is referring to in the Comment below.

```<code>Execution Plan
----------------------------------------------------------
Plan hash value: 1236776825

-----------------------------------------------------------------------------
| Id  | Operation                    | Name | Rows  | Cost (%CPU)| Time     |
-----------------------------------------------------------------------------
|   0 | SELECT STATEMENT             |      |     1 |     2   (0)| 00:00:01 |
|*  1 |  CONNECT BY WITHOUT FILTERING|      |       |            |          |
|   2 |   FAST DUAL                  |      |     1 |     2   (0)| 00:00:01 |
-----------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter(LEVEL<195)

Statistics
----------------------------------------------------------
          0  recursive calls
          0  db block gets
          0  consistent gets
          0  physical reads
          0  redo size
       6306  bytes sent via SQL*Net to client
        684  bytes received via SQL*Net from client
         14  SQL*Net roundtrips to/from client
          1  sorts (memory)
          0  sorts (disk)
        194  rows processed
</code>```

EDIT #2

I suspect the simple generation of levels in a recursive query may be expensive. It's possible that a cross-join of similarly generated, but smaller sequences of integers may work a bit faster. The code looks more complicated (of course); the only change, though, is the way I generate the powers.

```<code>with
     constants ( x, y, z ) as (
       select 0.5 * ( 1 + sqrt(5) ),
              0.5 * ( 1 - sqrt(5) ),
              sqrt(5)
       from   dual
     ),
     powers ( n ) as (
       select 14 * a.p + b.q
       from   (select level - 1 p from dual connect by level <= 14) a
              cross join
              (select level - 1 q from dual connect by level <= 14) b
     )
select n + 1 as seq, round( ( power(x, n) - power(y, n) ) / z ) as fib
from   constants cross join powers
where  n < 195
;
</code>```

Body:
I wonder if there is any way to generate Fibonacci numbers that beat in simplicity and efficiency this one I wrote:

WITH d (seq) AS
       (SELECT     LEVEL
        FROM       DUAL
        CONNECT BY LEVEL < 195)
SELECT   seq
        ,fib
FROM     d
MODEL
  DIMENSION BY(seq)
  MEASURES(0 AS fib)
  RULES
    (fib [1] = 0,
    fib [2] = 1,
    fib [seq BETWEEN 3 AND 194] = fib[CV(seq) - 2] + fib[CV(seq) - 1],
    fib [seq > 194] = NULL)
ORDER BY 1
/
Execution Plan
----------------------------------------------------------
Plan hash value: 2245903385

---------------------------------------------------------------------------------------
| Id  | Operation                      | Name | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT               |      |     1 |    13 |     2   (0)| 00:00:01 |
|   1 |  SQL MODEL ORDERED             |      |     1 |    13 |            |          |
|   2 |   VIEW                         |      |     1 |    13 |     2   (0)| 00:00:01 |
|*  3 |    CONNECT BY WITHOUT FILTERING|      |       |       |            |          |
|   4 |     FAST DUAL                  |      |     1 |       |     2   (0)| 00:00:01 |
---------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   3 - filter(LEVEL<195)

Statistics
----------------------------------------------------------
          0  recursive calls
          0  db block gets
          0  consistent gets
          0  physical reads
          0  redo size
       4798  bytes sent via SQL*Net to client
        500  bytes received via SQL*Net from client
         14  SQL*Net roundtrips to/from client
          1  sorts (memory)
          0  sorts (disk)
        194  rows processed

SQL>

Note: LEVEL < 195 was not arbitrarily chosen, higher values make the algorithm lose precision so I decided not to include them in order to keep correct results only.

Body:
Something like this should be (much?) faster:

with
     constants ( x, y, z ) as (
       select 0.5 * ( 1 + sqrt(5) ),
              0.5 * ( 1 - sqrt(5) ),
              sqrt(5)
       from   dual
     )
select level as seq, round( ( power(x, level - 1) - power(y, level - 1) ) / z ) as fib
from   constants
connect by level < 195
;

The point being, you don't need to use the recursive formula; the terms can be written in closed form. Since computers can't do arithmetic with real numbers, only with rational number approximations, I needed to add a ROUND(...) but even so this should be faster than recursive approaches.

EDIT: At the OP's request I traced the execution of this code. I don't see the recursive calls the OP is referring to in the Comment below.

Execution Plan
----------------------------------------------------------
Plan hash value: 1236776825

-----------------------------------------------------------------------------
| Id  | Operation                    | Name | Rows  | Cost (%CPU)| Time     |
-----------------------------------------------------------------------------
|   0 | SELECT STATEMENT             |      |     1 |     2   (0)| 00:00:01 |
|*  1 |  CONNECT BY WITHOUT FILTERING|      |       |            |          |
|   2 |   FAST DUAL                  |      |     1 |     2   (0)| 00:00:01 |
-----------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter(LEVEL<195)

Statistics
----------------------------------------------------------
          0  recursive calls
          0  db block gets
          0  consistent gets
          0  physical reads
          0  redo size
       6306  bytes sent via SQL*Net to client
        684  bytes received via SQL*Net from client
         14  SQL*Net roundtrips to/from client
          1  sorts (memory)
          0  sorts (disk)
        194  rows processed

EDIT #2

I suspect the simple generation of levels in a recursive query may be expensive. It's possible that a cross-join of similarly generated, but smaller sequences of integers may work a bit faster. The code looks more complicated (of course); the only change, though, is the way I generate the powers.

with
     constants ( x, y, z ) as (
       select 0.5 * ( 1 + sqrt(5) ),
              0.5 * ( 1 - sqrt(5) ),
              sqrt(5)
       from   dual
     ),
     powers ( n ) as (
       select 14 * a.p + b.q
       from   (select level - 1 p from dual connect by level <= 14) a
              cross join
              (select level - 1 q from dual connect by level <= 14) b
     )
select n + 1 as seq, round( ( power(x, n) - power(y, n) ) / z ) as fib
from   constants cross join powers
where  n < 195
;


答:
use eval

```<code>print (10 + eval(animal))
</code>```

In your case this would probably be a problem, but when creating more complexe it may present some security issue.
Refer to : Is using eval in Python a bad practice?

Althought in some case if may be convenient to generate code, as pointed out in the comment, use with caution.

EDIT : You can use a safer version which will only evaluated litteral expression :

```<code>import ast
print ( 10 + int(ast.literal_eval(  animal)))
</code>```

Title: How to turn a string of letters into integer?

Body:
Specifically, I'm taking a word that a user inputs, which is equivalent to a number (that the user wouldn't know).

my code:

animal = raw_input( > )  #and a user inputs cat
dog = 30
cat = 10
frog = 5
print 10 + int(animal) #with the hope that will output 20

Not sure how to do it..

Body:
use eval

print (10 + eval(animal))

In your case this would probably be a problem, but when creating more complexe it may present some security issue.
Refer to : Is using eval in Python a bad practice?

Althought in some case if may be convenient to generate code, as pointed out in the comment, use with caution.

EDIT : You can use a safer version which will only evaluated litteral expression :

import ast
print ( 10 + int(ast.literal_eval(  animal)))


问:
Loading folders of images in tensorflow
I'm new to tensorflow, but i already followed and executed the tutorials they promote and many others all over the web.
I made a little convolutional neural network over the MNIST images. Nothing special, but i would like to test on my own images.
Now my problem comes: I created several folders; the name of each folder is the class (label) the images inside belong.

The images have different shapes; i mean they have no fixed size.

How can i load them for using with Tensorflow?

I followed many tutorials and answers both here on StackOverflow and on others Q/A sites. But still, i did not figure out how to do this.

答:
Sample input pipeline script to load images and labels from directory. You could do preprocessing(resizing images etc.,) after this.

```<code>import tensorflow as tf
filename_queue = tf.train.string_input_producer(
tf.train.match_filenames_once("/home/xxx/Desktop/stackoverflow/images/*/*.png"))

image_reader = tf.WholeFileReader()
key, image_file = image_reader.read(filename_queue)
S = tf.string_split([key],'/')
length = tf.cast(S.dense_shape[1],tf.int32)
# adjust constant value corresponding to your paths if you face issues. It should work for above format.
label = S.values[length-tf.constant(2,dtype=tf.int32)]
label = tf.string_to_number(label,out_type=tf.int32)
image = tf.image.decode_png(image_file)

# Start a new session to show example output.
with tf.Session() as sess:
    # Required to get the filename matching to run.
    tf.initialize_all_variables().run()

    # Coordinate the loading of image files.
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    for i in xrange(6):
        # Get an image tensor and print its value.
        key_val,label_val,image_tensor = sess.run([key,label,image])
        print(image_tensor.shape)
        print(key_val)
        print(label_val)

    # Finish off the filename queue coordinator.
    coord.request_stop()
    coord.join(threads)
</code>```

File Directory

```<code>./images/1/1.png
./images/1/2.png
./images/3/1.png
./images/3/2.png
./images/2/1.png
./images/2/2.png
</code>```

Output:

```<code> (881, 2079, 3)
 /home/xxxx/Desktop/stackoverflow/images/3/1.png
 3
 (155, 2552, 3)
 /home/xxxx/Desktop/stackoverflow/images/2/1.png
 2
 (562, 1978, 3)
 /home/xxxx/Desktop/stackoverflow/images/3/2.png
 3
 (291, 2558, 3)
 /home/xxxx/Desktop/stackoverflow/images/1/1.png
 1
 (157, 2554, 3)
 /home/xxxx/Desktop/stackoverflow/images/1/2.png
 1
 (866, 936, 3)
 /home/xxxx/Desktop/stackoverflow/images/2/2.png
 2
</code>```

Title: Loading folders of images in tensorflow

Body:
Sample input pipeline script to load images and labels from directory. You could do preprocessing(resizing images etc.,) after this.

import tensorflow as tf
filename_queue = tf.train.string_input_producer(
tf.train.match_filenames_once("/home/xxx/Desktop/stackoverflow/images/*/*.png"))

image_reader = tf.WholeFileReader()
key, image_file = image_reader.read(filename_queue)
S = tf.string_split([key],'/')
length = tf.cast(S.dense_shape[1],tf.int32)
# adjust constant value corresponding to your paths if you face issues. It should work for above format.
label = S.values[length-tf.constant(2,dtype=tf.int32)]
label = tf.string_to_number(label,out_type=tf.int32)
image = tf.image.decode_png(image_file)

# Start a new session to show example output.
with tf.Session() as sess:
    # Required to get the filename matching to run.
    tf.initialize_all_variables().run()

    # Coordinate the loading of image files.
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    for i in xrange(6):
        # Get an image tensor and print its value.
        key_val,label_val,image_tensor = sess.run([key,label,image])
        print(image_tensor.shape)
        print(key_val)
        print(label_val)

    # Finish off the filename queue coordinator.
    coord.request_stop()
    coord.join(threads)

File Directory

./images/1/1.png
./images/1/2.png
./images/3/1.png
./images/3/2.png
./images/2/1.png
./images/2/2.png

Output:

 (881, 2079, 3)
 /home/xxxx/Desktop/stackoverflow/images/3/1.png
 3
 (155, 2552, 3)
 /home/xxxx/Desktop/stackoverflow/images/2/1.png
 2
 (562, 1978, 3)
 /home/xxxx/Desktop/stackoverflow/images/3/2.png
 3
 (291, 2558, 3)
 /home/xxxx/Desktop/stackoverflow/images/1/1.png
 1
 (157, 2554, 3)
 /home/xxxx/Desktop/stackoverflow/images/1/2.png
 1
 (866, 936, 3)
 /home/xxxx/Desktop/stackoverflow/images/2/2.png
 2


问:
How to bring running chrome instance in foreground/ontop when test is run through fitnesse wiki
I have different selenium tests created on my fitnesse wiki. Fitnesse wiki is opened in a chrome browser.
Now, When I hit on Test to run a particular test on fitnesse wiki, it opens a new chrome instance and runs tests there. The problem is that the new chrome instance opens in background and I can not see the execution unless I manually click the running chrome instance to bring it to foreground. My requirement is that whenever a new instance opened, it should get opened in foreground/OnTop without any manual intervention.
How can I achieve this using selenium C#.
Any help will be very much appreciated.</p>

答:
Since Chrome was opened by Selenium, you should have access to that window.

Try to maximize the window:

```<code>driver.Manage().Window.Maximize();
</code>```

Body:
Since Chrome was opened by Selenium, you should have access to that window.

Try to maximize the window:

driver.Manage().Window.Maximize();


问:
Angular2 Subscribe Not Working About Service
Although I have tried many times, but not working EMIT or SUBSCRIBE.

I want to hide app-header, app-sidebar and app-footer in

LoginComponent. Also *ngIf not listening GlobalService variable.

Thanks in advance for your support.

/* App HTML */

<app-header *ngIf="global.showHeader"></app-header>

<app-sidebar *ngIf="global.showSidebar"></app-sidebar>

    <router-outlet></router-outlet>

<app-footer *ngIf="global.showFooter"></app-footer>
```

<pre class="lang-js prettyprint-override"><code>/* AppComponent */

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  providers: [AppGlobalService]
})
export class AppComponent implements OnInit{

  global = {};

  constructor(private globalService: AppGlobalService) {

    this.globalService.listenUpdated.subscribe(

      data => {

        this.global = data;

      }

    );
  }

  ngOnInit(){
  }
}
</code>```

/* AppGlobalService */

@Injectable()
export class AppGlobalService {

    data={
        showHeader: true,
        showSidebar: true,
        showFooter: true
    };

    listenUpdated = new EventEmitter<any>();

    constructor(){}

    updateStatus(key: any, value: any) {
        this.data[key] = value;
        console.log('SERVICE ', this.data); // It's working...
    }
}
```

<pre class="lang-js prettyprint-override"><code>/* LoginComponent */

@Component({
    selector: 'app-login-index',
    templateUrl: './index.component.html',
    providers: [AppGlobalService]
})
export class LoginIndexComponent implements OnInit {

    private data = {};

    constructor(public globalService: AppGlobalService) {
        this.globalService.updateStatus('showHeader', false);
        this.globalService.updateStatus('showSidebar', false);
        this.globalService.updateStatus('showFooter', false);
        this.globalService.listenUpdated.emit(true);
    }

    ngOnInit() {
    }

}
</code>```

答:
I feel like a better way to do this would be to have a login component, and then lets say a home component. The Login component wouldn't include the html for a sidebar or footer or anything like that at all.

You would use routing to route to the login component when someone is not authenticated. Once they authenticate through the login component you would route to the home component where things like a footer and side bar would be present.

There is a whole guide to routing that includes login functionality. All of this is viewable in live examples from there as well.

Body:
Although I have tried many times, but not working EMIT or SUBSCRIBE.

I want to hide app-header, app-sidebar and app-footer in

LoginComponent. Also *ngIf not listening GlobalService variable.

Thanks in advance for your support.

/* App HTML */

<app-header *ngIf="global.showHeader"></app-header>

<app-sidebar *ngIf="global.showSidebar"></app-sidebar>

    <router-outlet></router-outlet>

<app-footer *ngIf="global.showFooter"></app-footer>

/* AppComponent */

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  providers: [AppGlobalService]
})
export class AppComponent implements OnInit{

  global = {};

  constructor(private globalService: AppGlobalService) {

    this.globalService.listenUpdated.subscribe(

      data => {

        this.global = data;

      }

    );
  }

  ngOnInit(){
  }
}

/* AppGlobalService */

@Injectable()
export class AppGlobalService {

    data={
        showHeader: true,
        showSidebar: true,
        showFooter: true
    };

    listenUpdated = new EventEmitter<any>();

    constructor(){}

    updateStatus(key: any, value: any) {
        this.data[key] = value;
        console.log('SERVICE ', this.data); // It's working...
    }
}

/* LoginComponent */

@Component({
    selector: 'app-login-index',
    templateUrl: './index.component.html',
    providers: [AppGlobalService]
})
export class LoginIndexComponent implements OnInit {

    private data = {};

    constructor(public globalService: AppGlobalService) {
        this.globalService.updateStatus('showHeader', false);
        this.globalService.updateStatus('showSidebar', false);
        this.globalService.updateStatus('showFooter', false);
        this.globalService.listenUpdated.emit(true);
    }

    ngOnInit() {
    }

}


问:
Python NET start a windows application
How to start a windows application like notepad using python NET ? This is my source code with python 2.7.13: </p>

```<code>C:\Python27>python.exe
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import clr
>>> import System
>>> type = System.Type.GetTypeFromProgID("Notepad.Application")
>>> System.Activator.CreateInstance(type)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
System.ArgumentNullException: Value cannot be null.
Parameter name: activationContext
   at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
   at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
   at System.Activator.CreateInstance(ActivationContext activationContext)
</code>```

答:
There is no ProgID="Notepad.Application" COM object on my machine, pythonnet works with other COM objects:</p>

```<code>>>> import clr
>>> import System
>>> type1=System.Type.GetTypeFromProgID("Excel.Application")
>>> type1
<System.RuntimeType object at 0x02ABEE10>
>>> System.Activator.CreateInstance(type1)
<Microsoft.Office.Interop.Excel.ApplicationClass object at 0x02AD11D0>
</code>```

Title: Python NET start a windows application

Body:
How to start a windows application like notepad using python NET ? This is my source code with python 2.7.13:

C:\Python27>python.exe
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import clr
>>> import System
>>> type = System.Type.GetTypeFromProgID("Notepad.Application")
>>> System.Activator.CreateInstance(type)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
System.ArgumentNullException: Value cannot be null.
Parameter name: activationContext
   at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
   at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
   at System.Activator.CreateInstance(ActivationContext activationContext)

Body:
There is no ProgID="Notepad.Application" COM object on my machine, pythonnet works with other COM objects:

>>> import clr
>>> import System
>>> type1=System.Type.GetTypeFromProgID("Excel.Application")
>>> type1
<System.RuntimeType object at 0x02ABEE10>
>>> System.Activator.CreateInstance(type1)
<Microsoft.Office.Interop.Excel.ApplicationClass object at 0x02AD11D0>


问:
Windows authentication failing on server side webapi call
I have got an MVC 5 web application hosted on IIS8 which is secured with Windows Authentication. The application has an WebApi2 controller which I am calling server side from itself via an MVC controller, however I keep getting a 401 Unauthorized when making the call (POST verb).

```<code>var client = new HttpClient();
var response = client.PostAsJsonAsync(url, dto).Result;
</code>```

Things I have tried with no success:

Setting the application pool user identity to a custom account

Enabling ASP.NET impersonation with account credentials

Editing the registry to whitelist the domain (as per this solution Unable to get windows authentication to work through local IIS)

Wondering if anyone else has any suggestions/seen this issue before?

答:
This solution worked for me when instantiating my HttpClient.</p>

```<code>            var clientHandler = new HttpClientHandler()
            {
                Credentials = CredentialCache.DefaultNetworkCredentials
            };
            var client = new HttpClient(clientHandler);
</code>```

Body:
I have got an MVC 5 web application hosted on IIS8 which is secured with Windows Authentication. The application has an WebApi2 controller which I am calling server side from itself via an MVC controller, however I keep getting a 401 Unauthorized when making the call (POST verb).

var client = new HttpClient();
var response = client.PostAsJsonAsync(url, dto).Result;

Things I have tried with no success:

Setting the application pool user identity to a custom account

Enabling ASP.NET impersonation with account credentials

Editing the registry to whitelist the domain (as per this solution Unable to get windows authentication to work through local IIS)

Wondering if anyone else has any suggestions/seen this issue before?

Body:
This solution worked for me when instantiating my HttpClient.

            var clientHandler = new HttpClientHandler()
            {
                Credentials = CredentialCache.DefaultNetworkCredentials
            };
            var client = new HttpClient(clientHandler);


问:
when I add elements to the vector<int *>, I meet some problems
here is my coding:

```<code>std::vector<int *>a;
for(i=0;i<3;i++)
{
  int j=i+1;
  int *p=&j;
  a.push_back(p);
}
for(auto &c:a)
{
  std::cout<<*c<<std::endl;
}
</code>```

I want to make the output be 1,2,3 ,but the output is 3,3,3.it seems that I have added  same pointer to a,but I want to add  different pointers to a by circulation,what should I do and how does the mistake above happen?

答:
j has automatic storage duration, and a pointer to it is only valid in that particular iteration of the for loop.

In other words, you've created a vector of dangling pointers! The behaviour on your dereferencing such a pointer is undefined.

Consider a std::vector<int> instead.

(The fact that you see the same value repeatedly in the output is probably due to the C++ runtime recreating j at the same memory location. But don't rely on that. The C++ standard does not insist on that behaviour.)

Body:
here is my coding:

std::vector<int *>a;
for(i=0;i<3;i++)
{
  int j=i+1;
  int *p=&j;
  a.push_back(p);
}
for(auto &c:a)
{
  std::cout<<*c<<std::endl;
}

I want to make the output be 1,2,3 ,but the output is 3,3,3.it seems that I have added  same pointer to a,but I want to add  different pointers to a by circulation,what should I do and how does the mistake above happen?


问:
Why isn't my background color showing up on
?
I am confused why the background color is not showing up on this code. There is padding on the "1" class but there is no color even though the color is specified. Look in the container class for the problem.

Please help.

body {
  margin: 0px;
  background-color: #fff;
}

/*
font-family: 'Lato', sans-serif;
font-family: 'Fjalla One', sans-serif;
font-family: 'Gloria Hallelujah', cursive;
*/

.welcome {
  font-family: 'Gloria Hallelujah', sans-serif;
  font-size: 45;
  text-align: center;
  color: #000;
}

.sub1 {
  font-family: 'Lato', sans-serif;
  font-size: 30;
  color: #000;
  text-indent: 20;
}

.sub2 {
  font-family: 'Lato', sans-serif;
  font-size: 25;
  color: #000;
  text-indent: 20;
}

.container {
  position: relative;
  width: 100%;
  height: 600px;
}

/*.container img {
    position: absolute;
    width: 1800px;
    background-size: cover;*/

}
@-webkit-keyframes xfade {
  0% {
    opacity: 1;
  }

  33% {
    opacity: 1;
  }

  44% {
    opacity: 0;
  }

  89% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}
@keyframes xfade {
  0% {
    opacity: 1;
  }

  33% {
    opacity: 1;
  }

  44% {
    opacity: 0;
  }

  89% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}
.container p:nth-child(3) {
  -webkit-animation: xfade 45s 0s infinite;
  animation: xfade 45s 0s infinite;
}
.container p:nth-child(2) {
  -webkit-animation: xfade 45s 15s infinite;
  animation: xfade 45s 15s infinite;
}
.container p:nth-child(1) {
  -webkit-animation: xfade 25s 30s infinite;
  animation: xfade 25s 30s infinite;
}
.container {
  position: relative;
}
.container img {
  position: absolute;
}
.1 {
  width: 100%;
  height: 100%;
  padding: 100px;
  /*background-image: url(Pictures/cupcakes.jpg)*/

  background-color: #00FFFF;
  overflow: auto;
  background-size: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
  <title>JAM Bakery</title>
  <link rel="stylesheet" type="text/css" href="home.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <link href="https://fonts.googleapis.com/css?family=Fjalla+One|Gloria+Hallelujah|Lato" rel="stylesheet">
</head>

<body>
  <br>
  <div class="content">
    <h1 class="welcome">Welcome to JAM Bakery!</h1>
    <div class="slogan">
      <h2 class="sub1">Creamy, Sweet, Toasted</h2>
      <h2 class="sub2">Your Choice.</h2>

      <div class="container">
        <p class="1">1</p>
        <p class="2"></p>
        <p class="3"></p>
      </div>

    </div>
  </div>
</body>

</html></code>```

Please check for any other problems you might see. Thank you.

答:
"1" is not a valid CSS class. CSS classes must start with a letter, hyphen, or underscore.

For more information, see this answer, or the W3C spec document.

Title: Why isn't my background color showing up on <p>?

Body:
I am confused why the background color is not showing up on this code. There is padding on the "1" class but there is no color even though the color is specified. Look in the container class for the problem.

Please help.

body {
  margin: 0px;
  background-color: #fff;
}

/*
font-family: 'Lato', sans-serif;
font-family: 'Fjalla One', sans-serif;
font-family: 'Gloria Hallelujah', cursive;
*/

.welcome {
  font-family: 'Gloria Hallelujah', sans-serif;
  font-size: 45;
  text-align: center;
  color: #000;
}

.sub1 {
  font-family: 'Lato', sans-serif;
  font-size: 30;
  color: #000;
  text-indent: 20;
}

.sub2 {
  font-family: 'Lato', sans-serif;
  font-size: 25;
  color: #000;
  text-indent: 20;
}

.container {
  position: relative;
  width: 100%;
  height: 600px;
}

/*.container img {
    position: absolute;
    width: 1800px;
    background-size: cover;*/

}
@-webkit-keyframes xfade {
  0% {
    opacity: 1;
  }

  33% {
    opacity: 1;
  }

  44% {
    opacity: 0;
  }

  89% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}
@keyframes xfade {
  0% {
    opacity: 1;
  }

  33% {
    opacity: 1;
  }

  44% {
    opacity: 0;
  }

  89% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}
.container p:nth-child(3) {
  -webkit-animation: xfade 45s 0s infinite;
  animation: xfade 45s 0s infinite;
}
.container p:nth-child(2) {
  -webkit-animation: xfade 45s 15s infinite;
  animation: xfade 45s 15s infinite;
}
.container p:nth-child(1) {
  -webkit-animation: xfade 25s 30s infinite;
  animation: xfade 25s 30s infinite;
}
.container {
  position: relative;
}
.container img {
  position: absolute;
}
.1 {
  width: 100%;
  height: 100%;
  padding: 100px;
  /*background-image: url(Pictures/cupcakes.jpg)*/

  background-color: #00FFFF;
  overflow: auto;
  background-size: cover;
}

  <title>JAM Bakery</title>
  <link rel="stylesheet" type="text/css" href="home.css">

  <link href="https://fonts.googleapis.com/css?family=Fjalla+One|Gloria+Hallelujah|Lato" rel="stylesheet">

Welcome to JAM Bakery!

Creamy, Sweet, Toasted

Your Choice.

1

Please check for any other problems you might see. Thank you.


问:
Implementation of ion-slides in ion-menu not working
I am trying to implement "sliding images" in side-menu of Ionic-3.

Following is my code :

```<code><ion-menu [content]="content">
  <ion-content>
        <ion-slides>
            <ion-slide>
                <img class="slide-image" src="img1.png">
            </ion-slide>
            <ion-slide>
                <img class="slide-image" src="img2.png">
            </ion-slide>
            <ion-slide>
                <img class="slide-image" src="img3.png">
            </ion-slide>
        </ion-slides>

        <ion-list>
          <p>some menu items</p>
        </ion-list>
  </ion-content>
</ion-menu>

<ion-nav [root]="rootPage" #content></ion-nav>
</code>```

The elements are rendering properly but the problem is that the <ion-slide> is behaving like horizontal scroll view in side menu.

I have tried to disable the swipe gesture of side-menu but still the behavior of <ion-slide> persist.

Even I have tried to use slideNext and slidePrev method of Slides but they are not working.

Is there any way I can implement the sliding-images in side-menu either using Ionic-3 or third party library?

答:
Verifying the ion-slides in the menu, the behaviour of these is normal in the sidemenu. Take a look in this link. these slides are only slides with a backgrounds of different colors.

the implementation is in the part of:

```<code> @App({
  template: `
    <ion-menu [content]="content">

      <ion-toolbar>
        <ion-title>Pages</ion-title>
      </ion-toolbar>

      <ion-content>
        <ion-slides pager>

          <ion-slide style="background-color: green">
            <h2>Slide 1</h2>
          </ion-slide>

          <ion-slide style="background-color: blue">
            <h2>Slide 2</h2>
          </ion-slide>

          <ion-slide style="background-color: red">
            <h2>Slide 3</h2>
          </ion-slide>

        </ion-slides>
      </ion-content>

    </ion-menu>

    <ion-nav id="nav" [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>

  `
})
</code>```

Body:
I am trying to implement "sliding images" in side-menu of Ionic-3.

Following is my code :

<ion-menu [content]="content">
  <ion-content>
        <ion-slides>
            <ion-slide>

            </ion-slide>
            <ion-slide>

            </ion-slide>
            <ion-slide>

            </ion-slide>
        </ion-slides>

        <ion-list>

some menu items

        </ion-list>
  </ion-content>
</ion-menu>

<ion-nav [root]="rootPage" #content></ion-nav>

The elements are rendering properly but the problem is that the <ion-slide> is behaving like horizontal scroll view in side menu.

I have tried to disable the swipe gesture of side-menu but still the behavior of <ion-slide> persist.

Even I have tried to use slideNext and slidePrev method of Slides but they are not working.

Is there any way I can implement the sliding-images in side-menu either using Ionic-3 or third party library?

Body:
Verifying the ion-slides in the menu, the behaviour of these is normal in the sidemenu. Take a look in this link. these slides are only slides with a backgrounds of different colors.

the implementation is in the part of:

 @App({
  template: `
    <ion-menu [content]="content">

      <ion-toolbar>
        <ion-title>Pages</ion-title>
      </ion-toolbar>

      <ion-content>
        <ion-slides pager>

          <ion-slide style="background-color: green">
            <h2>Slide 1</h2>
          </ion-slide>

          <ion-slide style="background-color: blue">
            <h2>Slide 2</h2>
          </ion-slide>

          <ion-slide style="background-color: red">
            <h2>Slide 3</h2>
          </ion-slide>

        </ion-slides>
      </ion-content>

    </ion-menu>

    <ion-nav id="nav" [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>

  `
})


问:
Is @$array['possibly_missing_key'] an anti-pattern?
Is it OK to use @ when extracting a possibly missing value from a PHP array? Example:

```<code>$value = @$array['possibly_missing_key'];
</code>```

The intended behavior:

```<code>if (isset($array['possibly_missing_key'])) {
    $value = $array['possibly_missing_key'];
} else {
    $value = null;
}
</code>```

I want to know, before spreading the usage pattern.

答:
Actually the isset variation is the anti-pattern. If you just use isset($var)?$var:NULL with the intention to suppress the "error", then you've achieved nothing over using the proper syntax for suppressing errors. It has the same outcome, yet is less readable.

People are arguing for that because of perceived "cleanliness" and because using isset is a micro optimization. Avoiding @ and using isset as syntactic salt replacement is just  cargo cult programming.

ContentLicense: CC BY-SA 2.5

Body:
Is it OK to use @ when extracting a possibly missing value from a PHP array? Example:

$value = @$array['possibly_missing_key'];

The intended behavior:

if (isset($array['possibly_missing_key'])) {
    $value = $array['possibly_missing_key'];
} else {
    $value = null;
}

I want to know, before spreading the usage pattern.


问:
Using firebase to get multiple individual values given an array of keys
I'm trying to access multiple individual keys in Firebase. I'm using a promise-based function and a for loop to iterate over the given keys.

Here's the code:

```<code>function getFirebaseData(key_arr)
{
   var ref_obj,
       data_obj = {};
   return new Promise(function(resolve)
   {
       for(var i = 0; i < key_arr.length; i++)
       {
           key_str = key_arr[i];
           ref_obj = firebase.database().ref('path/'+key_str);
           ref_obj.on('value', function(snapshot)
           {
               data_obj[key_str] = snapshot.val();
           });
        }
        resolve(data_obj);
   });
}
</code>```

And then I run this as follows:

```<code>var key_arr = ['first_key', 'second_key', 'third_key'];
getFirebaseData(key_arr).then(function(result){console.log(result);});
</code>```

The problem is that the result I get isn't all three keys; I only get one. I guess this is because the code inside the for loop is asynchronous, so resolve only gives me the first key.

How can I rewrite this in such a way that I can wait for the for loop to complete and return the full result.

答:
This minor variation on Jaromanda's well-crafted answer makes use of the key property of a DataSnapshot (all credit to him for the design):</p>

```<code>function getFirebaseData(key_arr) {
  return Promise.all(key_arr.map(key_str =>
    firebase.database().ref('path/'+key_str).once('value'))
  ).then(snapshots =>
    snapshots.reduce((result, snap) => {
      result[snap.key] = snap.val();
      return result;
    }, [])
  );
}
</code>```

Body:
I'm trying to access multiple individual keys in Firebase. I'm using a promise-based function and a for loop to iterate over the given keys.

Here's the code:

function getFirebaseData(key_arr)
{
   var ref_obj,
       data_obj = {};
   return new Promise(function(resolve)
   {
       for(var i = 0; i < key_arr.length; i++)
       {
           key_str = key_arr[i];
           ref_obj = firebase.database().ref('path/'+key_str);
           ref_obj.on('value', function(snapshot)
           {
               data_obj[key_str] = snapshot.val();
           });
        }
        resolve(data_obj);
   });
}

And then I run this as follows:

var key_arr = ['first_key', 'second_key', 'third_key'];
getFirebaseData(key_arr).then(function(result){console.log(result);});

The problem is that the result I get isn't all three keys; I only get one. I guess this is because the code inside the for loop is asynchronous, so resolve only gives me the first key.

How can I rewrite this in such a way that I can wait for the for loop to complete and return the full result.

Body:
This minor variation on Jaromanda's well-crafted answer makes use of the key property of a DataSnapshot (all credit to him for the design):

function getFirebaseData(key_arr) {
  return Promise.all(key_arr.map(key_str =>
    firebase.database().ref('path/'+key_str).once('value'))
  ).then(snapshots =>
    snapshots.reduce((result, snap) => {
      result[snap.key] = snap.val();
      return result;
    }, [])
  );
}


问:
Parallax scrolling not working on mobile css
My parallax scrolling is not working on mobile devices, both android and iOS. The code works great for desktop but not for mobile, be it any browser. Background images are not scrolling in parallax effect. You can check it here https://dkpyk75z6sfdo.cloudfront.net/

Here goes the CSS code,

```<code>.home {
background: url(assets/images/img1.jpg) no-repeat center center fixed;
display: table;
height: 100%;
position: relative;
width: 100%;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#information {
background: url(assets/images/b1.jpeg) no-repeat center center fixed;
display: table;
height: 100%;
z-index: -1;
position: relative;
width: 100%;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#information2 {
background: url(assets/images/ab9.jpeg) no-repeat center center fixed;
display: table;
height: 100%;
z-index: -1;
position: relative;
width: 100%;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#information3 {
background: url(assets/images/c4.jpg) no-repeat center center fixed;
display: table;
height: 100%;
z-index: -1;
position: relative;
width: 100%;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
</code>```

HTML code

```<code><!-- first section - Home -->
<div class="home">
<div class="centered">
<h1>PARALLAX WEB DESIGN</h1>
</div>
</div>
<!-- /first section -->

<!-- second section -->
<div id="information">
<div class="centered">
        <h1>SECTION 1</h1>
</div>
</div>
<!-- /second section -->
</code>```

And so on

答:
Parallax will never work properly on mobile devices - and here is why.

Mobile browsers are designed to function as efficiently as possible in order to save on battery life. One way that they do that is that they delay JS execution during a scroll event. Symptomatically this will display as the parallax not parallaxing but rather jumping to its new position after scroll completes.

I recommend disabling all parallax once down to mobile viewport.

Further reading on this topic: http://developer.telerik.com/featured/scroll-event-change-ios-8-big-deal/

Body:
My parallax scrolling is not working on mobile devices, both android and iOS. The code works great for desktop but not for mobile, be it any browser. Background images are not scrolling in parallax effect. You can check it here https://dkpyk75z6sfdo.cloudfront.net/

Here goes the CSS code,

.home {
background: url(assets/images/img1.jpg) no-repeat center center fixed;
display: table;
height: 100%;
position: relative;
width: 100%;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#information {
background: url(assets/images/b1.jpeg) no-repeat center center fixed;
display: table;
height: 100%;
z-index: -1;
position: relative;
width: 100%;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#information2 {
background: url(assets/images/ab9.jpeg) no-repeat center center fixed;
display: table;
height: 100%;
z-index: -1;
position: relative;
width: 100%;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#information3 {
background: url(assets/images/c4.jpg) no-repeat center center fixed;
display: table;
height: 100%;
z-index: -1;
position: relative;
width: 100%;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}

HTML code

PARALLAX WEB DESIGN

SECTION 1

And so on