问:
Making a local scope inside a for loop, into a global scope
I have been searching but I cant get a clear answer. (I am a beginner in javascript and this is a test/practice inside the console) How can I make a local scope within a for loop, a global scope so I can then add it to variable with an array of objects. For Example :
I want the user to set how many stars(rating) a movie has inside a variable(prompt) named "stars". Then be able to call it inside the movieDb variable inside the object/array where it says "rating :" ... using the variable stars so it can console log the stars the user inputs along with the other information. Is this allowed or is there a different approach? </p>

```<code> var movieDb =[
  {
    haswatched : "i",
    title : "In Burges",
    rating : stars,
  },
  {
    haswatched : "i",
    title : "Frozen",
    rating : stars,
  },
  {
    haswatched : "i",
    title : "Mad Max",
    rating : stars,
  },
]

for (var i = 0; i < movieDb.length ; i++) {
  var w = prompt("did you watch the movie?")
  if (w === 'yes'){//first IF
    movieDb[i].haswatched = "you have watched";
    var r = prompt("would you like to rate us?");
        if (r === "yes") {//nested in first IF
            var stars = prompt("Enters Stars");
            alert("Thanks for rating & Watching!")
        } else if(r === "no"){ //nested in second IF
            alert("You did not rate, Thanks for watching!")
        }
  }
  else if (w === "no"){ //first ELSE IF
    movieDb[i].haswatched = "you have not seen";
  }
console.log(movieDb[i].haswatched + " " + "\""+movieDb[i].title+"\"" + " -" + movieDb[i].rating);
}'
</code>```

答:
I'm not sure I understood quite well your question so don't hesitate to correct me if I say something stupid or answer to a question you didn't ask.

The best way to define a variable inside a for loop scope is to declare it with let.

```<code>var i = "aaa";

for (let i = 0; i < 10; i++) {
    console.log(i); // => 0...9
}

console.log(i); // => "aaa"
</code>```

I think the problem you are facing is that stars doesn't exist.

You can either set it to false or null (or whatever value), and then set it to the number you get with the prompt, or just set it when you have the value :

```<code>{
haswatched : "i",
title : "In Burges"
}

...

movieDb[i].stars = stars;
</code>```

I don't know if it is quicker to set it to an Int value at first, but that would be such a tiny improvement in this case that I'm not sure it would matter much.

Hope it helps

Edit :

About let scope inside a loop, here's an example :

```<code><ul>
    <li>a</li>
    <li>b</li>
    <li>c</li>
    <li>d</li>
    <li>e</li>
</ul>

<script>
var lis = document.querySelectorAll('li');
for (let i = 0; i < lis.length; i++) {
    lis[i].addEventListener('click', function(){
        console.log(i);
    });
}
</script>
</code>```

When clicking on li, show position (from 0 to 4) although :

```<code><script>
var lis = document.querySelectorAll('li');
for (var i = 0; i < lis.length; i++) {
    lis[i].addEventListener('click', function(){
        console.log(i);
    });
}
</script>
</code>```

Would display 5 (i is incremented before leaving the loop)

Body:
I have been searching but I cant get a clear answer. (I am a beginner in javascript and this is a test/practice inside the console) How can I make a local scope within a for loop, a global scope so I can then add it to variable with an array of objects. For Example :
I want the user to set how many stars(rating) a movie has inside a variable(prompt) named "stars". Then be able to call it inside the movieDb variable inside the object/array where it says "rating :" ... using the variable stars so it can console log the stars the user inputs along with the other information. Is this allowed or is there a different approach?

 var movieDb =[
  {
    haswatched : "i",
    title : "In Burges",
    rating : stars,
  },
  {
    haswatched : "i",
    title : "Frozen",
    rating : stars,
  },
  {
    haswatched : "i",
    title : "Mad Max",
    rating : stars,
  },
]

for (var i = 0; i < movieDb.length ; i++) {
  var w = prompt("did you watch the movie?")
  if (w === 'yes'){//first IF
    movieDb[i].haswatched = "you have watched";
    var r = prompt("would you like to rate us?");
        if (r === "yes") {//nested in first IF
            var stars = prompt("Enters Stars");
            alert("Thanks for rating & Watching!")
        } else if(r === "no"){ //nested in second IF
            alert("You did not rate, Thanks for watching!")
        }
  }
  else if (w === "no"){ //first ELSE IF
    movieDb[i].haswatched = "you have not seen";
  }
console.log(movieDb[i].haswatched + " " + "\""+movieDb[i].title+"\"" + " -" + movieDb[i].rating);
}'

Body:
I'm not sure I understood quite well your question so don't hesitate to correct me if I say something stupid or answer to a question you didn't ask.

The best way to define a variable inside a for loop scope is to declare it with let.

var i = "aaa";

for (let i = 0; i < 10; i++) {
    console.log(i); // => 0...9
}

console.log(i); // => "aaa"

I think the problem you are facing is that stars doesn't exist.

You can either set it to false or null (or whatever value), and then set it to the number you get with the prompt, or just set it when you have the value :

{
haswatched : "i",
title : "In Burges"
}

...

movieDb[i].stars = stars;

I don't know if it is quicker to set it to an Int value at first, but that would be such a tiny improvement in this case that I'm not sure it would matter much.

Hope it helps

Edit :

About let scope inside a loop, here's an example :

<ul>
    <li>a</li>
    <li>b</li>
    <li>c</li>
    <li>d</li>
    <li>e</li>
</ul>

<script>
var lis = document.querySelectorAll('li');
for (let i = 0; i < lis.length; i++) {
    lis[i].addEventListener('click', function(){
        console.log(i);
    });
}
</script>

When clicking on li, show position (from 0 to 4) although :

<script>
var lis = document.querySelectorAll('li');
for (var i = 0; i < lis.length; i++) {
    lis[i].addEventListener('click', function(){
        console.log(i);
    });
}
</script>

Would display 5 (i is incremented before leaving the loop)


来源: stackexchange

问:
mongod is not saving dbpath
I'm trying to set up mongodb on an Ubuntu server.
But MongoDB seems to not saving the dbpath I give.
Neither as

```<code>mongod --dbpath ~/mongodb/data/db
</code>```

nor as a config file

```<code>mongod -f ~/etc/mongod.conf
</code>```

ERROR: dbpath (~/mongodb/data/db) does not exist.
   Create this directory or give existing directory in --dbpath.
   See http://dochub.mongodb.org/core/startingandstoppingmongo

```<code>net:
  bindIp: 127.0.0.1
  port: 21154
  http:
    enabled: true
security:
  authorization: enabled
storage:
  dbPath: "~/mongodb/data/db"
  smallFiles: true
</code>```

~/etc/mongod.conf

Mongo has full permission to those directories.
After closing the connection when mongo is waiting for on on 27017, he forgets the dbPath again.

Hope somebody could finally help, and hope I'm not getting something completely wrong since I'm new to Ubuntu & setting up mongodb.

Cheers.

答:
The command should be

```<code>mongod --config /etc/mongodb.conf
mongod --dbpath /etc/mongodb/data/db
</code>```

and not

mongod --config ~/etc/mongodb.conf
 mongod --dbpath ~/mongodb/data/db

and as said by @joe

The tilde(~) to mean $HOME is a shell expansion, so it isn't expected to work in a config file, try using the full path

ContentLicense: CC BY-SA 3.0

Title: mongod is not saving dbpath

Body:
I'm trying to set up mongodb on an Ubuntu server.
But MongoDB seems to not saving the dbpath I give.
Neither as

mongod --dbpath ~/mongodb/data/db

nor as a config file

mongod -f ~/etc/mongod.conf

ERROR: dbpath (~/mongodb/data/db) does not exist.
   Create this directory or give existing directory in --dbpath.
   See http://dochub.mongodb.org/core/startingandstoppingmongo

net:
  bindIp: 127.0.0.1
  port: 21154
  http:
    enabled: true
security:
  authorization: enabled
storage:
  dbPath: "~/mongodb/data/db"
  smallFiles: true

~/etc/mongod.conf

Mongo has full permission to those directories.
After closing the connection when mongo is waiting for on on 27017, he forgets the dbPath again.

Hope somebody could finally help, and hope I'm not getting something completely wrong since I'm new to Ubuntu & setting up mongodb.

Cheers.

Body:
The command should be

mongod --config /etc/mongodb.conf
mongod --dbpath /etc/mongodb/data/db

and not

mongod --config ~/etc/mongodb.conf
 mongod --dbpath ~/mongodb/data/db

and as said by @joe

The tilde(~) to mean $HOME is a shell expansion, so it isn't expected to work in a config file, try using the full path


问:
VBA Compare times correctly
I am using VBA to compare two times from a spreadsheet.
Im my example the actual value form the sheet is 23:00 in two cells. I use them for an if-statement, the values both come from two different arrays from the type Variant.

```<code>if dataArr(v1) = rowArr(v2) Then
</code>```

If I debug the two values it shows the two value like this

0,958333333333333 / 0,958333333333333

They seem the same but the compare in the if-statement returns false

So I subtracted the two value to see if the result is zero.

```<code>dataArr(v1) - rowArr(v2)
</code>```

In this case the result is not zero but

3,33066907387547E-16

So something is wrong with the compare or the two double values that represent the time.

The only working solution I found was to convert them to string values by

```<code>CStr(dataArr(v1)) = CStr(rowArr(v2))
</code>```

which returns true as it should be.

I don't really like this solution because it is not really how it should work. I also investigated what happens to the values before they end up in the compare but I could not find any mistake . Actually all the values in the dataArr are coming from the spreadsheet (ListObject.DataBodyRange.Value) and then certain values are copied to the rowArr out of the dataArr so it really should be the same value.

Any suggestions? Thanks!

答:
Thanks to Florent B I got a solution that works!

Florent B: To compare the equality of two dates, you need to round to the precision which is 24hrs x 60min x 60 sec

So the solution is:

```<code>If Round(dataArr(v1) * 86400) = Round(rowArr(v2) * 86400) Then
</code>```

It makes perfektly sense. Thanks a lot!

Title: VBA Compare times correctly

Body:
I am using VBA to compare two times from a spreadsheet.
Im my example the actual value form the sheet is 23:00 in two cells. I use them for an if-statement, the values both come from two different arrays from the type Variant.

if dataArr(v1) = rowArr(v2) Then

If I debug the two values it shows the two value like this

0,958333333333333 / 0,958333333333333

They seem the same but the compare in the if-statement returns false

So I subtracted the two value to see if the result is zero.

dataArr(v1) - rowArr(v2)

In this case the result is not zero but

3,33066907387547E-16

So something is wrong with the compare or the two double values that represent the time.

The only working solution I found was to convert them to string values by

CStr(dataArr(v1)) = CStr(rowArr(v2))

which returns true as it should be.

I don't really like this solution because it is not really how it should work. I also investigated what happens to the values before they end up in the compare but I could not find any mistake . Actually all the values in the dataArr are coming from the spreadsheet (ListObject.DataBodyRange.Value) and then certain values are copied to the rowArr out of the dataArr so it really should be the same value.

Any suggestions? Thanks!

Body:
Thanks to Florent B I got a solution that works!

Florent B: To compare the equality of two dates, you need to round to the precision which is 24hrs x 60min x 60 sec

So the solution is:

If Round(dataArr(v1) * 86400) = Round(rowArr(v2) * 86400) Then

It makes perfektly sense. Thanks a lot!


问:
Parse Server Javascript API Post To Pointer
I have a pointer field in my class on my Parse Server.  I am trying to use the Javascript API to write the objectId of a linked class field in a Pointer.  Here is my function:

```<code>  $scope.createItem = function (user, product) {
        var Item = Parse.Object.extend("II"),newII = new Item();
        newII.set("product", product);
        var acl = new Parse.ACL();
        acl.setPublicReadAccess(false);
        acl.setPublicWriteAccess(false);
        acl.setReadAccess(Parse.User.current(), true);
        acl.setWriteAccess(Parse.User.current(), true);
        // This doesn't work
        newII.set({
            "__type": "Pointer",
            "shop": "dklJ4Oaf2B"
        });
        newII.set("QTY", $scope.qtyCount);
        newII.save();
};
</code>```

The ACL & QTY fields (number) write to the database without issue, however the pointer field (named "shop") doesn't populate.

答:
Don't 'hand' code what you think a pointer should look like, use the sdk to do it for you!</p>

```<code>var shop = new ParseObject('Shop');
shop.id = 'dklJ4Oaf2B';
var newII = new Item();
newII.set('shop', shop);
newII.save()
</code>```

Body:
I have a pointer field in my class on my Parse Server.  I am trying to use the Javascript API to write the objectId of a linked class field in a Pointer.  Here is my function:

  $scope.createItem = function (user, product) {
        var Item = Parse.Object.extend("II"),newII = new Item();
        newII.set("product", product);
        var acl = new Parse.ACL();
        acl.setPublicReadAccess(false);
        acl.setPublicWriteAccess(false);
        acl.setReadAccess(Parse.User.current(), true);
        acl.setWriteAccess(Parse.User.current(), true);
        // This doesn't work
        newII.set({
            "__type": "Pointer",
            "shop": "dklJ4Oaf2B"
        });
        newII.set("QTY", $scope.qtyCount);
        newII.save();
};

The ACL & QTY fields (number) write to the database without issue, however the pointer field (named "shop") doesn't populate.

Body:
Don't 'hand' code what you think a pointer should look like, use the sdk to do it for you!

var shop = new ParseObject('Shop');
shop.id = 'dklJ4Oaf2B';
var newII = new Item();
newII.set('shop', shop);
newII.save()


问:
Define expected parameters for a controller action in Rails
I remember once seeing the ability to define at the top of a controller the parameters that an action requires to work. For the life of me I can't seem to find any mention of that capability anymore and it would be useful for the following:

```<code>def sort
  params[:links].each_with_index do |id, index|
    @link_set.links.in_context(context).update_all(['position=?', index+1], ['id=?', id])
  end
  render :nothing => true
end
</code>```

I'm expecting params[:links] so if some smarty decides to visit that action without giving me params then it fails with nil.each_with_index.

It'd be nice to gracefully give a 404 or something if the parameters are missing without having to code this into every method of this type.

Does this exist? :)

答:
I dont recall functionality existing that allows you to do that. You could use this instead at the top of your action:</p>

```<code>params[:links] ||= []
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I remember once seeing the ability to define at the top of a controller the parameters that an action requires to work. For the life of me I can't seem to find any mention of that capability anymore and it would be useful for the following:

def sort
  params[:links].each_with_index do |id, index|
    @link_set.links.in_context(context).update_all(['position=?', index+1], ['id=?', id])
  end
  render :nothing => true
end

I'm expecting params[:links] so if some smarty decides to visit that action without giving me params then it fails with nil.each_with_index.

It'd be nice to gracefully give a 404 or something if the parameters are missing without having to code this into every method of this type.

Does this exist? :)

Body:
I dont recall functionality existing that allows you to do that. You could use this instead at the top of your action:

params[:links] ||= []


问:
How to run an instance of Excel Online on my own domain?
I stumbled on this website and found it very interesting because I'm trying to do the same thing: run Excel Online on my own domain. I tried Googling around without success. Does anyone have a resource or approach to this problem (see image for more information*) ?

答:
I think you would need to Configure your Online Office Server:

Configure Office Online Server for SharePoint Server 2016


问:
Eclipse Oxygen Java giving empty error
I have some Java that, in theory, draws a line from the top left corner to the bottom right corner of the 500x500 window. The code:

```<code>import javax.swing.JComponent;
import javax.swing.JFrame;

import java.awt.*;
import java.awt.geom.*;

@SuppressWarnings("serial")

public class graphix extends JFrame{

    public static void main(String[] args){

        new graphix();
    }

    public graphix(){

        this.setSize(500, 500);

        this.setTitle("Title Here");

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        this.add(new Draw(), BorderLayout.CENTER);

        this.setVisible(true);

    }

    private class Draw extends JComponent{

        public void paint(Graphics g){

            Graphics2D graph2 = (Graphics2D)g;

            graph2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            Shape drawLine = new Line2D.Float(10, 10, 490, 490);

            graph2.setPaint(Color.BLACK);

            graph2.draw(drawLine);

        }

    }

}
</code>```

When i run this code, eclipse gives me the error:

```<code>Exception in thread "main" java.lang.Error: Unresolved compilation problem:

at graphix.graphix.main(graphix.java:11)
</code>```

normally in eclipse, the error message will be displayed in the empty space between those two lines, but it says the error is triggered at line 11, which is

```<code>public static void main(String[] args){
</code>```

My project name is graphix, and the class file name is graphix.java

EDIT:

There is also a non-fatal error:

```<code>The declared package "" does not match the expected package "graphix"
</code>```

triggered by:

```<code>import javax.swing.JComponent;
</code>```

答:
The package declaration is missing on the top of the file, it must match the file structure inside your project:</p>

```<code>package xxx.yyy.zzz;
</code>```

Title: Eclipse Oxygen Java giving empty error

Body:
I have some Java that, in theory, draws a line from the top left corner to the bottom right corner of the 500x500 window. The code:

import javax.swing.JComponent;
import javax.swing.JFrame;

import java.awt.*;
import java.awt.geom.*;

@SuppressWarnings("serial")

public class graphix extends JFrame{

    public static void main(String[] args){

        new graphix();
    }

    public graphix(){

        this.setSize(500, 500);

        this.setTitle("Title Here");

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        this.add(new Draw(), BorderLayout.CENTER);

        this.setVisible(true);

    }

    private class Draw extends JComponent{

        public void paint(Graphics g){

            Graphics2D graph2 = (Graphics2D)g;

            graph2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            Shape drawLine = new Line2D.Float(10, 10, 490, 490);

            graph2.setPaint(Color.BLACK);

            graph2.draw(drawLine);

        }

    }

}

When i run this code, eclipse gives me the error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:

at graphix.graphix.main(graphix.java:11)

normally in eclipse, the error message will be displayed in the empty space between those two lines, but it says the error is triggered at line 11, which is

public static void main(String[] args){

My project name is graphix, and the class file name is graphix.java

EDIT:

There is also a non-fatal error:

The declared package "" does not match the expected package "graphix"

triggered by:

import javax.swing.JComponent;

Body:
The package declaration is missing on the top of the file, it must match the file structure inside your project:

package xxx.yyy.zzz;


问:
Finding equal variables in non solvable multi-variables linear equations
I am trying to find an algorithm to solve the current problem. I have multiple unknown variables (F1,F2,F3, ... Fx) and (R1,R2,R3 ... Rx) and multiple equations like this:

```<code>F1 + R1 = a
F1 + R2 = a
F2 + R1 = b
F3 + R2 = b
F2 + R3 = c
F3 + R4 = c
</code>```

where a, b and c are known numbers. I am trying to find all equal variables in such equations. For example in the above equation I could see that F2 and F3 are equal and R3 and R4 are equal.

First equations tells us that R1 and R2 are equal, and second tells us that F2 and F3 are equal, while the third tells us that R3 and R4 are equal.

For a more complex scenario, is there any known algorithm that can find all equal (F and R) variables????

(I will edit the question if it is not clear enough)

Thanks

答:
Here's a hint: you have defined a system of linear equations with 7 variables and 6 equations. Here's a crude matrix/vector notation:

```<code> 1 0 0 1 0 0 0     F1     a
 1 0 0 0 1 0 0     F2     a
 0 1 0 1 0 0 0  *  F3  =  b
 0 0 1 0 1 0 0     R1     b
 0 1 0 0 0 1 0     R2     c
 0 0 1 0 0 0 1     R3     c
                   R4
</code>```

If you do the Gaussian elimination manually, you can see that e.g. first row minus the second row results in

```<code> (0 0 0 1 -1 0 0) * (F1 F2 F3 R1 R2 R3 R4)^T = a - a
                                     R1 - R2 = 0
                                          R1 = R2
</code>```

Which implies that R1 and R2 are what you call equivalent. There are many different methods to solve the system or interpret the results. Maybe you will find this thread useful: Is there a standard solution for Gauss elimination in Python?

Body:
I am trying to find an algorithm to solve the current problem. I have multiple unknown variables (F1,F2,F3, ... Fx) and (R1,R2,R3 ... Rx) and multiple equations like this:

F1 + R1 = a
F1 + R2 = a
F2 + R1 = b
F3 + R2 = b
F2 + R3 = c
F3 + R4 = c

where a, b and c are known numbers. I am trying to find all equal variables in such equations. For example in the above equation I could see that F2 and F3 are equal and R3 and R4 are equal.

First equations tells us that R1 and R2 are equal, and second tells us that F2 and F3 are equal, while the third tells us that R3 and R4 are equal.

For a more complex scenario, is there any known algorithm that can find all equal (F and R) variables????

(I will edit the question if it is not clear enough)

Thanks

Body:
Here's a hint: you have defined a system of linear equations with 7 variables and 6 equations. Here's a crude matrix/vector notation:

 1 0 0 1 0 0 0     F1     a
 1 0 0 0 1 0 0     F2     a
 0 1 0 1 0 0 0  *  F3  =  b
 0 0 1 0 1 0 0     R1     b
 0 1 0 0 0 1 0     R2     c
 0 0 1 0 0 0 1     R3     c
                   R4

If you do the Gaussian elimination manually, you can see that e.g. first row minus the second row results in

 (0 0 0 1 -1 0 0) * (F1 F2 F3 R1 R2 R3 R4)^T = a - a
                                     R1 - R2 = 0
                                          R1 = R2

Which implies that R1 and R2 are what you call equivalent. There are many different methods to solve the system or interpret the results. Maybe you will find this thread useful: Is there a standard solution for Gauss elimination in Python?


问:
Strange plot by using sklearn.linear_model
I typically use MATLAB, but want to push myself to learn something about Python. I tried a code of linear regression that introduced by a youtuber. Here is the code:

```<code>import pandas as pd
from sklearn import linear_model
import matplotlib.pyplot as plt

#read data
dataframe = pd.read_fwf('brain_body.txt')
x_values = dataframe[['Brain']]
y_values = dataframe[['Body']]

#train model on data
body_reg = linear_model.LinearRegression()
body_reg.fit(x_values,y_values)

#visualize results
plt.scatter(x_values,y_values)
plt.plot(x_values,body_reg.predict(x_values))
plt.show()
</code>```

But I ended up with a very strange plot (I use Python 3.6):
1

here is part of details:
2

Apparently, something is missing or wrong.

The data of brain_body.txt can be found in https://github.com/llSourcell/linear_regression_demo/blob/master/brain_body.txt

Any suggestion or advice is welcome.

Update

I tried sera's code, and here is what I get:
3

It's funny and weird. it occurred to me that something is wrong with my data file, or something missing in my Python, but I just copied and pasted the raw data into the notepad and saved as .txt; I tried Python 3.6 and 2.7 as well as Pycharm and Spyder...so I have no idea...
BTW, the youtube video is here

@sascha @Moritz @sera I asked my friend to run the same code and data file, and everything is fine. In other words, there is something wrong with my Python and I don't know why. Let me try another computer and/or try an earlier version of python.

I tried, but nothing changed. Here are two different approaches I used to install Python:
1. Install Python (e.g. ver. 3.6); install Pycharm; install packages Pandas, scikit-learn...
2. Install Anaconda

Solved

Thanks for @Marc Bataillou 's suggestion. This is a problem associated with different versions of matplotlib. The problem was found in version 2.1.0. I tried 2.0.2 and found that the original code works fine in the older version; apparently, some changes are made from 2.0.2 to 2.1.0. Thanks for all your efforts.

答:
You should use
plt.scatter(x_values.values,y_values.values)
instead of
plt.scatter(x_values,y_values)

I hope it works !

Body:
I typically use MATLAB, but want to push myself to learn something about Python. I tried a code of linear regression that introduced by a youtuber. Here is the code:

import pandas as pd
from sklearn import linear_model
import matplotlib.pyplot as plt

#read data
dataframe = pd.read_fwf('brain_body.txt')
x_values = dataframe[['Brain']]
y_values = dataframe[['Body']]

#train model on data
body_reg = linear_model.LinearRegression()
body_reg.fit(x_values,y_values)

#visualize results
plt.scatter(x_values,y_values)
plt.plot(x_values,body_reg.predict(x_values))
plt.show()

But I ended up with a very strange plot (I use Python 3.6):
1

here is part of details:
2

Apparently, something is missing or wrong.

The data of brain_body.txt can be found in https://github.com/llSourcell/linear_regression_demo/blob/master/brain_body.txt

Any suggestion or advice is welcome.

Update

I tried sera's code, and here is what I get:
3

It's funny and weird. it occurred to me that something is wrong with my data file, or something missing in my Python, but I just copied and pasted the raw data into the notepad and saved as .txt; I tried Python 3.6 and 2.7 as well as Pycharm and Spyder...so I have no idea...
BTW, the youtube video is here

@sascha @Moritz @sera I asked my friend to run the same code and data file, and everything is fine. In other words, there is something wrong with my Python and I don't know why. Let me try another computer and/or try an earlier version of python.

I tried, but nothing changed. Here are two different approaches I used to install Python:
1. Install Python (e.g. ver. 3.6); install Pycharm; install packages Pandas, scikit-learn...
2. Install Anaconda

Solved

Thanks for @Marc Bataillou 's suggestion. This is a problem associated with different versions of matplotlib. The problem was found in version 2.1.0. I tried 2.0.2 and found that the original code works fine in the older version; apparently, some changes are made from 2.0.2 to 2.1.0. Thanks for all your efforts.


问:
Assigning picture stored on file system to item selected from database
I am building php my sql application and I need to associate picture to various items that are selected from database.

For example I want to have news on my web site, and I retrieve news from database, news properties can be Title, Content and Time, but I also need picture that is going to appear together with that news on a web site.

How to dynamically associate picture form file system to a selected row from database..

Thanks a lot.

答:
Add a column to the database called 'image' or something. That is, if a news items is stored in a row, it will have a column called 'images' in it. So you can store the path (location) to the image associated with that news item it's column.

This way you can display the associated image when a news item is displayed. Also you can store more than 1 image information in the image field (as csv or serialized array or something.)


问:
Postgres - Cohort analysis across months sequentially, not if exists in any later month
I'm doing a cohort analysis and can get the group of users to examine, then see whether they transacted in the months following on. But I want it like this:

Of that group in December, who transacted in Jan; of the Jan group from Dec, who transacted in Feb. Basically i'm tracking decay of the customer base

What I don't want is those that return in any month following Dec, which is this:

```<code>WITH start_sample AS (
SELECT
  user_fk,
  created_at AS start_sample_date
  FROM transactions
    WHERE created_at >= '2016-11-01' AND created_at < '2016-12-01'
      GROUP BY user_fk,
        start_sample_date),

start_sample_min AS (
SELECT
  user_fk,
  MIN(start_sample_date) AS first_transaction
    FROM start_sample
      GROUP BY user_fk
  )

SELECT
  DATE_TRUNC('month', created_at) AS transacting_month,
  COUNT(DISTINCT user_fk)
    FROM transactions
        WHERE created_at >= '2016-11-01'
        AND t.user_fk IN(SELECT user_fk FROM start_sample_min)
          GROUP BY transacting_month
            ORDER BY transacting_month;
</code>```

Then I made a churn model to see if it would get what I need, but it doesn't:

```<code>WITH monthly_users AS (
    SELECT
      user_fk AS monthly_user_fk,
      DATE_TRUNC('month', created_at) AS month
        FROM transactions
          WHERE created_at >= '2016-11-01' AND created_at < '2017-12-01'
            GROUP BY monthly_user_fk, month
            ORDER BY monthly_user_fk, month
),

lag_lead AS (
  SELECT
    monthly_user_fk,
    month,
    LAG(month,1) OVER (PARTITION BY monthly_user_fk ORDER BY month) AS lag,
    LEAD(month,1) OVER (PARTITION BY monthly_user_fk ORDER BY month) AS lead
      FROM monthly_users),

lag_lead_with_diffs AS (
  SELECT
    monthly_user_fk,
    month,
    lag AS previous_month,
    lead AS next_month,
    EXTRACT(EPOCH FROM (month - lag)/86400)::INT AS lag_size,
    EXTRACT(EPOCH FROM (lead - month)/86400)::INT AS lead_size
      FROM lag_lead
  ),

calculated AS (
      SELECT
      month,
      CASE WHEN previous_month IS NULL THEN 'ACTIVATION'
          WHEN lag_size <= 31 THEN 'ACTIVE'
          WHEN lag_size > 31 THEN 'RETURN' END AS this_month_values,
      CASE WHEN (lead_size > 31 OR lead_size IS NULL) THEN 'CHURN' ELSE NULL END AS next_month_churn,
      COUNT(DISTINCT monthly_user_fk) AS c_d_users
   FROM lag_lead_with_diffs
  GROUP BY month, 2, 3
)

SELECT
  month,
  this_month_values,
  SUM(c_d_users) AS distinct_users
  FROM calculated
  GROUP BY month, this_month_values
UNION
SELECT month + INTERVAL '1 month',
  'CHURN',
  SUM(c_d_users)
  FROM calculated
    WHERE next_month_churn IS NOT NULL
      GROUP BY month + INTERVAL '1 month', 2
        HAVING (EXTRACT(EPOCH FROM (month + INTERVAL '1 month'))) < 1512086400
          ORDER BY month, this_month_values;
</code>```

However this is not fixed at the initial group. The Active group rolls from month to month.

I understand that the above is likely more complicated than what i'm asking, but I can't seem to get my head around it

Thanks in advance

答:
Perhaps this is what you are looking for:

```<code>with Monthly_Users as (
select user_fk
     , date_trunc('month',created_at) as month
     , (date_part('year', created_at) - 2016) * 12
     + date_part('month', created_at) - 11 as Months_Between
  from transactions
 where created_at between date '2016-11-01'
                      and date '2017-12-01'
 group by user_fk, month, months_between
), t2 as (
select Monthly_Users.*
     , count(*) over (partition by user_fk
                          order by month rows between unbounded preceding
                                                  and 1 preceding) prev_rec_cnt
  from Monthly_Users
)
select month
     , count(*)
  from t2
 where Months_Between = Prev_Rec_Cnt
 group by month
 order by month;
</code>```

In this query the Monthly_Users CTE is just like yours, but adds a computation of the number of Months_Between the created_at date and your initial starting date.  In the second Common Table Expression, I count the number of occurrences of each user_fk prior to the current months record.  Finally in the output query I limit the results to only those records where the Months_Between value matches the Prev_Rec_Cnt value. Any missed months will cause the Prev_Rec_Cnt value to not match the Months_Between value, so you'll be able to see the fall off of user_fk values from month to month.

Body:
I'm doing a cohort analysis and can get the group of users to examine, then see whether they transacted in the months following on. But I want it like this:

Of that group in December, who transacted in Jan; of the Jan group from Dec, who transacted in Feb. Basically i'm tracking decay of the customer base

What I don't want is those that return in any month following Dec, which is this:

WITH start_sample AS (
SELECT
  user_fk,
  created_at AS start_sample_date
  FROM transactions
    WHERE created_at >= '2016-11-01' AND created_at < '2016-12-01'
      GROUP BY user_fk,
        start_sample_date),

start_sample_min AS (
SELECT
  user_fk,
  MIN(start_sample_date) AS first_transaction
    FROM start_sample
      GROUP BY user_fk
  )

SELECT
  DATE_TRUNC('month', created_at) AS transacting_month,
  COUNT(DISTINCT user_fk)
    FROM transactions
        WHERE created_at >= '2016-11-01'
        AND t.user_fk IN(SELECT user_fk FROM start_sample_min)
          GROUP BY transacting_month
            ORDER BY transacting_month;

Then I made a churn model to see if it would get what I need, but it doesn't:

WITH monthly_users AS (
    SELECT
      user_fk AS monthly_user_fk,
      DATE_TRUNC('month', created_at) AS month
        FROM transactions
          WHERE created_at >= '2016-11-01' AND created_at < '2017-12-01'
            GROUP BY monthly_user_fk, month
            ORDER BY monthly_user_fk, month
),

lag_lead AS (
  SELECT
    monthly_user_fk,
    month,
    LAG(month,1) OVER (PARTITION BY monthly_user_fk ORDER BY month) AS lag,
    LEAD(month,1) OVER (PARTITION BY monthly_user_fk ORDER BY month) AS lead
      FROM monthly_users),

lag_lead_with_diffs AS (
  SELECT
    monthly_user_fk,
    month,
    lag AS previous_month,
    lead AS next_month,
    EXTRACT(EPOCH FROM (month - lag)/86400)::INT AS lag_size,
    EXTRACT(EPOCH FROM (lead - month)/86400)::INT AS lead_size
      FROM lag_lead
  ),

calculated AS (
      SELECT
      month,
      CASE WHEN previous_month IS NULL THEN 'ACTIVATION'
          WHEN lag_size <= 31 THEN 'ACTIVE'
          WHEN lag_size > 31 THEN 'RETURN' END AS this_month_values,
      CASE WHEN (lead_size > 31 OR lead_size IS NULL) THEN 'CHURN' ELSE NULL END AS next_month_churn,
      COUNT(DISTINCT monthly_user_fk) AS c_d_users
   FROM lag_lead_with_diffs
  GROUP BY month, 2, 3
)

SELECT
  month,
  this_month_values,
  SUM(c_d_users) AS distinct_users
  FROM calculated
  GROUP BY month, this_month_values
UNION
SELECT month + INTERVAL '1 month',
  'CHURN',
  SUM(c_d_users)
  FROM calculated
    WHERE next_month_churn IS NOT NULL
      GROUP BY month + INTERVAL '1 month', 2
        HAVING (EXTRACT(EPOCH FROM (month + INTERVAL '1 month'))) < 1512086400
          ORDER BY month, this_month_values;

However this is not fixed at the initial group. The Active group rolls from month to month.

I understand that the above is likely more complicated than what i'm asking, but I can't seem to get my head around it

Thanks in advance

Body:
Perhaps this is what you are looking for:

with Monthly_Users as (
select user_fk
     , date_trunc('month',created_at) as month
     , (date_part('year', created_at) - 2016) * 12
     + date_part('month', created_at) - 11 as Months_Between
  from transactions
 where created_at between date '2016-11-01'
                      and date '2017-12-01'
 group by user_fk, month, months_between
), t2 as (
select Monthly_Users.*
     , count(*) over (partition by user_fk
                          order by month rows between unbounded preceding
                                                  and 1 preceding) prev_rec_cnt
  from Monthly_Users
)
select month
     , count(*)
  from t2
 where Months_Between = Prev_Rec_Cnt
 group by month
 order by month;

In this query the Monthly_Users CTE is just like yours, but adds a computation of the number of Months_Between the created_at date and your initial starting date.  In the second Common Table Expression, I count the number of occurrences of each user_fk prior to the current months record.  Finally in the output query I limit the results to only those records where the Months_Between value matches the Prev_Rec_Cnt value. Any missed months will cause the Prev_Rec_Cnt value to not match the Months_Between value, so you'll be able to see the fall off of user_fk values from month to month.


问:
How do I get 'npm test' to find my karma.conf.js file?
I have the following structure in my application:

```<code>Web (Asp net core)
|
|--wwwroot
|--ClientApp
|  |--app
|  |  |-- ... (typescript modules, *.spec.js files etc.)
|  |
|  |--karma.config.js
|  |--test-main.js
|
|--Controllers
|--config.json files for web etc.
</code>```

In the console I'm in the ClientApp folder when running:

```<code>npm test
</code>```

I get the following error:

```<code>File C:\Users\...\Web\karma.conf.js does not exist!
</code>```

Why does it try to look for the karma.conf.js file in the Web folder?

How can I tell it to look in the right place? Even if I CD to the app folder I get the exact same error.

If I try to place the karma.conf.js file where it expects it, I get a bunch of other errors like:

```<code>cannot find module requirejs
</code>```

I'm horribly confused, would really appreciate some help.

karma.conf.js file:

```<code>module.exports = function(config) {
config.set({

basePath: '',
frameworks: ['jasmine', 'requirejs'],
files: [
  'test-main.js',
  {pattern: 'test/**/*spec.js', included: false},
  {pattern: '*.js', included: false}
],
exclude: [
],
preprocessors: {
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome', 'Firefox'],
singleRun: false,
concurrency: Infinity
})
}
</code>```

test-main.js:

```<code>var allTestFiles = []
var TEST_REGEXP = /(spec|test)\.js$/i

Object.keys(window.__karma__.files).forEach(function (file) {
  if (TEST_REGEXP.test(file)) {
    var normalizedTestModule = file.replace(/^\/base\/|\.js$/g, '')
    allTestFiles.push(normalizedTestModule)
  }
})

require.config({
  baseUrl: '/base',
  deps: allTestFiles,
  callback: window.__karma__.start
})
</code>```

答:
Just go into your package.json and edit the test script to point to the location of your karma config.

```<code>"scripts": {
    "test": "karma start ./path/to/karma.conf.js"
}
</code>```

Body:
I have the following structure in my application:

Web (Asp net core)
|
|--wwwroot
|--ClientApp
|  |--app
|  |  |-- ... (typescript modules, *.spec.js files etc.)
|  |
|  |--karma.config.js
|  |--test-main.js
|
|--Controllers
|--config.json files for web etc.

In the console I'm in the ClientApp folder when running:

npm test

I get the following error:

File C:\Users\...\Web\karma.conf.js does not exist!

Why does it try to look for the karma.conf.js file in the Web folder?

How can I tell it to look in the right place? Even if I CD to the app folder I get the exact same error.

If I try to place the karma.conf.js file where it expects it, I get a bunch of other errors like:

cannot find module requirejs

I'm horribly confused, would really appreciate some help.

karma.conf.js file:

module.exports = function(config) {
config.set({

basePath: '',
frameworks: ['jasmine', 'requirejs'],
files: [
  'test-main.js',
  {pattern: 'test/**/*spec.js', included: false},
  {pattern: '*.js', included: false}
],
exclude: [
],
preprocessors: {
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome', 'Firefox'],
singleRun: false,
concurrency: Infinity
})
}

test-main.js:

var allTestFiles = []
var TEST_REGEXP = /(spec|test)\.js$/i

Object.keys(window.__karma__.files).forEach(function (file) {
  if (TEST_REGEXP.test(file)) {
    var normalizedTestModule = file.replace(/^\/base\/|\.js$/g, '')
    allTestFiles.push(normalizedTestModule)
  }
})

require.config({
  baseUrl: '/base',
  deps: allTestFiles,
  callback: window.__karma__.start
})

Body:
Just go into your package.json and edit the test script to point to the location of your karma config.

"scripts": {
    "test": "karma start ./path/to/karma.conf.js"
}


问:
Invalid Syntax - List index
im writing the code below:

```<code>def add_to_index(index,keyword,url):
    i=0
    while i<=len(index):
    if keyword in index[i]:
        index[i][1].append(url)
    else:
        index.append([keyword,[url]])
    i=i+2
</code>```

Im curious because when I define the index as

```<code>index = []
</code>```

gives me the error list out of range, whats makes sense because there is no entry in my list, but when I define the index as

```<code> index=[['udacity',['http_qualquer'],['udacity',['http_any']]]
</code>```

the error is:

```<code>Traceback (most recent call last):
  File "vm_main.py", line 33, in <module>
    import main
  File "/tmp/vmuser_azqmlozsjr/main.py", line 18
    def add_to_index(index,keyword,url):
      ^
SyntaxError: invalid syntax
</code>```

And there is no error in the syntax of this specific line, if the syntax was wrong the error should have appeared when the index was empty.

答:
use index this one

It should end with four brackets
check that number of open brackets should match number of closed brackets

```<code>index=[['udacity',['http_qualquer'],['udacity',['http_any']]]]
</code>```

Title: Invalid Syntax - List index

Body:
im writing the code below:

def add_to_index(index,keyword,url):
    i=0
    while i<=len(index):
    if keyword in index[i]:
        index[i][1].append(url)
    else:
        index.append([keyword,[url]])
    i=i+2

Im curious because when I define the index as

index = []

gives me the error list out of range, whats makes sense because there is no entry in my list, but when I define the index as

 index=[['udacity',['http_qualquer'],['udacity',['http_any']]]

the error is:

Traceback (most recent call last):
  File "vm_main.py", line 33, in <module>
    import main
  File "/tmp/vmuser_azqmlozsjr/main.py", line 18
    def add_to_index(index,keyword,url):
      ^
SyntaxError: invalid syntax

And there is no error in the syntax of this specific line, if the syntax was wrong the error should have appeared when the index was empty.

Body:
use index this one

It should end with four brackets
check that number of open brackets should match number of closed brackets

index=[['udacity',['http_qualquer'],['udacity',['http_any']]]]


问:
How to index a 1D numpy array as if it is a matrix with 1 row?
I have a 1D numpy array like:

```<code>a = np.array([1,2,3,4,5])
</code>```

And I would like to index this a like (as if it's a 1 by 5 matrix, and a[0,2] would be equal to 3):

```<code>a[0,2]

Traceback (most recent call last):

  File "<ipython-input-34-2fc0526218b3>", line 1, in <module>
    a[0,1]

IndexError: too many indices for array
</code>```

I know in MATLAB it's possible, but how to do that in Python? The reason that I need this is coz that a is dynamically generated, sometimes it's a 1D array, sometimes it's a nD array. And I need a unified way of indexing in my loop.

答:
Use .reshape and pass -1 as the second argument:

```<code>>>> a = np.array([1,2,3,4,5])
>>> a = a.reshape(1, -1)
>>> a[0,2]
3
</code>```

Note, if you are expecting any type of ndarray, then this might not be what you want:

```<code>>>> arr = np.array([[1,2],[3,4]])
>>> arr
array([[1, 2],
       [3, 4]])
>>> arr.reshape(1, -1)
array([[1, 2, 3, 4]])
</code>```

So you may need to add a conditional check:

```<code>>>> if a.ndim < 2:
...     a = a.reshape(1, -1)
...
>>> a
array([[1, 2, 3, 4, 5]])
</code>```

Body:
I have a 1D numpy array like:

a = np.array([1,2,3,4,5])

And I would like to index this a like (as if it's a 1 by 5 matrix, and a[0,2] would be equal to 3):

a[0,2]

Traceback (most recent call last):

  File "<ipython-input-34-2fc0526218b3>", line 1, in <module>
    a[0,1]

IndexError: too many indices for array

I know in MATLAB it's possible, but how to do that in Python? The reason that I need this is coz that a is dynamically generated, sometimes it's a 1D array, sometimes it's a nD array. And I need a unified way of indexing in my loop.

Body:
Use .reshape and pass -1 as the second argument:

>>> a = np.array([1,2,3,4,5])
>>> a = a.reshape(1, -1)
>>> a[0,2]
3

Note, if you are expecting any type of ndarray, then this might not be what you want:

>>> arr = np.array([[1,2],[3,4]])
>>> arr
array([[1, 2],
       [3, 4]])
>>> arr.reshape(1, -1)
array([[1, 2, 3, 4]])

So you may need to add a conditional check:

>>> if a.ndim < 2:
...     a = a.reshape(1, -1)
...
>>> a
array([[1, 2, 3, 4, 5]])


问:
Localized JSF default validators
Is there any way to painlessly localize the default validator messages in JSF 2.0? I know the key is, i. e., "javax.faces.component.UIInput.REQUIRED", but from all I've found, the only way to change them is in a message-bundle, and it is not locale aware like resource-bundle is. I also didn't find any way to override the default validator for

```<code>required="true"
</code>```

so, is there a way to decently localize those messages without writing a customized "required" validator that uses the needed resource-bundle? Not that it's too much work, but I really like the

```<code>required="true"
</code>```

instead of

```<code><h:inputText ...
    <f:validator  ...
</h:inputText ...
</code>```

merely for code shortness etc... The question is general, about default messages though, the required validator is mentioned as an example.

JSF 2.0, GFv3.1, JEE6 (Servlets 3.0, EL 2.2, EJB 3.1, etc if that matters to anyone).

答:
How did you conclude that they are not locale aware? It's definitely locale aware. Just provide your own copies of localized messages with keys as definied in chapter 2.5.2.4 of the JSF 2.0 specification and specify the base name of those message resources in <message-bundle> in faces-config.xml. They're loaded by ResourceBundle, you could just adhere the same bundle file naming convention of name_ll_CC.properties where ll is the language code and CC is the (optional) country code.

By the way, I just checked it once again, Mojarra 2.0.3 ships with builtin message bundles in English (default), German, Spanish, French, Japanese, Korean, Portuguese (Brazilian), Chinese and Taiwanese. What language are you using that you can't use one of the builtin message bundles?

Title: Localized JSF default validators

Body:
Is there any way to painlessly localize the default validator messages in JSF 2.0? I know the key is, i. e., "javax.faces.component.UIInput.REQUIRED", but from all I've found, the only way to change them is in a message-bundle, and it is not locale aware like resource-bundle is. I also didn't find any way to override the default validator for

required="true"

so, is there a way to decently localize those messages without writing a customized "required" validator that uses the needed resource-bundle? Not that it's too much work, but I really like the

required="true"

instead of

<h:inputText ...
    <f:validator  ...
</h:inputText ...

merely for code shortness etc... The question is general, about default messages though, the required validator is mentioned as an example.

JSF 2.0, GFv3.1, JEE6 (Servlets 3.0, EL 2.2, EJB 3.1, etc if that matters to anyone).


问:
How to Output multiple text files based on column name?
I have an excel spreadsheet with the following format.

Excel File

column 1: AAA BBB AAA BBB DDD BBB CCC BBB CCC

column 2: Fox Tiger Monkey  Bird  Cat  Wolf  Dog  Fish Pig

I want to save them to multiple text files using column 1 as the file name ---- "AAA", "BBB", "CCC", "DDD". The content should be column 2. Each text file should have multiple rows.

For example, in text file "AAA", the content should be:

Fox
Monkey

I am now using the following VBA script. But for each text file, I can only generate one row.

```<code>Sub Export_Files()
Dim sExportFolder, sFN
Dim rArticleName As Range
Dim rDisclaimer As Range
Dim oSh As Worksheet
Dim oFS As Object
Dim oTxt As Object

'sExportFolder = path to the folder you want to export to
'oSh = The sheet where your data is stored
sExportFolder = "I:\Projects\2017\Two_Weeks_Vacations\2017\December\Test\EmployeesOnVacation"
Set oSh = Sheet1

Set oFS = CreateObject("Scripting.Filesystemobject")

For Each rArticleName In oSh.UsedRange.Columns("A").Cells
    Set rDisclaimer = rArticleName.Offset(, 1)

    'Add .txt to the article name as a file name
    sFN = rArticleName.Value & ".txt"
    Set oTxt = oFS.OpenTextFile(sExportFolder & "\" & sFN, 2, True)
    oTxt.Write rDisclaimer.Value
    oTxt.Close
Next
End Sub
</code>```

答:
If you can sort, then you can use a base template:

```<code>Public a as String
</code>```

```<code>Sub
    Dim i as Long, lr as Long, strO as String, strN as String
    LR = Cells(Rows.Count, 1).End(xlUp).Row
    For i = i to lr Step 1
        strO = a
        If Cells(i,1).Value = Cells(i-1,1).Value Then
            If a <> "" Then Export_Files 'Calls the Sub that names the file... or you can just name and do that stuff here.
            a = ""
            strO = Cells(i,2).Value
        Else
            strN = Cells(i,2).Value
        End If
        a = strO & " " & strN
    Next i
    Export_Files
    a = ""
End Sub
</code>```

Then need to make a fix to the naming of the Export_Files macro, where you remove the parts that pick the file name and change the total file save name:

```<code>Set oTxt = oFS.OpenTextFile(sExportFolder & "\" & a, 2, True)
</code>```

Body:
I have an excel spreadsheet with the following format.

Excel File

column 1: AAA BBB AAA BBB DDD BBB CCC BBB CCC

column 2: Fox Tiger Monkey  Bird  Cat  Wolf  Dog  Fish Pig

I want to save them to multiple text files using column 1 as the file name ---- "AAA", "BBB", "CCC", "DDD". The content should be column 2. Each text file should have multiple rows.

For example, in text file "AAA", the content should be:

Fox
Monkey

I am now using the following VBA script. But for each text file, I can only generate one row.

Sub Export_Files()
Dim sExportFolder, sFN
Dim rArticleName As Range
Dim rDisclaimer As Range
Dim oSh As Worksheet
Dim oFS As Object
Dim oTxt As Object

'sExportFolder = path to the folder you want to export to
'oSh = The sheet where your data is stored
sExportFolder = "I:\Projects\2017\Two_Weeks_Vacations\2017\December\Test\EmployeesOnVacation"
Set oSh = Sheet1

Set oFS = CreateObject("Scripting.Filesystemobject")

For Each rArticleName In oSh.UsedRange.Columns("A").Cells
    Set rDisclaimer = rArticleName.Offset(, 1)

    'Add .txt to the article name as a file name
    sFN = rArticleName.Value & ".txt"
    Set oTxt = oFS.OpenTextFile(sExportFolder & "\" & sFN, 2, True)
    oTxt.Write rDisclaimer.Value
    oTxt.Close
Next
End Sub

Body:
If you can sort, then you can use a base template:

Public a as String

Sub
    Dim i as Long, lr as Long, strO as String, strN as String
    LR = Cells(Rows.Count, 1).End(xlUp).Row
    For i = i to lr Step 1
        strO = a
        If Cells(i,1).Value = Cells(i-1,1).Value Then
            If a <> "" Then Export_Files 'Calls the Sub that names the file... or you can just name and do that stuff here.
            a = ""
            strO = Cells(i,2).Value
        Else
            strN = Cells(i,2).Value
        End If
        a = strO & " " & strN
    Next i
    Export_Files
    a = ""
End Sub

Then need to make a fix to the naming of the Export_Files macro, where you remove the parts that pick the file name and change the total file save name:

Set oTxt = oFS.OpenTextFile(sExportFolder & "\" & a, 2, True)


问:
How do you tell git to stash the index only?
I have just used git add -p to add a bunch of changes to the index, and I just realised that I missed a change that should've gone into the previous commit.

I can't commit --amend now because I've added all these new changes to the index, and I don't want to use 'git reset' to remove them all from the index as it will take ages to add them all back in again.

What I need is something like git stash that will only stash the index – it should leave the working files alone.  Then I can stash the index, add the missing change, commit it, then pop the stash and have my index back the way it was.

It doesn't look like git stash is able to do this, but am I missing something?  Thanks!

答:
```<code>git stash -k
git stash
git stash apply stash@{1}
git stash drop stash@{1}
</code>```

ContentLicense: CC BY-SA 4.0


问:
Prevent Dagger2 component from recreating on screen rotation
I'm new to Dagger2 dependency injection. I have some difficulties to retain the same component when screen is rotated.

```<code>@Inject
MainActivityPresenterImpl presenter;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    component = DaggerMainActivityComponent.builder()
            .mainActivityModule(new MainActivityModule(this))
            .applicationComponent(TrainningDagger3.get(this).getComponent())
            .build();
    component.inject(this);
    presenter.fetchData();
}
</code>```

I tried to debug the application and I think when new configuration is loaded its creating new instance of component and new instance of the presenter. How I can retain the same component and presenter when screen is rotated. Thank you so much!

答:
You're going to have to decide whether you want your Activity to be destroyed and recreated when the screen rotates (i.e. "the configuration changes"). If you want to handle it yourself, which I recommend, you simply make the change in your AndroidManifest.xml; if you want to handle it through Dagger, you're going to need to save your data in a longer-lived object (such as your ApplicationComponent).

As in the official docs on "Handling Configuration Changes", you can instruct your Activity to simply handle a method call instead of being restarted:

```<code><activity android:name=".MyActivity"
          android:configChanges="orientation|keyboardHidden"
          android:label="@string/app_name">
</code>```

Now, when one of these configurations change, MyActivity does not restart. Instead, the MyActivity receives a call to onConfigurationChanged(). This method is passed a Configuration object that specifies the new device configuration. By reading fields in the Configuration, you can determine the new configuration and make appropriate changes by updating the resources used in your interface.

Importantly, this allows you to keep your ActivityComponent exactly as long-lived as your Activity itself, and can reason better about when your Activity's instance is valid or stale. You will still need to take care of loading and saving your data for Android's multitasking, but that is true no matter how you use Dagger.

If you think it is important to destroy and recreate your Activity on a configuration change, that's fine, but I would caution against using the term "activity component" if your are creating or modifying a component to live longer than a single Activity instance. That would be an atypical usage of the term, and might be very confusing for other developers. Instead, if you want a Dagger component to create and hold state for multiple Activity instances (of multiple activity classes, or multiple instances of the same activity), you should consider putting those objects into your existing ApplicationComponent, or creating a new component (e.g. "SessionComponent") that lives longer than one ActivityComponent but shorter than your ApplicationComponent. If you do this, you'll need to be very careful that nothing in this object holds onto an Activity instance, View, or anything that is permanently associated with a single Activity: That would cause a memory leak, as Android would not be able to garbage-collect those pieces of the Activity while your SessionComponent or ApplicationComponent holds a reference to it.

Body:
I'm new to Dagger2 dependency injection. I have some difficulties to retain the same component when screen is rotated.

@Inject
MainActivityPresenterImpl presenter;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    component = DaggerMainActivityComponent.builder()
            .mainActivityModule(new MainActivityModule(this))
            .applicationComponent(TrainningDagger3.get(this).getComponent())
            .build();
    component.inject(this);
    presenter.fetchData();
}

I tried to debug the application and I think when new configuration is loaded its creating new instance of component and new instance of the presenter. How I can retain the same component and presenter when screen is rotated. Thank you so much!

Body:
You're going to have to decide whether you want your Activity to be destroyed and recreated when the screen rotates (i.e. "the configuration changes"). If you want to handle it yourself, which I recommend, you simply make the change in your AndroidManifest.xml; if you want to handle it through Dagger, you're going to need to save your data in a longer-lived object (such as your ApplicationComponent).

As in the official docs on "Handling Configuration Changes", you can instruct your Activity to simply handle a method call instead of being restarted:

<activity android:name=".MyActivity"
          android:configChanges="orientation|keyboardHidden"
          android:label="@string/app_name">

Now, when one of these configurations change, MyActivity does not restart. Instead, the MyActivity receives a call to onConfigurationChanged(). This method is passed a Configuration object that specifies the new device configuration. By reading fields in the Configuration, you can determine the new configuration and make appropriate changes by updating the resources used in your interface.

Importantly, this allows you to keep your ActivityComponent exactly as long-lived as your Activity itself, and can reason better about when your Activity's instance is valid or stale. You will still need to take care of loading and saving your data for Android's multitasking, but that is true no matter how you use Dagger.

If you think it is important to destroy and recreate your Activity on a configuration change, that's fine, but I would caution against using the term "activity component" if your are creating or modifying a component to live longer than a single Activity instance. That would be an atypical usage of the term, and might be very confusing for other developers. Instead, if you want a Dagger component to create and hold state for multiple Activity instances (of multiple activity classes, or multiple instances of the same activity), you should consider putting those objects into your existing ApplicationComponent, or creating a new component (e.g. "SessionComponent") that lives longer than one ActivityComponent but shorter than your ApplicationComponent. If you do this, you'll need to be very careful that nothing in this object holds onto an Activity instance, View, or anything that is permanently associated with a single Activity: That would cause a memory leak, as Android would not be able to garbage-collect those pieces of the Activity while your SessionComponent or ApplicationComponent holds a reference to it.


问:
numpy function giving incorrect results - checked by hand and excel
I'm writing some functions in numpy for rock physics modelling and have noticed that one of my functions gives erroneous results. The function is my implimentation of Hertz-Mindlin sphere modelling:

Summary of the Hertz-Mindlin model

Here is my function currently:

```<code># Hertz-Mindlin sphere pack model:

import numpy as np

def hertzmindlin(K0, G0, PHIC, P, f=1.0):
'''
Hertz-Mindlin sphere-pack model, adapted from:
'Dvorkin, J. and Nur, A., 1996. Elasticity of high-porosity sandstones:
Theory for two North Sea data sets. Geophysics, 61(5), pp.1363-1370."

Arguments:
K0 = Bulk modulus of mineral in GPa
G0 = Shear modulus of mineral in GPa
PHIC = Critical porosity for mineral-fluid mixture. Calculate using Dvorkin-Nuir (1995) or use literature
P = Confining pressure in GPa
f = Shear modulus correction factor. Default = 1

Results:
V0 = Theoretical poissons ratio of mineral
n = Coordination number of sphere-pack, calculated from Murphy's (1982) empirical relation
K_HM = Hertz-Mindlin effective dry Bulk modulus at pressure, P, in GPa
G_HM = Hertz-Mindlin effective dry Shear modulus at pressure, P, in GPa

'''
V0 = (3*K0-2*G0)/(6*K0+2*G0) # Calculated theoretical poissons ratio of bulk rock
n = 20-(34*PHIC)+(14*(PHIC**2)) # Coordination number at critical porosity (Murphy 1982)
K_HM = (P*(n**2*(1-PHIC)**2*G0**2) / (18*np.pi**2*(1-V0)**2))**(1/3)
G_HM = ((2+3*f-V0*(1+3*f))/(5*(2-V0))) * ((P*(3*n**2*(1-PHIC)**2*G0**2)/(2*np.pi**2*(1-V0)**2)))**(1/3)
return K_HM, G_HM
</code>```

The problem is that when I run this function for inputs of:

K, G, = 36, 45

PHIC = 0.4

P = 0.001

I get a result of K_HM = 1.0, G_HM = 0.49009009009009

The hand calculated and excel calculated values show this is incorrect, I should be outputting K_HM = 0.763265313, G_HM = 1.081083984

I am fairly certain something is going wrong in the function based on the fact that for the inputs K, G, the output G should be larger than K (it is currently smaller)

Any help would be appreciated! I can do this in excel, but ideally want everything running in python.

答:
In Python2, division of integers (using /) returns an integer. For example, 1/3 = 0.
In Python3, division of integers (using /) may return a float.

It appears you are using Python2. To get floating-point division (in both Python2 and Python3), ensure each division operation involves at least one float: for example, change 1/3 to 1.0/3 or 1/3.0 or (acceptable but perhaps less readable, 1/3.):

```<code>import numpy as np
def hertzmindlin(K0, G0, PHIC, P, f=1.0):
    K0, G0 = map(float, (K0, G0))
    V0 = (3*K0-2*G0)/(6*K0+2*G0) # Calculated theoretical poissons ratio of bulk rock
    n = 20-(34*PHIC)+(14*(PHIC**2)) # Coordination number at critical porosity (Murphy 1982)
    K_HM = (P*(n**2*(1-PHIC)**2*G0**2) / (18*np.pi**2*(1-V0)**2))**(1/3.0)
    G_HM = ((2+3*f-V0*(1+3*f))/(5*(2-V0))) * ((P*(3*n**2*(1-PHIC)**2*G0**2)/(2*np.pi**2*(1-V0)**2)))**(1/3.0)
    return K_HM, G_HM

K, G, = 36, 45
PHIC = 0.4
P = 0.001

print(hertzmindlin(K, G, PHIC, P))
</code>```

Alternatively, in later versions of Python2 (such as Python2.7) you could place

```<code>from __future__ import division
</code>```

at the top of your script (before all other import statements) to activate Python3-style floating-point division.

Body:
I'm writing some functions in numpy for rock physics modelling and have noticed that one of my functions gives erroneous results. The function is my implimentation of Hertz-Mindlin sphere modelling:

Summary of the Hertz-Mindlin model

Here is my function currently:

# Hertz-Mindlin sphere pack model:

import numpy as np

def hertzmindlin(K0, G0, PHIC, P, f=1.0):
'''
Hertz-Mindlin sphere-pack model, adapted from:
'Dvorkin, J. and Nur, A., 1996. Elasticity of high-porosity sandstones:
Theory for two North Sea data sets. Geophysics, 61(5), pp.1363-1370."

Arguments:
K0 = Bulk modulus of mineral in GPa
G0 = Shear modulus of mineral in GPa
PHIC = Critical porosity for mineral-fluid mixture. Calculate using Dvorkin-Nuir (1995) or use literature
P = Confining pressure in GPa
f = Shear modulus correction factor. Default = 1

Results:
V0 = Theoretical poissons ratio of mineral
n = Coordination number of sphere-pack, calculated from Murphy's (1982) empirical relation
K_HM = Hertz-Mindlin effective dry Bulk modulus at pressure, P, in GPa
G_HM = Hertz-Mindlin effective dry Shear modulus at pressure, P, in GPa

'''
V0 = (3*K0-2*G0)/(6*K0+2*G0) # Calculated theoretical poissons ratio of bulk rock
n = 20-(34*PHIC)+(14*(PHIC**2)) # Coordination number at critical porosity (Murphy 1982)
K_HM = (P*(n**2*(1-PHIC)**2*G0**2) / (18*np.pi**2*(1-V0)**2))**(1/3)
G_HM = ((2+3*f-V0*(1+3*f))/(5*(2-V0))) * ((P*(3*n**2*(1-PHIC)**2*G0**2)/(2*np.pi**2*(1-V0)**2)))**(1/3)
return K_HM, G_HM

The problem is that when I run this function for inputs of:

K, G, = 36, 45

PHIC = 0.4

P = 0.001

I get a result of K_HM = 1.0, G_HM = 0.49009009009009

The hand calculated and excel calculated values show this is incorrect, I should be outputting K_HM = 0.763265313, G_HM = 1.081083984

I am fairly certain something is going wrong in the function based on the fact that for the inputs K, G, the output G should be larger than K (it is currently smaller)

Any help would be appreciated! I can do this in excel, but ideally want everything running in python.

Body:
In Python2, division of integers (using /) returns an integer. For example, 1/3 = 0.
In Python3, division of integers (using /) may return a float.

It appears you are using Python2. To get floating-point division (in both Python2 and Python3), ensure each division operation involves at least one float: for example, change 1/3 to 1.0/3 or 1/3.0 or (acceptable but perhaps less readable, 1/3.):

import numpy as np
def hertzmindlin(K0, G0, PHIC, P, f=1.0):
    K0, G0 = map(float, (K0, G0))
    V0 = (3*K0-2*G0)/(6*K0+2*G0) # Calculated theoretical poissons ratio of bulk rock
    n = 20-(34*PHIC)+(14*(PHIC**2)) # Coordination number at critical porosity (Murphy 1982)
    K_HM = (P*(n**2*(1-PHIC)**2*G0**2) / (18*np.pi**2*(1-V0)**2))**(1/3.0)
    G_HM = ((2+3*f-V0*(1+3*f))/(5*(2-V0))) * ((P*(3*n**2*(1-PHIC)**2*G0**2)/(2*np.pi**2*(1-V0)**2)))**(1/3.0)
    return K_HM, G_HM

K, G, = 36, 45
PHIC = 0.4
P = 0.001

print(hertzmindlin(K, G, PHIC, P))

Alternatively, in later versions of Python2 (such as Python2.7) you could place

from __future__ import division

at the top of your script (before all other import statements) to activate Python3-style floating-point division.


问:
How to call a JavaScript function named `call` from dart
Is there any way to call a JavaScript function named call() (in a nested object) from Dart or do I have to wait for Dart 2.0 from which the special handling of call() might get removed?

I have a JS Proxy like:

@JS()
class SomethingFancy {
  external String call();
}
```

<p>But as <code>call()</code> can be used to turn an object into a function, it makes it impossible to access the function of the JS object.</p>

<p>If I could, I would change the name of the method in Dart, but that's not supported by <code>package:js</code>:</p>

<pre class="lang-dart prettyprint-override"><code>/// By default the dart name is used. It is not valid to specify a custom
/// [name] for class instance members.
</code>```

The error I get is:

Uncaught Error: NoSuchMethodError: method not found: 'call$0' (J.getSomethingFancy$1$x(...).call$0 is not a function)

If the function didn't exist, the error would look like this:

Uncaught Error: NoSuchMethodError: method not found: 'callMe' (receiver.callMe is not a function)

Other functions on the same object work just fine.

答:
You can prefix call with JS$:

@JS()
class SomethingFancy {
  external String JS$call();
}
```

JS$ can be used as prefix to allow to access to JS names that conflicts with dart keywords.

Body:
Is there any way to call a JavaScript function named call() (in a nested object) from Dart or do I have to wait for Dart 2.0 from which the special handling of call() might get removed?

I have a JS Proxy like:

@JS()
class SomethingFancy {
  external String call();
}

But as call() can be used to turn an object into a function, it makes it impossible to access the function of the JS object.

If I could, I would change the name of the method in Dart, but that's not supported by package:js:

/// By default the dart name is used. It is not valid to specify a custom
/// [name] for class instance members.

The error I get is:

Uncaught Error: NoSuchMethodError: method not found: 'call$0' (J.getSomethingFancy$1$x(...).call$0 is not a function)

If the function didn't exist, the error would look like this:

Uncaught Error: NoSuchMethodError: method not found: 'callMe' (receiver.callMe is not a function)

Other functions on the same object work just fine.

Body:
You can prefix call with JS$:

@JS()
class SomethingFancy {
  external String JS$call();
}

JS$ can be used as prefix to allow to access to JS names that conflicts with dart keywords.


问:
Calling `super()` in parent class
I'm reading Raymond Hettinger's Python’s super() considered super!  About a page in, there's this example:

```<code>class Shape:
    def __init__(self, shapename, **kwds):
        self.shapename = shapename
        super().__init__(**kwds)

class ColoredShape(Shape):
    def __init__(self, color, **kwds):
        self.color = color
        super().__init__(**kwds)

cs = ColoredShape(color='red', shapename='circle')
</code>```

Why is it necessary to call super() in Shape here?  My understanding is that this calls object.__init__(**kwds) since Shape implicitly inherits from object.

Even without that statement, we've already

established shapename already in the parent's __init__,

established the child class's color in an explicit method override,

then invoked the parent's __init__ with super() in ColoredShape.

As far as I can tell, dropping this line produces the same behavior & functionality:

```<code>class Shape:  # (object)
    def __init__(self, shapename, **kwds):
        self.shapename = shapename
        # super().__init__(**kwds)

class ColoredShape(Shape):
    def __init__(self, color, **kwds):
        self.color = color
        super().__init__(**kwds)
    def check(self):
        print(self.color)
        print(self.shapename)

cs = ColoredShape(color='red', shapename='circle')

cs.check()
# red
# circle
</code>```

What is the purpose of super() within Shape here?

答:
The point is cooperative multiple inheritance. The point of the whole entire article is cooperative multiple inheritance, really.

You look at Shape and you don't see any parents besides object. Sure, but that doesn't mean there aren't any siblings, or anything else on the MRO after Shape. super() isn't just for superclasses; it searches for the next implementation of the method in the method resolution order. For example, one of the later classes in the article is

```<code>class MovableColoredShape(ColoredShape, MoveableAdapter):
    pass
</code>```

In this case, Shape.__init__ needs to call super().__init__, or MoveableAdapter.__init__ and all further __init__ calls will be skipped.

Title: Calling `super()` in parent class

Body:
I'm reading Raymond Hettinger's Python’s super() considered super!  About a page in, there's this example:

class Shape:
    def __init__(self, shapename, **kwds):
        self.shapename = shapename
        super().__init__(**kwds)

class ColoredShape(Shape):
    def __init__(self, color, **kwds):
        self.color = color
        super().__init__(**kwds)

cs = ColoredShape(color='red', shapename='circle')

Why is it necessary to call super() in Shape here?  My understanding is that this calls object.__init__(**kwds) since Shape implicitly inherits from object.

Even without that statement, we've already

established shapename already in the parent's __init__,

established the child class's color in an explicit method override,

then invoked the parent's __init__ with super() in ColoredShape.

As far as I can tell, dropping this line produces the same behavior & functionality:

class Shape:  # (object)
    def __init__(self, shapename, **kwds):
        self.shapename = shapename
        # super().__init__(**kwds)

class ColoredShape(Shape):
    def __init__(self, color, **kwds):
        self.color = color
        super().__init__(**kwds)
    def check(self):
        print(self.color)
        print(self.shapename)

cs = ColoredShape(color='red', shapename='circle')

cs.check()
# red
# circle

What is the purpose of super() within Shape here?

Body:
The point is cooperative multiple inheritance. The point of the whole entire article is cooperative multiple inheritance, really.

You look at Shape and you don't see any parents besides object. Sure, but that doesn't mean there aren't any siblings, or anything else on the MRO after Shape. super() isn't just for superclasses; it searches for the next implementation of the method in the method resolution order. For example, one of the later classes in the article is

class MovableColoredShape(ColoredShape, MoveableAdapter):
    pass

In this case, Shape.__init__ needs to call super().__init__, or MoveableAdapter.__init__ and all further __init__ calls will be skipped.


问:
Flatten array to 2D
I know there are a couple of answers on the matter, but as I was trying to make my own, I got very lost on how recursive functions work, here's what I tried :

function flatcoords(arr) {
  for (i = 0; i < arr.length; i++) {
    const value = arr[i];
    if (value.isArray) {
      return flatcoords(value);
    } else {
      return arr;
    }
  }

}

const arr_test = [
  [
    [1, 2],
    [1, 2]
  ],
  [1, 2],
  [1, 2],
  [
    [
      [1, 2],
      [1, 2]
    ]
  ]
];

//wanted_result = [ [1,2],[1,2],[1,2],[1,2],[1,2],[1,2] ]
console.log(flatcoords(arr_test));```

I want the result to be a 2D array, what am I missing in my logic?

答:
First of all, you need to declare all variables before use. Then you could use Array.isArray for a check if an item is an array.

In this case, I suggest to check the first item of the checked element if it is an array as well, in this case flat the array.

As result, an array comes in handy, because not only one element should be returned, but all. And while arrays have more item, you need to append all items to the existing result array.

function flatcoords(array) {
    var result = [],
        value,
        i;

    for (i = 0; i < array.length; i++) {
        value = array[i];
        if (Array.isArray(value) && Array.isArray(value[0])) {
            result = result.concat(flatcoords(value));
        } else {
            result.push(value);
        }
    }
    return result;
}

const arr_test = [[[1, 2], [1, 2]], [1, 2], [1, 2], [[[1, 2], [1, 2]]]];

console.log(flatcoords(arr_test));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: Flatten array to 2D

Body:
I know there are a couple of answers on the matter, but as I was trying to make my own, I got very lost on how recursive functions work, here's what I tried :

function flatcoords(arr) {
  for (i = 0; i < arr.length; i++) {
    const value = arr[i];
    if (value.isArray) {
      return flatcoords(value);
    } else {
      return arr;
    }
  }

}

const arr_test = [
  [
    [1, 2],
    [1, 2]
  ],
  [1, 2],
  [1, 2],
  [
    [
      [1, 2],
      [1, 2]
    ]
  ]
];

//wanted_result = [ [1,2],[1,2],[1,2],[1,2],[1,2],[1,2] ]
console.log(flatcoords(arr_test));

I want the result to be a 2D array, what am I missing in my logic?

Body:
First of all, you need to declare all variables before use. Then you could use Array.isArray for a check if an item is an array.

In this case, I suggest to check the first item of the checked element if it is an array as well, in this case flat the array.

As result, an array comes in handy, because not only one element should be returned, but all. And while arrays have more item, you need to append all items to the existing result array.

function flatcoords(array) {
    var result = [],
        value,
        i;

    for (i = 0; i < array.length; i++) {
        value = array[i];
        if (Array.isArray(value) && Array.isArray(value[0])) {
            result = result.concat(flatcoords(value));
        } else {
            result.push(value);
        }
    }
    return result;
}

const arr_test = [[[1, 2], [1, 2]], [1, 2], [1, 2], [[[1, 2], [1, 2]]]];

console.log(flatcoords(arr_test));

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
error using type converter for application setting
After reading some of the msdn docs I thought I had figured out how to use a custom type as an app setting via the visual studio designer.

The designer stores my string happily enough but I get an error message when I run a unit test to see if I can actually use the setting.

I was getting serialization errors on some of the other types that make up the custom type in question - I made them go away by reluctantly making several properties setters public. BUT the docs suggest that if a Type Converter is supplied that it will be used in lieu of serialization. Must I provide a type converter for every type that makes up the type I want as  a setting?

Cheers,

Berryl

generated code from designer setting

```<code>[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("8 hours")]
public global::Smack.Core.Lib.Domains.Temporal.TimeQuantity WorkQuota_Daily {
    get {
        return ((global::Smack.Core.Lib.Domains.Temporal.TimeQuantity)(this["WorkQuota_Daily"]));
        }
    }
</code>```

unit test and error

```<code>    [Test]
    public void WorkQuota_Daily_CanRead() {
        var setting = Properties.Settings.Default.WorkQuota_Daily;
        Assert.That(setting, Is.EqualTo(TimeQuantity.Hours(8)));
    }
Test failed: System.ArgumentException : The property 'WorkQuota_Daily' could not be created from it's default value.
Error message: There is an error in XML document (1, 1).
at System.Configuration.SettingsPropertyValue.Deserialize()
at System.Configuration.SettingsPropertyValue.get_PropertyValue()
at System.Configuration.SettingsBase.GetPropertyValueByName(String propertyName)
at System.Configuration.SettingsBase.get_Item(String propertyName)
at System.Configuration.ApplicationSettingsBase.GetPropertyValue(String propertyName)
at System.Configuration.ApplicationSettingsBase.get_Item(String propertyName)
C:\Users\Lord & Master\Documents\Projects\Smack\trunk\src\ConstructionAdmin.TestingSupport\Properties\Settings.Designer.cs(211,0): at Smack.ConstructionAdmin.TestingSupport.Properties.Settings.get_WorkQuota_Daily()
General\ApplicationSettingsTests.cs(22,0): at Smack.ConstructionAdmin.TestingSupport.General.ApplicationSettingsTests.WorkQuota_Daily_CanRead()
</code>```

type converter

```<code>public class TimeQuantityTypeConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        if (value is string)
        {
            var v = ((string)value).Split();
            var amt = v[0];
            var unit = v[1];
            var timeSliceFactory = new TimeSliceFactory();
            var map = TimeSliceFactory.GetUnitMap(timeSliceFactory);
            var key = unit.ToLowerInvariant();
            if (!map.ContainsKey(key)) throw new ArgumentException(string.Format("There is no time slice unit key fpr '{0}", key));
            return new TimeQuantity(amt, map[key]);
        }
        return base.ConvertFrom(context, culture, value);
    }

    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(string)) {
            return string.Format("{0} {1}", ((TimeQuantity) value).Amount, ((TimeQuantity) value).Unit.PluralForm);
        }
        return base.ConvertTo(context, culture, value, destinationType);
    }
}
</code>```

settings file (several User settings ommited)

```<code>[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
public sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {

    private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

    public static Settings Default {
        get {
            return defaultInstance;
        }
    }

    [global::System.Configuration.ApplicationScopedSettingAttribute()]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Configuration.DefaultSettingValueAttribute("8 hours")]
    public global::Smack.Core.Lib.Domains.Temporal.TimeQuantity WorkQuota_Daily {
        get {
            return ((global::Smack.Core.Lib.Domains.Temporal.TimeQuantity)(this["WorkQuota_Daily"]));
        }
    }

    [global::System.Configuration.ApplicationScopedSettingAttribute()]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Configuration.DefaultSettingValueAttribute("Monday")]
    public global::System.DayOfWeek StartDay {
        get {
            return ((global::System.DayOfWeek)(this["StartDay"]));
        }
    }
}
</code>```

Update (Fixed!)

Answer goes to the first person that sees what part of the puzzle I was missing. Hint #1 - the original TypeConverter code was fine. Hint # 2 - The System.ComponentModel is pretty powerful!

答:
@Berryl - I got this working (with some modifications, like creating my own TimeQuantity class). Did you remember to add a TypeConverterAttribute to your TimeQuantity class?

```<code>[TypeConverter(typeof(TimeQuantityTypeConverter))]
public class TimeQuantity
{
</code>```

If you set a breakpoint inside your CanConvertFrom(...) and ConvertFrom(...) methods, you should see them hit when you read the property. Without that TypeConverter attribute, I get the same error you got.

Body:
After reading some of the msdn docs I thought I had figured out how to use a custom type as an app setting via the visual studio designer.

The designer stores my string happily enough but I get an error message when I run a unit test to see if I can actually use the setting.

I was getting serialization errors on some of the other types that make up the custom type in question - I made them go away by reluctantly making several properties setters public. BUT the docs suggest that if a Type Converter is supplied that it will be used in lieu of serialization. Must I provide a type converter for every type that makes up the type I want as  a setting?

Cheers,

Berryl

generated code from designer setting

[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("8 hours")]
public global::Smack.Core.Lib.Domains.Temporal.TimeQuantity WorkQuota_Daily {
    get {
        return ((global::Smack.Core.Lib.Domains.Temporal.TimeQuantity)(this["WorkQuota_Daily"]));
        }
    }

unit test and error

    [Test]
    public void WorkQuota_Daily_CanRead() {
        var setting = Properties.Settings.Default.WorkQuota_Daily;
        Assert.That(setting, Is.EqualTo(TimeQuantity.Hours(8)));
    }
Test failed: System.ArgumentException : The property 'WorkQuota_Daily' could not be created from it's default value.
Error message: There is an error in XML document (1, 1).
at System.Configuration.SettingsPropertyValue.Deserialize()
at System.Configuration.SettingsPropertyValue.get_PropertyValue()
at System.Configuration.SettingsBase.GetPropertyValueByName(String propertyName)
at System.Configuration.SettingsBase.get_Item(String propertyName)
at System.Configuration.ApplicationSettingsBase.GetPropertyValue(String propertyName)
at System.Configuration.ApplicationSettingsBase.get_Item(String propertyName)
C:\Users\Lord & Master\Documents\Projects\Smack\trunk\src\ConstructionAdmin.TestingSupport\Properties\Settings.Designer.cs(211,0): at Smack.ConstructionAdmin.TestingSupport.Properties.Settings.get_WorkQuota_Daily()
General\ApplicationSettingsTests.cs(22,0): at Smack.ConstructionAdmin.TestingSupport.General.ApplicationSettingsTests.WorkQuota_Daily_CanRead()

type converter

public class TimeQuantityTypeConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        if (value is string)
        {
            var v = ((string)value).Split();
            var amt = v[0];
            var unit = v[1];
            var timeSliceFactory = new TimeSliceFactory();
            var map = TimeSliceFactory.GetUnitMap(timeSliceFactory);
            var key = unit.ToLowerInvariant();
            if (!map.ContainsKey(key)) throw new ArgumentException(string.Format("There is no time slice unit key fpr '{0}", key));
            return new TimeQuantity(amt, map[key]);
        }
        return base.ConvertFrom(context, culture, value);
    }

    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(string)) {
            return string.Format("{0} {1}", ((TimeQuantity) value).Amount, ((TimeQuantity) value).Unit.PluralForm);
        }
        return base.ConvertTo(context, culture, value, destinationType);
    }
}

settings file (several User settings ommited)

[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
public sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {

    private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

    public static Settings Default {
        get {
            return defaultInstance;
        }
    }

    [global::System.Configuration.ApplicationScopedSettingAttribute()]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Configuration.DefaultSettingValueAttribute("8 hours")]
    public global::Smack.Core.Lib.Domains.Temporal.TimeQuantity WorkQuota_Daily {
        get {
            return ((global::Smack.Core.Lib.Domains.Temporal.TimeQuantity)(this["WorkQuota_Daily"]));
        }
    }

    [global::System.Configuration.ApplicationScopedSettingAttribute()]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Configuration.DefaultSettingValueAttribute("Monday")]
    public global::System.DayOfWeek StartDay {
        get {
            return ((global::System.DayOfWeek)(this["StartDay"]));
        }
    }
}

Update (Fixed!)

Answer goes to the first person that sees what part of the puzzle I was missing. Hint #1 - the original TypeConverter code was fine. Hint # 2 - The System.ComponentModel is pretty powerful!

Body:
@Berryl - I got this working (with some modifications, like creating my own TimeQuantity class). Did you remember to add a TypeConverterAttribute to your TimeQuantity class?

[TypeConverter(typeof(TimeQuantityTypeConverter))]
public class TimeQuantity
{

If you set a breakpoint inside your CanConvertFrom(...) and ConvertFrom(...) methods, you should see them hit when you read the property. Without that TypeConverter attribute, I get the same error you got.


问:
why some types of data refer to the same memory location
Asked such a question. Why only the type only str and boolean with the same variables refer to one memory location:

```<code>a = 'something'
b = 'something'
if a is b: print('True') # True
</code>```

but we did not write anywhere a = b. hence the interpreter saw that the strings are equal to each other and made a reference to one memory cell.

Of course, if we assign a new value to either of these two variables, there will be no conflict, so now the variable will refer to another memory location

```<code>b = 'something more'
if a is b: print('True') # False
</code>```

with type boolean going on all the same

```<code>a = True
b = True
if a is b: print('True') # True
</code>```

I first thought that this happens with all mutable types. But no. There remained one unchangeable type - tuple. But it has a different behavior, that is, when we assign the same values to variables, we already refer to different memory cells. Why does this happen only with tuple of immutable types

```<code>a = (1,9,8)
b = (1,9,8)
if a is b: print('True') # False
</code>```

答:
In Python, == checks for value equality, while is checks if basically its the same object like so:
 id(object) == id(object)

Python has some builtin singletons which it starts off with (I'm guessing lower integers and some commonly used strings)

So, if you dig deeper into your statement

```<code>a = 'something'
b = 'something'
id(a)
# 139702804094704
id(b)
# 139702804094704
a is b
# True
</code>```

But if you change it a bit:

```<code>a = 'something else'
b = 'something else'
id(a)
# 139702804150640
id(b)
# 139702804159152
a is b
# False
</code>```

We're getting False because Python uses different memory location for a and b this time, unlike before.

My guess is with tuples (and someone correct me if I'm mistaken) Python allocates different memory every time you create one.

Body:
Asked such a question. Why only the type only str and boolean with the same variables refer to one memory location:

a = 'something'
b = 'something'
if a is b: print('True') # True

but we did not write anywhere a = b. hence the interpreter saw that the strings are equal to each other and made a reference to one memory cell.

Of course, if we assign a new value to either of these two variables, there will be no conflict, so now the variable will refer to another memory location

b = 'something more'
if a is b: print('True') # False

with type boolean going on all the same

a = True
b = True
if a is b: print('True') # True

I first thought that this happens with all mutable types. But no. There remained one unchangeable type - tuple. But it has a different behavior, that is, when we assign the same values to variables, we already refer to different memory cells. Why does this happen only with tuple of immutable types

a = (1,9,8)
b = (1,9,8)
if a is b: print('True') # False

Body:
In Python, == checks for value equality, while is checks if basically its the same object like so:
 id(object) == id(object)

Python has some builtin singletons which it starts off with (I'm guessing lower integers and some commonly used strings)

So, if you dig deeper into your statement

a = 'something'
b = 'something'
id(a)
# 139702804094704
id(b)
# 139702804094704
a is b
# True

But if you change it a bit:

a = 'something else'
b = 'something else'
id(a)
# 139702804150640
id(b)
# 139702804159152
a is b
# False

We're getting False because Python uses different memory location for a and b this time, unlike before.

My guess is with tuples (and someone correct me if I'm mistaken) Python allocates different memory every time you create one.


问:
CSS gradient border not showing correctly
I want to set half blue and orange for border-color of text input.

I tried using a gradient but it doesn't work.

what is my code problem?

.search {
  width: 550px;
  height: 50px;
  margin-left: 350px;
  border-radius: 20px;
  outline: none;
  margin-top: 70px;
  border: solid;
  border-image: linear-gradient(to right, rgb(254, 113, 53) 50%, rgb(55, 154, 214) 50%);
  font-size: 20px;
  text-align: center;
  transition: all 0.2s linear;
}

.search:hover,
.search:focus {
  border: #4cbea5 solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <form method="post">
    <input type="Search" class="search" placeholder="Search">
  </form>
</div></code>```

答:
To get the half orange, half blue gradient on the border you are looking for, make use of border-image-slice property and apply the blue and orange border-image on the search class. You can look at the clean border gradient and the smooth transition on hover.
Hope, it helps.

.search{
  width: 550px;
  height: 50px;
  margin-left: 350px;
  border-radius: 20px;
  outline: none;
  margin-top: 70px;
  border: solid;
  border-image: linear-gradient(to right, #4cbea5 0%, orange 100%);
  border-image-slice: 1;
  font-size: 20px;
  text-align: center;
   transition: all 0.2s linear;
}
.search:hover , .search:focus{
border: #4cbea5 solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
    <form method="post">
    <input type="Search" class="search" placeholder="Search">
    </form>
    </div></code>```

Body:
I want to set half blue and orange for border-color of text input.

I tried using a gradient but it doesn't work.

what is my code problem?

.search {
  width: 550px;
  height: 50px;
  margin-left: 350px;
  border-radius: 20px;
  outline: none;
  margin-top: 70px;
  border: solid;
  border-image: linear-gradient(to right, rgb(254, 113, 53) 50%, rgb(55, 154, 214) 50%);
  font-size: 20px;
  text-align: center;
  transition: all 0.2s linear;
}

.search:hover,
.search:focus {
  border: #4cbea5 solid;
}

  <form method="post">
    <input type="Search" class="search" placeholder="Search">
  </form>

Body:
To get the half orange, half blue gradient on the border you are looking for, make use of border-image-slice property and apply the blue and orange border-image on the search class. You can look at the clean border gradient and the smooth transition on hover.
Hope, it helps.

.search{
  width: 550px;
  height: 50px;
  margin-left: 350px;
  border-radius: 20px;
  outline: none;
  margin-top: 70px;
  border: solid;
  border-image: linear-gradient(to right, #4cbea5 0%, orange 100%);
  border-image-slice: 1;
  font-size: 20px;
  text-align: center;
   transition: all 0.2s linear;
}
.search:hover , .search:focus{
border: #4cbea5 solid;
}

<div>
    <form method="post">
    <input type="Search" class="search" placeholder="Search">
    </form>
    </div>