问:
Android: camera.setParameter question
When implementing SurfaceHolder.Callback, some online tutorials suggest (actually, I found this is what Google wrote in API demo)

```<code>    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        Parameters params = camera.getParameters();
        params.setPreviewSize(width, height);
        camera.setParameters(params);
        camera.startPreview();
    }
</code>```

However, this is not practical. As on real device, code like this would likely raise an exception on camera.setParameter(params), as the height and width specified isn't likely supported by the device.

After reading some Q&As on stackoverflow, I understood why that wasn't right. Those posts said I should find one that suits best for the screen. I then decided to print a table of the dimensions my phone (HTC Magic, android 2.1) supports, using params.getSupportedPreviewSizes();. Got these, regardless of the phone's orientation.

```<code> h:720  , w:1280
 h:480  , w:800
 h:480  , w:720
 h:480  , w:640
 h:432  , w:576
 h:320  , w:480
 h:240  , w:400
 h:288  , w:384
 h:288  , w:352
 h:240  , w:320
 h:272  , w:272
 h:240  , w:240
 h:160  , w:240
 h:144  , w:176
</code>```

After all, I don't have any clue on how to find the most suitable dimension for the screen. And I'm now very confused on what the correct program is. I think this program should be quite common and I don't have to come up with one myself.

Can anyone help me and post a well-written public void surfaceChanged sample here?

Thank you!

答: All I know is that width and height of which is being passed as argument to the callback is of SurfaceHolder calculated at runtime. So you are unlikely to get the exception.</p>

Title: Android: camera.setParameter question

Body:
When implementing SurfaceHolder.Callback, some online tutorials suggest (actually, I found this is what Google wrote in API demo)

    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        Parameters params = camera.getParameters();
        params.setPreviewSize(width, height);
        camera.setParameters(params);
        camera.startPreview();
    }

However, this is not practical. As on real device, code like this would likely raise an exception on camera.setParameter(params), as the height and width specified isn't likely supported by the device.

After reading some Q&As on stackoverflow, I understood why that wasn't right. Those posts said I should find one that suits best for the screen. I then decided to print a table of the dimensions my phone (HTC Magic, android 2.1) supports, using params.getSupportedPreviewSizes();. Got these, regardless of the phone's orientation.

 h:720  , w:1280
 h:480  , w:800
 h:480  , w:720
 h:480  , w:640
 h:432  , w:576
 h:320  , w:480
 h:240  , w:400
 h:288  , w:384
 h:288  , w:352
 h:240  , w:320
 h:272  , w:272
 h:240  , w:240
 h:160  , w:240
 h:144  , w:176

After all, I don't have any clue on how to find the most suitable dimension for the screen. And I'm now very confused on what the correct program is. I think this program should be quite common and I don't have to come up with one myself.

Can anyone help me and post a well-written public void surfaceChanged sample here?

Thank you!


来源: stackexchange

问:
Json String array into Java String list
I have a webservice that returns a list of strings, only a list of strings:

```<code>["string1","string2","string3"]
</code>```

How can I convert this into an ArrayList<String> in java? I'm trying to use jackson as I know you can convert Json to objects with it, but I can't find an example of a case like this.

答:
It's weird, but there is a direct transformation from new JSONArray(stringWithJSONArray) into List.
At least I was able to do like this:</p>

```<code>public List<String> method(String data) {
    return new JSONArray(data);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Json String array into Java String list

Body:
I have a webservice that returns a list of strings, only a list of strings:

["string1","string2","string3"]

How can I convert this into an ArrayList<String> in java? I'm trying to use jackson as I know you can convert Json to objects with it, but I can't find an example of a case like this.

Body:
It's weird, but there is a direct transformation from new JSONArray(stringWithJSONArray) into List.
At least I was able to do like this:

public List<String> method(String data) {
    return new JSONArray(data);
}


问:
Spark job writing to parquet - has a container with physical memory that keeps increasing
I have a spark streaming application that reads from kafka topic and writes the data to hdfs in parquet format.
I see that during time(very short time) the physical memory of the container keeps growing until it reaches the maximum size and fails on
"Diagnostics: Container [pid=29328,containerID=container_e42_1512395822750_0026_02_000001] is running beyond physical memory limits. Current usage: 1.5 GB of 1.5 GB physical memory used; 2.3 GB of 3.1 GB virtual memory used. Killing container."
The container that is being killed is the same that runs the driver so the application is also being killed.
When looking for this error I only saw solutions of increasing the memory but this I think will only postpone the problem.
I want to understand why is the memory keeps increasing if I don't save anything in memory.
I also saw that all containers have increases in memory but they are just being killed after a while(before reaching the maximum).
I saw in some post "Your job is writing out Parquet data, and Parquet buffers data in memory prior to writing it out to disk".

The code we are using (we also tried without the repartition - not sure that is needed):

```<code>val repartition = rdd.repartition(6)
val df: DataFrame = sqlContext.read.json(repartition)
df.write.mode(SaveMode.Append).parquet(dbLocation)
</code>```

Is there some way to just fix the increasing memory problem ?

The created parquet files

The nodeManager logs that show the increase in the memory

答:
Assuming your application does nothing other than just writes, I suspect the root cause to be size of data being received in batches. It's possible that data received in one of the batches is beyond the thresholds configured. Assuming the application is killed for this season, the solution is to enable "back pressure".
The solution is detailed enough in the post below.

Limit Kafka batches size when using Spark Streaming

Body:
I have a spark streaming application that reads from kafka topic and writes the data to hdfs in parquet format.
I see that during time(very short time) the physical memory of the container keeps growing until it reaches the maximum size and fails on
"Diagnostics: Container [pid=29328,containerID=container_e42_1512395822750_0026_02_000001] is running beyond physical memory limits. Current usage: 1.5 GB of 1.5 GB physical memory used; 2.3 GB of 3.1 GB virtual memory used. Killing container."
The container that is being killed is the same that runs the driver so the application is also being killed.
When looking for this error I only saw solutions of increasing the memory but this I think will only postpone the problem.
I want to understand why is the memory keeps increasing if I don't save anything in memory.
I also saw that all containers have increases in memory but they are just being killed after a while(before reaching the maximum).
I saw in some post "Your job is writing out Parquet data, and Parquet buffers data in memory prior to writing it out to disk".

The code we are using (we also tried without the repartition - not sure that is needed):

val repartition = rdd.repartition(6)
val df: DataFrame = sqlContext.read.json(repartition)
df.write.mode(SaveMode.Append).parquet(dbLocation)

Is there some way to just fix the increasing memory problem ?

The created parquet files

The nodeManager logs that show the increase in the memory


问:
[stack][list]I can't understand my mistake
Help please, I can't understand where is mistake, after compilation, program has nothing to show. Need to create 2 stacks, one of them will contain random numbers, the other will contain only those numbers from first stack, which greater than average of all numbers in first stack</p>

```<code>#include "stdafx.h"
#include <iostream>
#include <ctime>

using namespace std;

struct stack //our stack
{
    int num;
    stack* ptr = NULL;
};

void addtostack(int &n, stack* p) //add element to stack
{
    stack* newstack = new stack;
    newstack->num = n;
    newstack->ptr = p;
    p = newstack;
}

void showstack(stack* p) //show stack
{
    stack* current = p;
    while (current->ptr)
    {
        cout << current->num << endl;
        current = current->ptr;
    }
}

int main()
{
    srand(time(NULL));
    const int SIZE = 5;
    stack* first = new stack;
    int rnd;
    double average = 0;
    for (int i = 0; i < SIZE; i++)
    {
        rnd = -50 + rand() % 101;
        addtostack(rnd, first);
        average += rnd;
    }
    average /= SIZE;
    showstack(first);
    system("pause > nul");
}
</code>```

答:
The line

```<code>p = newstack;
</code>```

does not do what you hope it will do.

It changes a local copy of the variable p. The pointer in main still points to the only object that it was initialized with.

You can solve it couple of ways:

Pass p by reference. You don't need to pass n by reference though.

```<code>void addtostack(int n, stack*& p) //add element to stack
{
    stack* newstack = new stack;
    newstack->num = n;
    newstack->ptr = p;
    p = newstack;
}
</code>```

Return the new pointer to the calling function.

```<code>stack* addtostack(int n, stack* p) //add element to stack
{
    stack* newstack = new stack;
    newstack->num = n;
    newstack->ptr = p;
    return newstack;
}
</code>```

and then change main to:

```<code>for (int i = 0; i < SIZE; i++)
{
    rnd = -50 + rand() % 101;
    first = addtostack(rnd, first);
    average += rnd;
}
</code>```

Body:
Help please, I can't understand where is mistake, after compilation, program has nothing to show. Need to create 2 stacks, one of them will contain random numbers, the other will contain only those numbers from first stack, which greater than average of all numbers in first stack

#include "stdafx.h"
#include <iostream>
#include <ctime>

using namespace std;

struct stack //our stack
{
    int num;
    stack* ptr = NULL;
};

void addtostack(int &n, stack* p) //add element to stack
{
    stack* newstack = new stack;
    newstack->num = n;
    newstack->ptr = p;
    p = newstack;
}

void showstack(stack* p) //show stack
{
    stack* current = p;
    while (current->ptr)
    {
        cout << current->num << endl;
        current = current->ptr;
    }
}

int main()
{
    srand(time(NULL));
    const int SIZE = 5;
    stack* first = new stack;
    int rnd;
    double average = 0;
    for (int i = 0; i < SIZE; i++)
    {
        rnd = -50 + rand() % 101;
        addtostack(rnd, first);
        average += rnd;
    }
    average /= SIZE;
    showstack(first);
    system("pause > nul");
}

Body:
The line

p = newstack;

does not do what you hope it will do.

It changes a local copy of the variable p. The pointer in main still points to the only object that it was initialized with.

You can solve it couple of ways:

Pass p by reference. You don't need to pass n by reference though.

void addtostack(int n, stack*& p) //add element to stack
{
    stack* newstack = new stack;
    newstack->num = n;
    newstack->ptr = p;
    p = newstack;
}

Return the new pointer to the calling function.

stack* addtostack(int n, stack* p) //add element to stack
{
    stack* newstack = new stack;
    newstack->num = n;
    newstack->ptr = p;
    return newstack;
}

and then change main to:

for (int i = 0; i < SIZE; i++)
{
    rnd = -50 + rand() % 101;
    first = addtostack(rnd, first);
    average += rnd;
}


问:
I was given an OOP project using SDL. I haven't used inheritance. What reason can i give to my evaluators
I took a course OOP. We were supposed to create a game in a group of 3. I worked on the menu part. Unfortunately, i didnt use inheritance and other OOP concepts. I DID use classes. What is the possible reason that i can give to me evaluators without having my marks deducted? My viva is tomorrow. (after 13 hours)
Thanks.</p>

答:
It is a bit difficult to guess what you can say without knowing anything about your design (i.e. how the classes cooperate between each other), and there are a lot of "OOP concepts out there".

The only thing I can suggest you, assuming that you didn't declare every function of the other classes static, is to say that you did not use inheritance because composition is often (but not always) better. You have a composition if one member of you class is a class itself:

```<code>class Player
{
  private:
     Weapon gun;
  public:
     Player(Weapon& pistol);
     void shoot(){gun.bang();}
};
</code>```

Gun is a composition: Player uses a Gun to shoot() and it is a perfectly legit use of a composition here. This is a case when you DON'T want to use a composition:

```<code>class MedievalFolk
{
  private:
     Knight arthur;
  public:
     Player(Knight& pistol);
     void duel(){arthur.duel();}
};
</code>```

If you did something like this be prepared to be turned down, because there is no difference between a Knight and a MedievalFolk and you will need a better reason than "composition is better" here since this argument won't hold. Also, if you declared everything static then the only thing I can advise you is to rework your code not to do so. You would have just a glorification of old-fashioned procedural code (regardless of using classes) where everything is a function which calls other functions and, if I would be teaching a course on OOP, I would fail this coursework

I don't know what you are studying OOP for, but if you plan to get into software development I would strongly advise you to defer the examination and do your coursework properly, you won't be able to fix it all in a few hours not even professional can ressurect bad code in few days of work. Also there isn't a single employer that wish to hire a developer which is not proficient in OOP those days, unless you plan to work on ancient stuff of the 70s (and probably it still won't be sufficient). There is nothing wrong with taking a bit longer time if this makes you better

Body:
It is a bit difficult to guess what you can say without knowing anything about your design (i.e. how the classes cooperate between each other), and there are a lot of "OOP concepts out there".

The only thing I can suggest you, assuming that you didn't declare every function of the other classes static, is to say that you did not use inheritance because composition is often (but not always) better. You have a composition if one member of you class is a class itself:

class Player
{
  private:
     Weapon gun;
  public:
     Player(Weapon& pistol);
     void shoot(){gun.bang();}
};

Gun is a composition: Player uses a Gun to shoot() and it is a perfectly legit use of a composition here. This is a case when you DON'T want to use a composition:

class MedievalFolk
{
  private:
     Knight arthur;
  public:
     Player(Knight& pistol);
     void duel(){arthur.duel();}
};

If you did something like this be prepared to be turned down, because there is no difference between a Knight and a MedievalFolk and you will need a better reason than "composition is better" here since this argument won't hold. Also, if you declared everything static then the only thing I can advise you is to rework your code not to do so. You would have just a glorification of old-fashioned procedural code (regardless of using classes) where everything is a function which calls other functions and, if I would be teaching a course on OOP, I would fail this coursework

I don't know what you are studying OOP for, but if you plan to get into software development I would strongly advise you to defer the examination and do your coursework properly, you won't be able to fix it all in a few hours not even professional can ressurect bad code in few days of work. Also there isn't a single employer that wish to hire a developer which is not proficient in OOP those days, unless you plan to work on ancient stuff of the 70s (and probably it still won't be sufficient). There is nothing wrong with taking a bit longer time if this makes you better


问:
Create a constant variable link to year and quarter
Hi i am a stata user and i am trying to pass my codes to R. I have a panel data as shown below, and i am looking for a command that can create a constant variable according to which year and quarter the row is located. In stata such command would be reproduced by gen new_variable = yq(year, quarter)

My dataframe look like this

```<code>id     year    quarter
 1    2007          1
 1    2007          2
 1    2007          3
 1    2007          4
 1    2008          1
 1    2008          2
 1    2008          3
 1    2008          4
 1    2009          1
 1    2009          2
 1    2009          3
 1    2009          4
 2    2007          1
 2    2007          2
 2    2007          3
 2    2007          4
 2    2008          1
 2    2008          2
 2    2008          3
 2    2008          4
 3    2009          2
 3    2009          3
 3    2010          2
 3    2010          3
</code>```

I my expected output should look like this: (Values inside new_variable are arbitrary, just looking for a constant value the would be always the same for each year and quarter)

```<code>id     year    quarter   new_variable
 1    2007          1     220
 1    2007          2     221
 1    2007          3     222
 1    2007          4     223
 1    2008          1     224
 1    2008          2     225
 1    2008          3     226
 1    2008          4     227
 1    2009          1     228
 1    2009          2     229
 1    2009          3     230
 1    2009          4     231
 2    2007          1     220
 2    2007          2     221
 2    2007          3     222
 2    2007          4     223
 2    2008          1     224
 2    2008          2     225
 2    2008          3     226
 2    2008          4     227
 3    2009          2     229
 3    2009          3     230
 3    2010          2     233
 3    2010          3     234
</code>```

答:
1) yearqtr The yearqtr class in the zoo package does this.   yearqtr objects have a type of double with the value year + 0 for Q1, year + 1/4 for Q2, etc. When displayed they are shown in a meaningful way; however, they can still be manipulated as if they were plain numbers, e.g. if yq is yearqtr variable then yq + 1 is the same quarter in the next year.

```<code>library(zoo)

transform(df, new_variable = as.yearqtr(year + (quarter - 1)/4))
</code>```

1a) or

```<code>transform(df, new_variable = as.yearqtr(paste(year, quarter, sep = "-")))
</code>```

Either of these give:

```<code>   id year quarter new_variable
1   1 2007       1      2007 Q1
2   1 2007       2      2007 Q2
3   1 2007       3      2007 Q3
4   1 2007       4      2007 Q4
5   1 2008       1      2008 Q1
... etc ...
</code>```

2) 220 If you specifically wanted to assign 220 to the first date and have each subsequent quarter increment by 1 then:

```<code>transform(df, new_variable = as.numeric(factor(4 * year + quarter)) + 220 - 1)
</code>```

Body:
Hi i am a stata user and i am trying to pass my codes to R. I have a panel data as shown below, and i am looking for a command that can create a constant variable according to which year and quarter the row is located. In stata such command would be reproduced by gen new_variable = yq(year, quarter)

My dataframe look like this

id     year    quarter
 1    2007          1
 1    2007          2
 1    2007          3
 1    2007          4
 1    2008          1
 1    2008          2
 1    2008          3
 1    2008          4
 1    2009          1
 1    2009          2
 1    2009          3
 1    2009          4
 2    2007          1
 2    2007          2
 2    2007          3
 2    2007          4
 2    2008          1
 2    2008          2
 2    2008          3
 2    2008          4
 3    2009          2
 3    2009          3
 3    2010          2
 3    2010          3

I my expected output should look like this: (Values inside new_variable are arbitrary, just looking for a constant value the would be always the same for each year and quarter)

id     year    quarter   new_variable
 1    2007          1     220
 1    2007          2     221
 1    2007          3     222
 1    2007          4     223
 1    2008          1     224
 1    2008          2     225
 1    2008          3     226
 1    2008          4     227
 1    2009          1     228
 1    2009          2     229
 1    2009          3     230
 1    2009          4     231
 2    2007          1     220
 2    2007          2     221
 2    2007          3     222
 2    2007          4     223
 2    2008          1     224
 2    2008          2     225
 2    2008          3     226
 2    2008          4     227
 3    2009          2     229
 3    2009          3     230
 3    2010          2     233
 3    2010          3     234

Body:
1) yearqtr The yearqtr class in the zoo package does this.   yearqtr objects have a type of double with the value year + 0 for Q1, year + 1/4 for Q2, etc. When displayed they are shown in a meaningful way; however, they can still be manipulated as if they were plain numbers, e.g. if yq is yearqtr variable then yq + 1 is the same quarter in the next year.

library(zoo)

transform(df, new_variable = as.yearqtr(year + (quarter - 1)/4))

1a) or

transform(df, new_variable = as.yearqtr(paste(year, quarter, sep = "-")))

Either of these give:

   id year quarter new_variable
1   1 2007       1      2007 Q1
2   1 2007       2      2007 Q2
3   1 2007       3      2007 Q3
4   1 2007       4      2007 Q4
5   1 2008       1      2008 Q1
... etc ...

2) 220 If you specifically wanted to assign 220 to the first date and have each subsequent quarter increment by 1 then:

transform(df, new_variable = as.numeric(factor(4 * year + quarter)) + 220 - 1)


问:
How do I pad an IP address' octets and turn it into a unique int id in an Ansible playbook?
Given an IP address like 127.0.0.1 (as a string), I want to drop the dots, pad each octet (ideally except for the first one) with zeros to a length of three digits and turn the result into an integer, e.g. 127000000001. (Although I'm assuming that leading zeros would be dropped when converting from string to integer anyway.)

How do I go about doing that in Ansible?
I have the ip defined as ip: "127.0.0.1"

The octets can be obtained with octets: "{{ ip.split('.')}}"

I have found a post that shows how to format strings: {{'%03d'|format(item|int) }}

And I can join a list to a string using result: modified_octets.join()

What I'm struggling with is how to bring all that together. I know I can loop over the octets with an with_items: octets, and could thus apply the format to each item. But how would I join the result together into a list of items (i.e. modified_octets) again? (If I assign item to a variable using the register module, I'll only get the last octet's value; previous ones will be overridden by it...)

Update: It's not important whether I get a string or an int back, really, as long as the return value looks like an integer (i.e. no leading zeroes, no dots, numbers only, etc.)

答:
You can use the replace filter to replace the dots with zeros.  The int filter will cast the string to an integer.

```<code>result: "{{ ip | replace('.', '00') | int }}"
</code>```

Body:
You can use the replace filter to replace the dots with zeros.  The int filter will cast the string to an integer.

result: "{{ ip | replace('.', '00') | int }}"


问:
Is it possible to revert file open behavior of SSMS 16.* to the SSMS 2012 behavior?
SSMS 2012 used to open a script from shell integration in a new tab, re-using the session to the currently selected DB in the explorer, or the current tab's session.

The new version opens an entire new instance where I have to make a new connection to the DB.

Is it possible, through a registry hack or other means, to revert this behavior to what SSMS 2012 used to do?

答: SSMS 17.3 reverted that behavior - upgraded and it's fine now.</p>


问:
what does `'CreateNote'`represent in this section?
Referring to this link https://learn.microsoft.com/en-us/bot-framework/nodejs/bot-builder-nodejs-recognize-intent-luis

I took this code section :

```<code>// CreateNote dialog
bot.dialog('CreateNote', [
    function (session, args, next) {
        // Resolve and store any Note.Title entity passed from LUIS.
        var intent = args.intent;
        var title = builder.EntityRecognizer.findEntity(intent.entities, 'Note.Title');

        var note = session.dialogData.note = {
          title: title ? title.entity : null,
        };
</code>```

What i don't understand is what does 'CreateNote'represent in this section?

And referring to this line :

```<code>var title = builder.EntityRecognizer.findEntity(intent.entities, 'Note.Title');
</code>```

Assuming my intent name is calendar.add and my entity name calendar.location
will the intent.entities calendar.add.calendar.location create any confusion.

答:
That's the internal identifier of the dialog, and can be referenced where necessary.

Regarding the second part, I don't think it will create confusion, but if you'll get back to this code two weeks later, you will scratch your head thinking why is it named that way, so it's more of a logistics kind of thing, in my opinion.

Body:
Referring to this link https://learn.microsoft.com/en-us/bot-framework/nodejs/bot-builder-nodejs-recognize-intent-luis

I took this code section :

// CreateNote dialog
bot.dialog('CreateNote', [
    function (session, args, next) {
        // Resolve and store any Note.Title entity passed from LUIS.
        var intent = args.intent;
        var title = builder.EntityRecognizer.findEntity(intent.entities, 'Note.Title');

        var note = session.dialogData.note = {
          title: title ? title.entity : null,
        };

What i don't understand is what does 'CreateNote'represent in this section?

And referring to this line :

var title = builder.EntityRecognizer.findEntity(intent.entities, 'Note.Title');

Assuming my intent name is calendar.add and my entity name calendar.location
will the intent.entities calendar.add.calendar.location create any confusion.


问:
INNER JOIN SQL ORDER BY NOT WORKING
WORKING!

```<code>SELECT s.*, COUNT(rs.id_segreto) as tot
FROM Segreti s INNER JOIN
     Reazioni_Segreti rs
     ON s.id = rs.id_segreto
WHERE rs.tipo_reazione = 'mi_piace'
GROUP BY s.id
ORDER BY tot DESC
LIMIT 10;
</code>```

But it print me only 1 row.

```<code>$rs_result = mysql_query($sql);
while ($row = mysql_fetch_array($rs_result, MYSQL_ASSOC)) {
echo $row['id']."<br>";
}
</code>```

Why happened? What i wrong?

答:
This is a syntax that MySQL allows, but the SQL standard does not -- nor do other databases.  You have a multitude of ungrouped fields in theSELECT, but the COUNT() turns this into an aggregation query.

With no group by, such a query always returns exactly one row.

I would also recommend using table aliases:

```<code>SELECT s.*, COUNT(rs.id_segreto) as tot
FROM Segreti s INNER JOIN
     Reazioni_Segreti rs
     ON s.id = rs.id_segreto
WHERE rs.tipo_reazione = 'mi_piace'
GROUP BY s.id
ORDER BY tot DESC
LIMIT 10;
</code>```

Note that the use of s.id (rather than listing all the columns) in the GROUP BY is allowed -- even under ANSI -- assuming that id is defined to be unique in the table.

Title: INNER JOIN SQL ORDER BY NOT WORKING

Body:
WORKING!

SELECT s.*, COUNT(rs.id_segreto) as tot
FROM Segreti s INNER JOIN
     Reazioni_Segreti rs
     ON s.id = rs.id_segreto
WHERE rs.tipo_reazione = 'mi_piace'
GROUP BY s.id
ORDER BY tot DESC
LIMIT 10;

But it print me only 1 row.

$rs_result = mysql_query($sql);
while ($row = mysql_fetch_array($rs_result, MYSQL_ASSOC)) {
echo $row['id']."
";
}

Why happened? What i wrong?

Body:
This is a syntax that MySQL allows, but the SQL standard does not -- nor do other databases.  You have a multitude of ungrouped fields in theSELECT, but the COUNT() turns this into an aggregation query.

With no group by, such a query always returns exactly one row.

I would also recommend using table aliases:

SELECT s.*, COUNT(rs.id_segreto) as tot
FROM Segreti s INNER JOIN
     Reazioni_Segreti rs
     ON s.id = rs.id_segreto
WHERE rs.tipo_reazione = 'mi_piace'
GROUP BY s.id
ORDER BY tot DESC
LIMIT 10;

Note that the use of s.id (rather than listing all the columns) in the GROUP BY is allowed -- even under ANSI -- assuming that id is defined to be unique in the table.


问:
Restoring the model in tensorflow, Attempting to use uninitialized value Variable Error message
I have trained my model and saved it with using

```<code>    saver = tf.train.Saver()
    saver.save(sess, '/final_model', global_step = i)
</code>```

Then I rebuild the exact same graph and try to restore the model to reproduce my result, restoring is working but as long as try to access to any value of the network parameters or operations, it gives me an error saying trying to use the uninitialized variable.

After rebuilding the graph, the code I use to restore is:

```<code>    sess=tf.Session()
    new_saver = tf.train.import_meta_graph('final_model-699.meta')
    new_saver.restore(sess, tf.train.latest_checkpoint('./'))
</code>```

However, the following any of them give me an error of attempting to use uninitialized variable

```<code>    print(sess.run(weights['hidden1']))
    print(sess.run(loss_f, feed_dict={x: train_x, y_: train_y}))
</code>```

Any idea?

As a simple example, here is the training and saving the model:

```<code>train_x = np.random.rand(200,2)
w= np.array([2,3])
train_y = np.dot(train_x, w)
train_y = np.reshape(train_y, [200,1])
feature_dim = 2
output_dim = 1

x = tf.placeholder(tf.float32, [None, feature_dim])
y_ = tf.placeholder(tf.float32, [None, output_dim])
weights = {
    'hidden1': tf.Variable(tf.random_normal([feature_dim, output_dim], stddev=1 / np.sqrt(feature_dim)))
}

def network1(data):
    output = tf.matmul(x, weights['hidden1'])
    return output
y = network1(x)

loss_f = output_dim * tf.reduce_mean(tf.squared_difference(y, y_))
optimizer_f = tf.train.AdamOptimizer(1e-4).minimize(loss_f)
saver = tf.train.Saver()
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for i in range(10000):
    batch_x = train_x
    batch_y = train_y
    sess.run(optimizer_f, feed_dict={x: batch_x, y_: batch_y})
    print(sess.run(loss_f, feed_dict={x: batch_x, y_: batch_y}))
saver.save(sess,'./savedmodel/', global_step = i)
</code>```

Restoring and reproducing the result

```<code>import scipy.io
import numpy as np
import tensorflow as tf
import random
train_x = np.random.rand(200,2)
w= np.array([2,3])
train_y = np.dot(train_x, w)
train_y = np.reshape(train_y, [200,1])
feature_dim = 2
output_dim = 1
x = tf.placeholder(tf.float32, [None, feature_dim])
y_ = tf.placeholder(tf.float32, [None, output_dim])

weights = {
    'hidden1': tf.Variable(tf.random_normal([feature_dim, output_dim], stddev=1 / np.sqrt(feature_dim)))
}

def network1(data):
    output = tf.matmul(x, weights['hidden1'])
    return output

y = network1(x)
loss_f = tf.reduce_mean(tf.squared_difference(y, y_))
optimizer_f = tf.train.AdamOptimizer(1e-4).minimize(loss_f)
sess = tf.Session()
saver = tf.train.import_meta_graph('./savedmodel/-9999.meta')
saver.restore(sess, tf.train.latest_checkpoint('./savedmodel/'))

print(sess.run(loss_f, feed_dict={x: train_x, y_: train_y}))
</code>```

The error:

```<code>FailedPreconditionErrorTraceback (most recent call last)
<ipython-input-5-17910473afab> in <module>()
----> 1 print(sess.run(loss_f, feed_dict={x: train_x, y_: train_y}))

/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in run(self, fetches, feed_dict, options, run_metadata)
    776     try:
    777       result = self._run(None, fetches, feed_dict, options_ptr,
--> 778                          run_metadata_ptr)
    779       if run_metadata:
    780         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in _run(self, handle, fetches, feed_dict, options, run_metadata)
    980     if final_fetches or final_targets:
    981       results = self._do_run(handle, final_targets, final_fetches,
--> 982                              feed_dict_string, options, run_metadata)
    983     else:
    984       results = []

/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1030     if handle is None:
   1031       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
-> 1032                            target_list, options, run_metadata)
   1033     else:
   1034       return self._do_call(_prun_fn, self._session, handle, feed_dict,

/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in _do_call(self, fn, *args)
   1050         except KeyError:
   1051           pass
-> 1052       raise type(e)(node_def, op, message)
   1053
   1054   def _extend_graph(self):

FailedPreconditionError: Attempting to use uninitialized value Variable
     [[Node: Variable/read = Identity[T=DT_FLOAT, _class=["loc:@Variable"], _device="/job:localhost/replica:0/task:0/gpu:0"](Variable)]]
     [[Node: Mean/_15 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_7_Mean", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

Caused by op u'Variable/read', defined at:
  File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/usr/local/lib/python2.7/dist-packages/ipykernel_launcher.py", line 16, in <module>
    app.launch_new_instance()
  File "/usr/local/lib/python2.7/dist-packages/traitlets/config/application.py", line 658, in launch_instance
    app.start()
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelapp.py", line 477, in start
    ioloop.IOLoop.instance().start()
  File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "/usr/local/lib/python2.7/dist-packages/tornado/ioloop.py", line 888, in start
    handler_func(fd_obj, events)
  File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 283, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 235, in dispatch_shell
    handler(stream, idents, msg)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 399, in execute_request
    user_expressions, allow_stdin)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/zmqshell.py", line 533, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2718, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2822, in run_ast_nodes
    if self.run_code(code, result):
  File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2882, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-3-7d229041d9bb>", line 6, in <module>
    'hidden1': tf.Variable(tf.random_normal([feature_dim, output_dim], stddev=1 / np.sqrt(feature_dim)))
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/variables.py", line 197, in __init__
    expected_shape=expected_shape)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/variables.py", line 316, in _init_from_args
    self._snapshot = array_ops.identity(self._variable, name="read")
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_array_ops.py", line 1338, in identity
    result = _op_def_lib.apply_op("Identity", input=input, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/op_def_library.py", line 768, in apply_op
    op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2336, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1228, in __init__
    self._traceback = _extract_stack()

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value Variable
     [[Node: Variable/read = Identity[T=DT_FLOAT, _class=["loc:@Variable"], _device="/job:localhost/replica:0/task:0/gpu:0"](Variable)]]
     [[Node: Mean/_15 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_7_Mean", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

In [ ]:

print(sess.run(weights['hidden1']))
In [ ]:
</code>```

same error for:

```<code>print(sess.run(weights['hidden1']))

</code>```

答:
Finally what I find is that seems every variable or operations we want to get access later need to be given a name, so is the placeholder, then we do not have the need to redefine the graph. The following is working finally, please give me more hints if there is an even more simple way to do that. </p>

```<code>import scipy.io
import numpy as np
import tensorflow as tf
import random

train_x = np.random.rand(200,2)
w= np.array([2,3])
train_y = np.dot(train_x, w)
train_y = np.reshape(train_y, [200,1])
feature_dim = 2
output_dim = 1

x = tf.placeholder(tf.float32, [None, feature_dim], name="input")
y_ = tf.placeholder(tf.float32, [None, output_dim], name="output")
weights = {
    'hidden1': tf.Variable(tf.random_normal([feature_dim, output_dim], stddev=1 / np.sqrt(feature_dim)), name="weights")
}

def network1(data):
    output = tf.matmul(data, weights['hidden1'])
    return output

y = network1(x)

loss_f = tf.reduce_mean(tf.squared_difference(y, y_), name="op_to_restore")

optimizer_f = tf.train.AdamOptimizer(1e-4).minimize(loss_f)
saver = tf.train.Saver()
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for i in range(100):
    batch_x = train_x
    batch_y = train_y
    sess.run(optimizer_f, feed_dict={x: batch_x, y_: batch_y})
    print(sess.run(loss_f, feed_dict={x: batch_x, y_: batch_y}))
saver.save(sess,'./savedmodel/', global_step = i)

with tf.Session() as sess:
    saver = tf.train.import_meta_graph('./savedmodel/-99.meta')
    saver.restore(sess,tf.train.latest_checkpoint('./savedmodel/'))
    graph = tf.get_default_graph()
    x = graph.get_tensor_by_name("input:0")
    y_ = graph.get_tensor_by_name("output:0")
    feed_dict={x: train_x, y_: train_y}
    op_to_restore = graph.get_tensor_by_name("op_to_restore:0")
    print(sess.run(op_to_restore, feed_dict))
</code>```

Body:
I have trained my model and saved it with using

    saver = tf.train.Saver()
    saver.save(sess, '/final_model', global_step = i)

Then I rebuild the exact same graph and try to restore the model to reproduce my result, restoring is working but as long as try to access to any value of the network parameters or operations, it gives me an error saying trying to use the uninitialized variable.

After rebuilding the graph, the code I use to restore is:

    sess=tf.Session()
    new_saver = tf.train.import_meta_graph('final_model-699.meta')
    new_saver.restore(sess, tf.train.latest_checkpoint('./'))

However, the following any of them give me an error of attempting to use uninitialized variable

    print(sess.run(weights['hidden1']))
    print(sess.run(loss_f, feed_dict={x: train_x, y_: train_y}))

Any idea?

As a simple example, here is the training and saving the model:

train_x = np.random.rand(200,2)
w= np.array([2,3])
train_y = np.dot(train_x, w)
train_y = np.reshape(train_y, [200,1])
feature_dim = 2
output_dim = 1

x = tf.placeholder(tf.float32, [None, feature_dim])
y_ = tf.placeholder(tf.float32, [None, output_dim])
weights = {
    'hidden1': tf.Variable(tf.random_normal([feature_dim, output_dim], stddev=1 / np.sqrt(feature_dim)))
}

def network1(data):
    output = tf.matmul(x, weights['hidden1'])
    return output
y = network1(x)

loss_f = output_dim * tf.reduce_mean(tf.squared_difference(y, y_))
optimizer_f = tf.train.AdamOptimizer(1e-4).minimize(loss_f)
saver = tf.train.Saver()
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for i in range(10000):
    batch_x = train_x
    batch_y = train_y
    sess.run(optimizer_f, feed_dict={x: batch_x, y_: batch_y})
    print(sess.run(loss_f, feed_dict={x: batch_x, y_: batch_y}))
saver.save(sess,'./savedmodel/', global_step = i)

Restoring and reproducing the result

import scipy.io
import numpy as np
import tensorflow as tf
import random
train_x = np.random.rand(200,2)
w= np.array([2,3])
train_y = np.dot(train_x, w)
train_y = np.reshape(train_y, [200,1])
feature_dim = 2
output_dim = 1
x = tf.placeholder(tf.float32, [None, feature_dim])
y_ = tf.placeholder(tf.float32, [None, output_dim])

weights = {
    'hidden1': tf.Variable(tf.random_normal([feature_dim, output_dim], stddev=1 / np.sqrt(feature_dim)))
}

def network1(data):
    output = tf.matmul(x, weights['hidden1'])
    return output

y = network1(x)
loss_f = tf.reduce_mean(tf.squared_difference(y, y_))
optimizer_f = tf.train.AdamOptimizer(1e-4).minimize(loss_f)
sess = tf.Session()
saver = tf.train.import_meta_graph('./savedmodel/-9999.meta')
saver.restore(sess, tf.train.latest_checkpoint('./savedmodel/'))

print(sess.run(loss_f, feed_dict={x: train_x, y_: train_y}))

The error:

FailedPreconditionErrorTraceback (most recent call last)
<ipython-input-5-17910473afab> in <module>()
----> 1 print(sess.run(loss_f, feed_dict={x: train_x, y_: train_y}))

/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in run(self, fetches, feed_dict, options, run_metadata)
    776     try:
    777       result = self._run(None, fetches, feed_dict, options_ptr,
--> 778                          run_metadata_ptr)
    779       if run_metadata:
    780         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in _run(self, handle, fetches, feed_dict, options, run_metadata)
    980     if final_fetches or final_targets:
    981       results = self._do_run(handle, final_targets, final_fetches,
--> 982                              feed_dict_string, options, run_metadata)
    983     else:
    984       results = []

/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1030     if handle is None:
   1031       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
-> 1032                            target_list, options, run_metadata)
   1033     else:
   1034       return self._do_call(_prun_fn, self._session, handle, feed_dict,

/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in _do_call(self, fn, *args)
   1050         except KeyError:
   1051           pass
-> 1052       raise type(e)(node_def, op, message)
   1053
   1054   def _extend_graph(self):

FailedPreconditionError: Attempting to use uninitialized value Variable
     [[Node: Variable/read = Identity[T=DT_FLOAT, _class=["loc:@Variable"], _device="/job:localhost/replica:0/task:0/gpu:0"](Variable)]]
     [[Node: Mean/_15 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_7_Mean", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

Caused by op u'Variable/read', defined at:
  File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/usr/local/lib/python2.7/dist-packages/ipykernel_launcher.py", line 16, in <module>
    app.launch_new_instance()
  File "/usr/local/lib/python2.7/dist-packages/traitlets/config/application.py", line 658, in launch_instance
    app.start()
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelapp.py", line 477, in start
    ioloop.IOLoop.instance().start()
  File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "/usr/local/lib/python2.7/dist-packages/tornado/ioloop.py", line 888, in start
    handler_func(fd_obj, events)
  File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 283, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 235, in dispatch_shell
    handler(stream, idents, msg)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 399, in execute_request
    user_expressions, allow_stdin)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/zmqshell.py", line 533, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2718, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2822, in run_ast_nodes
    if self.run_code(code, result):
  File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2882, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-3-7d229041d9bb>", line 6, in <module>
    'hidden1': tf.Variable(tf.random_normal([feature_dim, output_dim], stddev=1 / np.sqrt(feature_dim)))
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/variables.py", line 197, in __init__
    expected_shape=expected_shape)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/variables.py", line 316, in _init_from_args
    self._snapshot = array_ops.identity(self._variable, name="read")
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_array_ops.py", line 1338, in identity
    result = _op_def_lib.apply_op("Identity", input=input, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/op_def_library.py", line 768, in apply_op
    op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2336, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1228, in __init__
    self._traceback = _extract_stack()

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value Variable
     [[Node: Variable/read = Identity[T=DT_FLOAT, _class=["loc:@Variable"], _device="/job:localhost/replica:0/task:0/gpu:0"](Variable)]]
     [[Node: Mean/_15 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_7_Mean", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

In [ ]:

print(sess.run(weights['hidden1']))
In [ ]:

same error for:

print(sess.run(weights['hidden1']))

Body:
Finally what I find is that seems every variable or operations we want to get access later need to be given a name, so is the placeholder, then we do not have the need to redefine the graph. The following is working finally, please give me more hints if there is an even more simple way to do that.

import scipy.io
import numpy as np
import tensorflow as tf
import random

train_x = np.random.rand(200,2)
w= np.array([2,3])
train_y = np.dot(train_x, w)
train_y = np.reshape(train_y, [200,1])
feature_dim = 2
output_dim = 1

x = tf.placeholder(tf.float32, [None, feature_dim], name="input")
y_ = tf.placeholder(tf.float32, [None, output_dim], name="output")
weights = {
    'hidden1': tf.Variable(tf.random_normal([feature_dim, output_dim], stddev=1 / np.sqrt(feature_dim)), name="weights")
}

def network1(data):
    output = tf.matmul(data, weights['hidden1'])
    return output

y = network1(x)

loss_f = tf.reduce_mean(tf.squared_difference(y, y_), name="op_to_restore")

optimizer_f = tf.train.AdamOptimizer(1e-4).minimize(loss_f)
saver = tf.train.Saver()
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for i in range(100):
    batch_x = train_x
    batch_y = train_y
    sess.run(optimizer_f, feed_dict={x: batch_x, y_: batch_y})
    print(sess.run(loss_f, feed_dict={x: batch_x, y_: batch_y}))
saver.save(sess,'./savedmodel/', global_step = i)

with tf.Session() as sess:
    saver = tf.train.import_meta_graph('./savedmodel/-99.meta')
    saver.restore(sess,tf.train.latest_checkpoint('./savedmodel/'))
    graph = tf.get_default_graph()
    x = graph.get_tensor_by_name("input:0")
    y_ = graph.get_tensor_by_name("output:0")
    feed_dict={x: train_x, y_: train_y}
    op_to_restore = graph.get_tensor_by_name("op_to_restore:0")
    print(sess.run(op_to_restore, feed_dict))


问:
Cannot serialize my game stats
Well i am trying to save my Game Stats using system serializable but i am not being able to do it i have two scripts one named "Stats" and another named "SaveLoad" in the "Stats" i have my serializables and in the "SaveLoad" i have my saving and loading script i followed the instructions here

https://gamedevelopment.tutsplus.com/tutorials/how-to-save-and-load-your-players-progress-in-unity--cms-20934

But since i am a begginer with this stuff and my seriazable data differs i am having issues on saving it.

My "Stats"

```<code> using UnityEngine;
 using System.Collections;
[System.Serializable]
public class Stats : MonoBehaviour {

public static int coins = 0;
public static int totalcoins = 0;
public static int score = 0;

public static int personalbest = 0;
public static float UmbrellaSpeed = 0.1f;
public static float currentumbdur = 500;

public static int CarrotSpawnRateLVL = 1;
public static float CarrotSpawnRate = 60f;
public static int CarrotSpawnRateUpgradeCost = 15;

public static int UmbrellaDurabilityLVL = 1;
public static float UmbrellaDurability = 500;
public static int UmbrellaDurabilityUpgradeCost = 30;

public static int UmbrellaSizeLVL = 1;
public static float UmbrellaSize = 0f;
public static int UmbrellaSizeUpgradeCost = 25;

public static int CarrotEffectLVL = 1;
public static float CarrotEffect = 20;
public static int CarrotEffectUpgradeCost = 25;

public static int HealthRegenLVL = 1;
public static float HealthRegenTime = 4f;
public static int HealthRegenCost = 100;

public static int BuyTreesCost = 250;

public static int Tree1Bought = 0;
public static float Tree1Size = 0;
public static int Tree1SizeLVL = 1;
public static int Tree1SizeUpgradeCost = 50;

public static int Tree2Bought = 0;
public static float Tree2Size = 0;
public static int Tree2SizeLVL = 1;
public static int Tree2SizeUpgradeCost = 50;

public static int Tree3Bought = 0;
public static float Tree3Size =0;
public static int Tree3SizeLVL = 1;
public static int Tree3SizeUpgradeCost = 50;

// Use this for initialization
void Start () {
    InvokeRepeating ("AddCoins", 4.0f, 2.0f);
    InvokeRepeating ("AddScore", 1.5f, 1.5f);
}

// Update is called once per frame
void Update () {
    if (score > personalbest) {
        personalbest = score;
    }
    //Debug.Log (" " + coins);
}

void AddCoins (){
    if (BunnyScript.BunnyAlive == true) {
        coins += 1;

    }
}

void AddScore (){
    if (BunnyScript.BunnyAlive == true) {
        score += 1;
    }
}

}
</code>```

And my "SaveLoad" script

```<code>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public static class SaveLoad {
public static List<Stats> savedGames = new List<Stats>();

public static void Save (){
    savedGames.Add(Stats);
    BinaryFormatter bf = new BinaryFormatter();
    FileStream file = File.Create (Application.persistentDataPath + "/savedGames.gd");
    bf.Serialize(file, SaveLoad.savedGames);
    file.Close();
}

public static void Load (){
    if (File.Exists (Application.persistentDataPath + "/savedGames.gd")) {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Open(Application.persistentDataPath + "/savedGames.gd", FileMode.Open);
        SaveLoad.savedGames = (List<Stats>)bf.Deserialize(file);
        file.Close();
    }
}
}
</code>```

答:
You should not serialize a MonoBehaviour class for storing data, there is so much below that you cannot see in this type that it is just wrong.

Also, you have a list of stats object but it is only containing static value so all your Stats objects have same content.

```<code> using UnityEngine;
 using System.Collections;

public class Stats : MonoBehaviour
{
    StatContainer stats = new StatContainer();

    // Use this for initialization
    void Start () {
       InvokeRepeating ("AddCoins", 4.0f, 2.0f);
       InvokeRepeating ("AddScore", 1.5f, 1.5f);
    }

     // Update is called once per frame
    void Update () {
        this.stats.Update();
    }

    void AddCoins (){
       stats.AddCoins();
    }

    void AddScore (){
       stats.AddScore();
    }
}
[Serializable]
public class StatContainer
{
    public int coins = 0;
    public int totalcoins = 0;
    public int score = 0;

    public int personalbest = 0;
    public float UmbrellaSpeed = 0.1f;
    public float currentumbdur = 500;

    public  int CarrotSpawnRateLVL = 1;
    public float CarrotSpawnRate = 60f;
    public int CarrotSpawnRateUpgradeCost = 15;

    // and the rest

    public void Update(){
       if (statscore > personalbest) {
             personalbest = score;
       }
    }
}
</code>```

Now you can serialize the StatContainer in the same manner you were.
Because there is no static method anymore, each StatContainr on each Stats component is unique and not sharing anything with others.

And bonus, you can even perform unit test more easily with StatContainer, but that is another topic.

Title: Cannot serialize my game stats

Body:
Well i am trying to save my Game Stats using system serializable but i am not being able to do it i have two scripts one named "Stats" and another named "SaveLoad" in the "Stats" i have my serializables and in the "SaveLoad" i have my saving and loading script i followed the instructions here

https://gamedevelopment.tutsplus.com/tutorials/how-to-save-and-load-your-players-progress-in-unity--cms-20934

But since i am a begginer with this stuff and my seriazable data differs i am having issues on saving it.

My "Stats"

 using UnityEngine;
 using System.Collections;
[System.Serializable]
public class Stats : MonoBehaviour {

public static int coins = 0;
public static int totalcoins = 0;
public static int score = 0;

public static int personalbest = 0;
public static float UmbrellaSpeed = 0.1f;
public static float currentumbdur = 500;

public static int CarrotSpawnRateLVL = 1;
public static float CarrotSpawnRate = 60f;
public static int CarrotSpawnRateUpgradeCost = 15;

public static int UmbrellaDurabilityLVL = 1;
public static float UmbrellaDurability = 500;
public static int UmbrellaDurabilityUpgradeCost = 30;

public static int UmbrellaSizeLVL = 1;
public static float UmbrellaSize = 0f;
public static int UmbrellaSizeUpgradeCost = 25;

public static int CarrotEffectLVL = 1;
public static float CarrotEffect = 20;
public static int CarrotEffectUpgradeCost = 25;

public static int HealthRegenLVL = 1;
public static float HealthRegenTime = 4f;
public static int HealthRegenCost = 100;

public static int BuyTreesCost = 250;

public static int Tree1Bought = 0;
public static float Tree1Size = 0;
public static int Tree1SizeLVL = 1;
public static int Tree1SizeUpgradeCost = 50;

public static int Tree2Bought = 0;
public static float Tree2Size = 0;
public static int Tree2SizeLVL = 1;
public static int Tree2SizeUpgradeCost = 50;

public static int Tree3Bought = 0;
public static float Tree3Size =0;
public static int Tree3SizeLVL = 1;
public static int Tree3SizeUpgradeCost = 50;

// Use this for initialization
void Start () {
    InvokeRepeating ("AddCoins", 4.0f, 2.0f);
    InvokeRepeating ("AddScore", 1.5f, 1.5f);
}

// Update is called once per frame
void Update () {
    if (score > personalbest) {
        personalbest = score;
    }
    //Debug.Log (" " + coins);
}

void AddCoins (){
    if (BunnyScript.BunnyAlive == true) {
        coins += 1;

    }
}

void AddScore (){
    if (BunnyScript.BunnyAlive == true) {
        score += 1;
    }
}

}

And my "SaveLoad" script

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public static class SaveLoad {
public static List<Stats> savedGames = new List<Stats>();

public static void Save (){
    savedGames.Add(Stats);
    BinaryFormatter bf = new BinaryFormatter();
    FileStream file = File.Create (Application.persistentDataPath + "/savedGames.gd");
    bf.Serialize(file, SaveLoad.savedGames);
    file.Close();
}

public static void Load (){
    if (File.Exists (Application.persistentDataPath + "/savedGames.gd")) {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Open(Application.persistentDataPath + "/savedGames.gd", FileMode.Open);
        SaveLoad.savedGames = (List<Stats>)bf.Deserialize(file);
        file.Close();
    }
}
}

Body:
You should not serialize a MonoBehaviour class for storing data, there is so much below that you cannot see in this type that it is just wrong.

Also, you have a list of stats object but it is only containing static value so all your Stats objects have same content.

 using UnityEngine;
 using System.Collections;

public class Stats : MonoBehaviour
{
    StatContainer stats = new StatContainer();

    // Use this for initialization
    void Start () {
       InvokeRepeating ("AddCoins", 4.0f, 2.0f);
       InvokeRepeating ("AddScore", 1.5f, 1.5f);
    }

     // Update is called once per frame
    void Update () {
        this.stats.Update();
    }

    void AddCoins (){
       stats.AddCoins();
    }

    void AddScore (){
       stats.AddScore();
    }
}
[Serializable]
public class StatContainer
{
    public int coins = 0;
    public int totalcoins = 0;
    public int score = 0;

    public int personalbest = 0;
    public float UmbrellaSpeed = 0.1f;
    public float currentumbdur = 500;

    public  int CarrotSpawnRateLVL = 1;
    public float CarrotSpawnRate = 60f;
    public int CarrotSpawnRateUpgradeCost = 15;

    // and the rest

    public void Update(){
       if (statscore > personalbest) {
             personalbest = score;
       }
    }
}

Now you can serialize the StatContainer in the same manner you were.
Because there is no static method anymore, each StatContainr on each Stats component is unique and not sharing anything with others.

And bonus, you can even perform unit test more easily with StatContainer, but that is another topic.


问:
Error: Property 'pipe' does not exist on type 'Observable<any>'
I'm copy pasting one of the examples from here:

https://material.angular.io/components/autocomplete/overview

HTML:

```<code><form class="example-form">
  <mat-form-field class="example-full-width">
    <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
        {{ option }}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>
</code>```

TS:

```<code>import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs/Observable';
import {startWith} from 'rxjs/operators/startWith';
import {map} from 'rxjs/operators/map';

/**
 * @title Filter autocomplete
 */
@Component({
  selector: 'autocomplete-filter-example',
  templateUrl: 'autocomplete-filter-example.html',
  styleUrls: ['autocomplete-filter-example.css']
})
export class AutocompleteFilterExample {

  myControl: FormControl = new FormControl();

  options = [
    'One',
    'Two',
    'Three'
  ];

  filteredOptions: Observable<string[]>;

  ngOnInit() {
    this.filteredOptions = this.myControl.valueChanges
      .pipe(
        startWith(''),
        map(val => this.filter(val))
      );
  }

  filter(val: string): string[] {
    return this.options.filter(option =>
      option.toLowerCase().indexOf(val.toLowerCase()) === 0);
  }

}
</code>```

CSS:

```<code>.example-form {
  min-width: 150px;
  max-width: 500px;
  width: 100%;
}

.example-full-width {
  width: 100%;
}
</code>```

But I get this error:

Failed to compile: Property 'pipe' does not exist on type 'Observable'.

Any idea why?

答:
Make sure you are usingthe latest version of rxjs@5.x.x and angular.

https://github.com/ReactiveX/rxjs/blob/master/doc/lettable-operators.md

Body:
I'm copy pasting one of the examples from here:

https://material.angular.io/components/autocomplete/overview

HTML:

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
        {{ option }}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

TS:

import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs/Observable';
import {startWith} from 'rxjs/operators/startWith';
import {map} from 'rxjs/operators/map';

/**
 * @title Filter autocomplete
 */
@Component({
  selector: 'autocomplete-filter-example',
  templateUrl: 'autocomplete-filter-example.html',
  styleUrls: ['autocomplete-filter-example.css']
})
export class AutocompleteFilterExample {

  myControl: FormControl = new FormControl();

  options = [
    'One',
    'Two',
    'Three'
  ];

  filteredOptions: Observable<string[]>;

  ngOnInit() {
    this.filteredOptions = this.myControl.valueChanges
      .pipe(
        startWith(''),
        map(val => this.filter(val))
      );
  }

  filter(val: string): string[] {
    return this.options.filter(option =>
      option.toLowerCase().indexOf(val.toLowerCase()) === 0);
  }

}

CSS:

.example-form {
  min-width: 150px;
  max-width: 500px;
  width: 100%;
}

.example-full-width {
  width: 100%;
}

But I get this error:

Failed to compile: Property 'pipe' does not exist on type 'Observable'.

Any idea why?


问:
Flash Builder 4 Design View vs Flash runtime appearance w/SDK 4.1

Flash Builder's design view is worse than 3's (which at least was usable if you ignore some quirks), so WHAT do Flex UI designers (those who don't have paid design teams...) do to design a complex UI?  Because Design View (also based on what a lot of people say about it..) gets more useless with every release.

See image for some differences in design view vs. Flash. WHAT is causing this? css also posted.. ("Duration", "hr", "min" are mx Labels, the image size text is an mx Text comp. Project is an "mx only" SDK 4.1 project.)  I don't even care that the spinners look different, I just need it to show me correctly sized stuff so I can position things via Canvas, or properly size containers.

mx|Label {
    font-weight:bold;
    font-size:12;
}

mx|Text {
    font-weight:normal;
}

答:
Try embedding your fonts.  I've found the design view to be more accurate when you do so.

But overall, the design view sucks.  I code most of my views by hand.  Flash Catalyst gives you pretty good fidelity, but it's an entirely different type of tool.

ContentLicense: CC BY-SA 2.5


问:
Partially applied functions
While studying functional programming, the concept partially applied functions comes up a lot. In Haskell, something like the built-in function take is considered to be partially applied.

I am still unclear as to what it exactly means for a function to be partially applied or the use/implication of it.

答:
A function by itself can't be "partially applied" or not. It's a meaningless concept.

When you say that a function is "partially applied", you refer to how the function is called (aka "applied"). If the function is called with all its parameters, then it is said to be "fully applied". If some of the parameters are missing, then the function is said to be "partially applied".

For example:

```<code>-- The function `take` is fully applied here:
oneTwoThree = take 3 [1,2,3,4,5]

-- The function `take` is partially applied here:
take10 = take 10   -- see? it's missing one last argument

-- The function `take10` is fully applied here:
oneToTen = take10 [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,42]
</code>```

The result of a partial function application is another function - a function that still "expects" to get its missing arguments - like the take10 in the example above, which still "expects" to receive the list.

Of course, it all gets a bit more complicated once you get into the higher-order functions - i.e. functions that take other functions as arguments or return other functions as result. Consider this function:

```<code>mkTake n = take (n+5)
</code>```

The function mkTake has only one parameter, but it returns another function as result. Now, consider this:

```<code>x = mkTake 10
y = mkTake 10 [1,2,3]
</code>```

On the first line, the function mkTake is, obviously, "fully applied", because it is given one argument, which is exactly how many arguments it expects. But the second line is also valid: since mkTake 10 returns a function, I can then call this function with another parameter. So what does it make mkTake? "Overly applied", I guess?

Then consider the fact that (barring compiler optimizations) all functions are, mathematically speaking, functions of exactly one argument. How could this be? When you declare a function take n l = ..., what you're "conceptually" saying is take = \n -> \l -> ... - that is, take is a function that takes argument n and returns another function that takes argument l and returns some result.

So the bottom line is that the concept of "partial application" isn't really that strictly defined, it's just a handy shorthand to refer to functions that "ought to" (as in common sense) take N arguments, but are instead given M < N arguments.

Title: Partially applied functions

Body:
A function by itself can't be "partially applied" or not. It's a meaningless concept.

When you say that a function is "partially applied", you refer to how the function is called (aka "applied"). If the function is called with all its parameters, then it is said to be "fully applied". If some of the parameters are missing, then the function is said to be "partially applied".

For example:

-- The function `take` is fully applied here:
oneTwoThree = take 3 [1,2,3,4,5]

-- The function `take` is partially applied here:
take10 = take 10   -- see? it's missing one last argument

-- The function `take10` is fully applied here:
oneToTen = take10 [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,42]

The result of a partial function application is another function - a function that still "expects" to get its missing arguments - like the take10 in the example above, which still "expects" to receive the list.

Of course, it all gets a bit more complicated once you get into the higher-order functions - i.e. functions that take other functions as arguments or return other functions as result. Consider this function:

mkTake n = take (n+5)

The function mkTake has only one parameter, but it returns another function as result. Now, consider this:

x = mkTake 10
y = mkTake 10 [1,2,3]

On the first line, the function mkTake is, obviously, "fully applied", because it is given one argument, which is exactly how many arguments it expects. But the second line is also valid: since mkTake 10 returns a function, I can then call this function with another parameter. So what does it make mkTake? "Overly applied", I guess?

Then consider the fact that (barring compiler optimizations) all functions are, mathematically speaking, functions of exactly one argument. How could this be? When you declare a function take n l = ..., what you're "conceptually" saying is take = \n -> \l -> ... - that is, take is a function that takes argument n and returns another function that takes argument l and returns some result.

So the bottom line is that the concept of "partial application" isn't really that strictly defined, it's just a handy shorthand to refer to functions that "ought to" (as in common sense) take N arguments, but are instead given M < N arguments.


答:
the classic example is

```<code>add     :: Int -> Int -> Int
add x y = x + y
</code>```

add function takes two arguments and adds them, we can now implement

```<code>increment = add 1
</code>```

by partially applying add, which now waits for the other argument.

Title: Partially applied functions

Body:
While studying functional programming, the concept partially applied functions comes up a lot. In Haskell, something like the built-in function take is considered to be partially applied.

I am still unclear as to what it exactly means for a function to be partially applied or the use/implication of it.

Body:
the classic example is

add     :: Int -> Int -> Int
add x y = x + y

add function takes two arguments and adds them, we can now implement

increment = add 1

by partially applying add, which now waits for the other argument.