问:
Python collections.Counter, how to avoid double lookup
Trying to learn python here:

Suppose I have a very large Counter object where I want to change the value of a particular key if that value is greater than 0. So something like this:

```<code>from collections import Counter
...
A = Counter(huge_list)
...
if (A[some_key] > 0):
    ...
    A[some_key] -= 1
    ...
...
</code>```

My question is, how do I avoid the double lookup for the same value A[some_key] ? The way that would have happened in C++ for example would be to return a reference to A[some_key] and then change the value pointed to by that reference, so probably something like this:

```<code>#include <iostream>
#include <string>
#include <map>

using namespace std;

int main()
{
  map<string, int> A = { {"key", 1}, {"key2", 2}};

  int &a = A["key"];
  if ( a > 0 ) {
       a--;
  }
  cout << A["key"] << endl;
}
</code>```

which will happily print 0.

I believe the problem here is that the values of Counter are immutable objects; doing:

```<code>a = A[some_key]
</code>```

"a" will be a reference to object A[some_key]. But a subsequent:

```<code>a-=1
</code>```

will simply assign "a" to another int object with the same value lowered by one and A[some_key] will remain unchanged.

I suppose one solution would be to have a defaultdict with values that are lists of a single integer; lists are mutable therefore I could just delete the integer value and insert a new one decremented by 1 and A[some_key] would change this time. But is there a better way?

That probably also means the problem I'm describing here should be common for every iterable collection of immutable objects?

What are your thoughts?

答:
You can avoid one of three lookups by using max(0, ...) instead of if ... > 0: ....

```<code>>>> def f(c):
...     if c['a'] > 0:
...         c['a'] -= 1

>>> def g(c):
...     c['a'] = max(0, c['a'] - 1)

>>> import dis
>>> dis.dis(f)
  2           0 LOAD_FAST                0 (c)
              2 LOAD_CONST               1 ('a')
              <b>4 BINARY_SUBSCR</b>
              6 LOAD_CONST               2 (0)
              8 COMPARE_OP               4 (>)
             10 POP_JUMP_IF_FALSE       28

  3          12 LOAD_FAST                0 (c)
             14 LOAD_CONST               1 ('a')
             16 DUP_TOP_TWO
             <b>18 BINARY_SUBSCR</b>
             20 LOAD_CONST               3 (1)
             22 INPLACE_SUBTRACT
             24 ROT_THREE
             <b>26 STORE_SUBSCR</b>
             28 LOAD_CONST               0 (None)
             30 RETURN_VALUE
>>> dis.dis(g)
  2           0 LOAD_GLOBAL              0 (max)
              2 LOAD_CONST               1 (0)
              4 LOAD_FAST                0 (c)
              6 LOAD_CONST               2 ('a')
              <b>8 BINARY_SUBSCR</b>
             10 LOAD_CONST               3 (1)
             12 BINARY_SUBTRACT
             14 CALL_FUNCTION            2
             16 LOAD_FAST                0 (c)
             18 LOAD_CONST               2 ('a')
             <b>20 STORE_SUBSCR</b>
             22 LOAD_CONST               0 (None)
             24 RETURN_VALUE
</code>```

BINARY_SUBSCR reads c['a'] and STORE_SUBSCR assigns to c['a'].

This was using Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32.

But this does not mean that one or the other version is faster. You'll have to do some measurements to find out.

Body:
Trying to learn python here:

Suppose I have a very large Counter object where I want to change the value of a particular key if that value is greater than 0. So something like this:

from collections import Counter
...
A = Counter(huge_list)
...
if (A[some_key] > 0):
    ...
    A[some_key] -= 1
    ...
...

My question is, how do I avoid the double lookup for the same value A[some_key] ? The way that would have happened in C++ for example would be to return a reference to A[some_key] and then change the value pointed to by that reference, so probably something like this:

#include <iostream>
#include <string>
#include <map>

using namespace std;

int main()
{
  map<string, int> A = { {"key", 1}, {"key2", 2}};

  int &a = A["key"];
  if ( a > 0 ) {
       a--;
  }
  cout << A["key"] << endl;
}

which will happily print 0.

I believe the problem here is that the values of Counter are immutable objects; doing:

a = A[some_key]

"a" will be a reference to object A[some_key]. But a subsequent:

a-=1

will simply assign "a" to another int object with the same value lowered by one and A[some_key] will remain unchanged.

I suppose one solution would be to have a defaultdict with values that are lists of a single integer; lists are mutable therefore I could just delete the integer value and insert a new one decremented by 1 and A[some_key] would change this time. But is there a better way?

That probably also means the problem I'm describing here should be common for every iterable collection of immutable objects?

What are your thoughts?

Body:
You can avoid one of three lookups by using max(0, ...) instead of if ... > 0: ....

>>> def f(c):
...     if c['a'] > 0:
...         c['a'] -= 1

>>> def g(c):
...     c['a'] = max(0, c['a'] - 1)

>>> import dis
>>> dis.dis(f)
  2           0 LOAD_FAST                0 (c)
              2 LOAD_CONST               1 ('a')
              4 BINARY_SUBSCR
              6 LOAD_CONST               2 (0)
              8 COMPARE_OP               4 (>)
             10 POP_JUMP_IF_FALSE       28

  3          12 LOAD_FAST                0 (c)
             14 LOAD_CONST               1 ('a')
             16 DUP_TOP_TWO
             18 BINARY_SUBSCR
             20 LOAD_CONST               3 (1)
             22 INPLACE_SUBTRACT
             24 ROT_THREE
             26 STORE_SUBSCR
             28 LOAD_CONST               0 (None)
             30 RETURN_VALUE
>>> dis.dis(g)
  2           0 LOAD_GLOBAL              0 (max)
              2 LOAD_CONST               1 (0)
              4 LOAD_FAST                0 (c)
              6 LOAD_CONST               2 ('a')
              8 BINARY_SUBSCR
             10 LOAD_CONST               3 (1)
             12 BINARY_SUBTRACT
             14 CALL_FUNCTION            2
             16 LOAD_FAST                0 (c)
             18 LOAD_CONST               2 ('a')
             20 STORE_SUBSCR
             22 LOAD_CONST               0 (None)
             24 RETURN_VALUE

BINARY_SUBSCR reads c['a'] and STORE_SUBSCR assigns to c['a'].

This was using Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32.

But this does not mean that one or the other version is faster. You'll have to do some measurements to find out.


来源: stackexchange

问:
how to end streamtokenizer loop when reading tokens?
I know  "while (((str.nextToken()!=str.TT_EOL)))" is an infinite loop, but I want to know how can I end this loop in a similar way that in StringTokenizer as "while (st.hasMoreTokens())", it only needs to read 20 tokens, this is my code:
Help really appreciated:</p>

```<code>    import java.io.*;
    import java.util.Arrays;

    public class StonePile {

    public static void main(String args[]) throws IOException {
        StreamTokenizer str = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        //int diff = 0;
        str.nextToken();
        int[] array = new int[(int) str.nval + 1];
        int array2[] = new int[array.length - 1];
        //System.out.println(array.length);
        int i = 0;
        int diff = 0;

        while (((str.nextToken() != str.TT_EOL))) {
            if (str.ttype == StreamTokenizer.TT_NUMBER) {
                System.out.println(i);
                array[i++] = (int) str.nval;

            }
//            if (i > 4) {
//                break;
//            }
        }

        for (int j = 0; j < array.length - 2; j++) {
            diff = Math.abs(array[j + 1] - array[j]);
            array2[j] = diff;
            // System.out.println("El array es en" + j+" es"+ array2[j]);
        }

        Arrays.sort(array2);
        System.out.println(array2[1]);
    }
}
</code>```

答:
If you want the first 20 any tokens use:

```<code>for (int k = 0; k < 20 && str.nextToken() != str.TT_EOL; k++) {
    if (str.ttype == StreamTokenizer.TT_NUMBER) {
        System.out.println(i);
        array[i++] = (int) str.nval;
    }
}
</code>```

If you want the first 20 TT_NUMBER use:

```<code>int k = 0;
while (k < 20 && str.nextToken() != str.TT_EOL) {
    if (str.ttype == StreamTokenizer.TT_NUMBER) {
        System.out.println(i);
        array[i++] = (int) str.nval;
        k++;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I know  "while (((str.nextToken()!=str.TT_EOL)))" is an infinite loop, but I want to know how can I end this loop in a similar way that in StringTokenizer as "while (st.hasMoreTokens())", it only needs to read 20 tokens, this is my code:
Help really appreciated:

    import java.io.*;
    import java.util.Arrays;

    public class StonePile {

    public static void main(String args[]) throws IOException {
        StreamTokenizer str = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        //int diff = 0;
        str.nextToken();
        int[] array = new int[(int) str.nval + 1];
        int array2[] = new int[array.length - 1];
        //System.out.println(array.length);
        int i = 0;
        int diff = 0;

        while (((str.nextToken() != str.TT_EOL))) {
            if (str.ttype == StreamTokenizer.TT_NUMBER) {
                System.out.println(i);
                array[i++] = (int) str.nval;

            }
//            if (i > 4) {
//                break;
//            }
        }

        for (int j = 0; j < array.length - 2; j++) {
            diff = Math.abs(array[j + 1] - array[j]);
            array2[j] = diff;
            // System.out.println("El array es en" + j+" es"+ array2[j]);
        }

        Arrays.sort(array2);
        System.out.println(array2[1]);
    }
}

Body:
If you want the first 20 any tokens use:

for (int k = 0; k < 20 && str.nextToken() != str.TT_EOL; k++) {
    if (str.ttype == StreamTokenizer.TT_NUMBER) {
        System.out.println(i);
        array[i++] = (int) str.nval;
    }
}

If you want the first 20 TT_NUMBER use:

int k = 0;
while (k < 20 && str.nextToken() != str.TT_EOL) {
    if (str.ttype == StreamTokenizer.TT_NUMBER) {
        System.out.println(i);
        array[i++] = (int) str.nval;
        k++;
    }
}


问:
Prevent child from assuming full width of dynamic width parent
I have a container, and the width of this container is determined by either max-width or the width of its widest child.

How do I force each child to assume the width of its content while maintaining a single column of elements?

In the example below, how do I make the abc elements, outlined by the limegreen border, only as wide as their content (i.e. abc)?

#container {
  display: inline-block;
box-sizing: border-box;
border: solid orange 2px;
}

.child {
box-sizing: border-box;
border: solid limegreen 2px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='container'>
  <div class='child'>abcdefghi</div>
  <div class='child'>abc</div>
  <div class='child'>abc</div>
</div></code>```

答:
a flexbox layout will do the job

#container {
  display: inline-flex;
  flex-direction: column;
  align-items:flex-start; /* OR flex-end */
  border: solid orange 2px;
}

.child {
  border: solid limegreen 2px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='container'>
  <div class='child'>abcdefghi</div>
  <div class='child'>abc</div>
  <div class='child'>abc</div>
</div></code>```

Or display:table :

#container {
  display: inline-block;
  border: solid orange 2px;
}

.child {
  border: solid limegreen 2px;
  display:table;
  /* margin-left:auto to push to the right */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='container'>
  <div class='child'>abcdefghi</div>
  <div class='child'>abc</div>
  <div class='child'>abc</div>
</div></code>```

Even float will do the job:

#container {
  display: inline-block;
  border: solid orange 2px;
}

.child {
  border: solid limegreen 2px;
  float:left;
  clear:left;
  /* OR right for both */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='container'>
  <div class='child'>abcdefghi</div>
  <div class='child'>abc</div>
  <div class='child'>abc</div>
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a container, and the width of this container is determined by either max-width or the width of its widest child.

How do I force each child to assume the width of its content while maintaining a single column of elements?

In the example below, how do I make the abc elements, outlined by the limegreen border, only as wide as their content (i.e. abc)?

#container {
  display: inline-block;
box-sizing: border-box;
border: solid orange 2px;
}

.child {
box-sizing: border-box;
border: solid limegreen 2px;
}

abcdefghi

abc

abc

Body:
a flexbox layout will do the job

#container {
  display: inline-flex;
  flex-direction: column;
  align-items:flex-start; /* OR flex-end */
  border: solid orange 2px;
}

.child {
  border: solid limegreen 2px;
}

<div id='container'>
  <div class='child'>abcdefghi</div>
  <div class='child'>abc</div>
  <div class='child'>abc</div>
</div>

Or display:table :

#container {
  display: inline-block;
  border: solid orange 2px;
}

.child {
  border: solid limegreen 2px;
  display:table;
  /* margin-left:auto to push to the right */
}

<div id='container'>
  <div class='child'>abcdefghi</div>
  <div class='child'>abc</div>
  <div class='child'>abc</div>
</div>

Even float will do the job:

#container {
  display: inline-block;
  border: solid orange 2px;
}

.child {
  border: solid limegreen 2px;
  float:left;
  clear:left;
  /* OR right for both */
}

<div id='container'>
  <div class='child'>abcdefghi</div>
  <div class='child'>abc</div>
  <div class='child'>abc</div>
</div>


问:
I have a list of inputs type file and it accept image only .. How can i view an image every time i add one? using onchange method
i wrote this code and its working but when i choose image it only appear in front of the first element .

```<code><html lang="en">
<head>
    <title>Change image on select new image from file input</title>
</head>
<body>
    <ul>
        <li>
            <input type="file" accept=".png, .jpg, .jpeg" onchange="loadFile(event)">
            <img class="output" width="100px" />
        </li>
        <li>
            <input type="file" accept=".png, .jpg, .jpeg" onchange="loadFile(event)">
            <img class="output" width="100px" />
        </li>
        <li>
            <input type="file" accept=".png, .jpg, .jpeg" onchange="loadFile(event)">
            <img class="output" width="100px" />
        </li>
    </ul>

<script type="text/javascript">
    var loadFile = function(event) {
        var output = document.getElementsByClassName('output')[0];
        output.src = URL.createObjectURL(event.target.files[0]);
    };
</script>

</code>```

I just want every image to appear in front of its input.

答:
With Jquery, you can add as many input as you want.

  <title>Change image on select new image from file input</title>

      <input type="file" accept=".png, .jpg, .jpeg">

      <input type="file" accept=".png, .jpg, .jpeg">

      <input type="file" accept=".png, .jpg, .jpeg">

  ```

Body:
i wrote this code and its working but when i choose image it only appear in front of the first element .

    <title>Change image on select new image from file input</title>

            <input type="file" accept=".png, .jpg, .jpeg" onchange="loadFile(event)">

            <input type="file" accept=".png, .jpg, .jpeg" onchange="loadFile(event)">

            <input type="file" accept=".png, .jpg, .jpeg" onchange="loadFile(event)">

I just want every image to appear in front of its input.

Body:
With Jquery, you can add as many input as you want.

<html lang="en">

<head>
  <title>Change image on select new image from file input</title>
</head>

<body>
  <ul>
    <li>
      <input type="file" accept=".png, .jpg, .jpeg">
      <img class="output" width="100px" />
    </li>
    <li>
      <input type="file" accept=".png, .jpg, .jpeg">
      <img class="output" width="100px" />
    </li>
    <li>
      <input type="file" accept=".png, .jpg, .jpeg">
      <img class="output" width="100px" />
    </li>
  </ul>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script type="text/javascript">
    $("input[type=file]").on("change", function(e) {
      $(this).next().attr("src", URL.createObjectURL(e.target.files[0]));
    })
  </script>


问:
How to explain undefined behavior to know-it-all newbies?
There'a a handful of situations that the C++ standard attributes as undefined behavior. For example if I allocate with new[], then try to free with delete (not delete[]) that's undefined behavior - anything can happen - it might work, it might crash nastily, it might corrupt something silently and plant a timed problem.

It's so problematic to explain this anything can happen part to newbies. They start "proving" that "this works" (because it really works on the C++ implementation they use) and ask "what could possibly be wrong with this"? What concise explanation could I give that would motivate them to just not write such code?

答:
Both the C and C++ Standards use the term "Undefined Behavior" to refer to situations in which it may be useful for different implementations to process constructs in differing, incompatible, fashions, some of which will behave predictably but some of which may not.  Both use the same terminology to describe UB, and while I don't know of any published Rationale for C++ Standards, the Rationale for the C Standard says:

Undefined behavior gives the implementor license not to catch certain program errors that are difficult to diagnose. It also identifies areas of possible conforming language extension: the implementor may augment the language by providing a definition of the officially undefined behavior."

Note that many actions which were classified as Undefined Behavior by the C Standard were considered fully defined on many if not all implementations, but the authors of the Standard wanted to give implementors targeting unusual platforms or application fields the ability to deviate from the normal behaviors if doing so would benefit their customers.  Such freedom was not intended to invite arbitrary and capricious deviations from precedent that make it harder for programmers to quickly and easily do what needed to be done.

Unfortunately, many programmers who use gcc and clang don't understand their needs as well as the maintainers of those compilers, who recognize that that since the Standard avoids mandating anything that would impair the efficiency of applications that will never receive maliciously-crafted inputs, or will only run in contexts where even malicious programs would be unable to damage anything, that implies that there's no need for any implementations to allow programmers to easily and efficiently write programs that are suitable for use in other contexts.

ContentLicense: CC BY-SA 2.5


问:
asp.net ExpressionBuilder: Possible to wire up an event?
I have used ExpressionBuilders here and there within my asp.net markup to return simple data types.

Does anyone have any ideas how an ExpressionBuilder might be used to wire up an event inline? Or can ExpressionBuilders only return literals?

I would like to wire up the OnLoad event (or any event) by creating an ExpressionBuilder (named AutoBind in my example). Any ideas if this can be done?

```<code><asp:DropDownList ID="DropDownList1" runat="server"
    DataSource='<%# GetRecords() %>'
    DataTextField="Name" DataValueField="ID"
    OnLoad="<%$ AutoBind: this.DataBind() %>" />
</code>```

答:
instead of using expression builder you can call any of the event method defined in your code which has the reuqired signature of event handler

in the event handle event arguments you can identify the object and data and manipulate control as you want

OwnerDisplayName: Andrew Robinson

Body:
I have used ExpressionBuilders here and there within my asp.net markup to return simple data types.

Does anyone have any ideas how an ExpressionBuilder might be used to wire up an event inline? Or can ExpressionBuilders only return literals?

I would like to wire up the OnLoad event (or any event) by creating an ExpressionBuilder (named AutoBind in my example). Any ideas if this can be done?

<asp:DropDownList ID="DropDownList1" runat="server"
    DataSource='<%# GetRecords() %>'
    DataTextField="Name" DataValueField="ID"
    OnLoad="<%$ AutoBind: this.DataBind() %>" />

LastEditorDisplayName: Andrew Robinson

OwnerDisplayName: scorpio


问:
Loop through an array in JavaScript
In Java, you can use a for loop to traverse objects in an array as follows:

```<code>String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray) {
    // Do something
}
</code>```

Can I do the same in JavaScript?

答:
There is a way to do it where you have very little implicit scope in your loop and do away with extra variables.

```<code>var i = 0,
     item;

// Note this is weak to sparse arrays or falsey values
for ( ; item = myStringArray[i++] ; ){
    item; // This is the string at the index.
}
</code>```

Or if you really want to get the id and have a really classical for loop:

```<code>var i = 0,
    len = myStringArray.length; // Cache the length

for ( ; i < len ; i++ ){
    myStringArray[i]; // Don't use this if you plan on changing the length of the array
}
</code>```

Modern browsers all support iterator methods forEach, map, reduce, filter and a host of other methods on the Array prototype.

Title: Loop through an array in JavaScript

Body:
In Java, you can use a for loop to traverse objects in an array as follows:

String[] myStringArray = {"Hello", "World"};
for (String s : myStringArray) {
    // Do something
}

Can I do the same in JavaScript?

Body:
There is a way to do it where you have very little implicit scope in your loop and do away with extra variables.

var i = 0,
     item;

// Note this is weak to sparse arrays or falsey values
for ( ; item = myStringArray[i++] ; ){
    item; // This is the string at the index.
}

Or if you really want to get the id and have a really classical for loop:

var i = 0,
    len = myStringArray.length; // Cache the length

for ( ; i < len ; i++ ){
    myStringArray[i]; // Don't use this if you plan on changing the length of the array
}

Modern browsers all support iterator methods forEach, map, reduce, filter and a host of other methods on the Array prototype.


答:
you're overloading on the first  element every time the file changes. It's better you find the  next to the target input element:

```<code>var loadFile = function(event) {
    var output = event.target.nextElementSibling;
    output.src = URL.createObjectURL(event.target.files[0]);
};
</code>```

EDIT: to include for your question in the comment

To create new input elements in JS and implement the same behavior as the other input elements, you will need to create not just the input element but the whole li node just like the structure of the existing html and append it to the ul in the DOM. Note that if the html structure changes, nextElementSibling may fail to find the corresponding img tag.

```<code><script type="text/javascript">

    var loadFile = function(event) {
        var output = event.target.nextElementSibling;
        output.src = URL.createObjectURL(event.target.files[0]);
    };

    const input = document.createElement('INPUT');
    input.type = 'file';
    input.accept = '.png, .jpg, .jpeg';
    input.onchange = loadFile;

    const img = document.createElement('IMG');
    img.width = '100';

    const li = document.createElement('LI');
    li.appendChild(input);
    li.appendChild(img);

    const ul = document.querySelector('ul');
    ul.appendChild(li);

</script>
</code>```

Title: I have a list of inputs type file and it accept image only .. How can i view an image every time i add one? using onchange method

Body:
you're overloading on the first <img> element every time the file changes. It's better you find the <img> next to the target input element:

var loadFile = function(event) {
    var output = event.target.nextElementSibling;
    output.src = URL.createObjectURL(event.target.files[0]);
};

EDIT: to include for your question in the comment

To create new input elements in JS and implement the same behavior as the other input elements, you will need to create not just the input element but the whole li node just like the structure of the existing html and append it to the ul in the DOM. Note that if the html structure changes, nextElementSibling may fail to find the corresponding img tag.

<script type="text/javascript">

    var loadFile = function(event) {
        var output = event.target.nextElementSibling;
        output.src = URL.createObjectURL(event.target.files[0]);
    };

    const input = document.createElement('INPUT');
    input.type = 'file';
    input.accept = '.png, .jpg, .jpeg';
    input.onchange = loadFile;

    const img = document.createElement('IMG');
    img.width = '100';

    const li = document.createElement('LI');
    li.appendChild(input);
    li.appendChild(img);

    const ul = document.querySelector('ul');
    ul.appendChild(li);

</script>


问:
Is there a built in way of efficiently finding if a vector is in a vector array and if so what # variable it is
Hello I am creating a procedurally generated cave generation script and I have gotten down all the perlin noise garbage out of the way and am trying to transform the vertices into a mesh . I understand that I need to declare the faces for it and need some form of marching cubes algorithm. For me to know which direction to render the face in I need my script to be aware of all the vertices around it by searching through the vertices. Is there any way my script can efficiently search through a vector3 array to find if a vector3 is in there and if so what place in the array is the Vector3 in?</p>

答:
If you're using a triangulation lookup table based implementation of marching cubes, you could store a normal vector alongside the face in the same table entry. A video by Sebastian Lague mentions using such a table. I'm not exactly sure where he downloaded it from, but he includes it in his repo which is MIT licensed. Video, Table (EDIT: The order of a triangle's vertices alone may be sufficient to define its direction, and you may not need an explicit normal vector)

Also heads up: Old Perlin noise tends to be visibly grid aligned. Most times I see it used, appear to be because a library provided it or because it was mentioned in a tutorial, and not because it was actually the best choice for the application. Simplex-type noises generally produce less grid-aligned results. It's straightforward to import external noise into Unity. It looks like you might need to anyway, if your implementation depends on 3D noise. Here are the noises from my repo that use an open implementation for 3D, a tailored gradient table, and rotated evaluators that are good for terrain. There are a lot of other options out there too, though they may not have these aspects in particular. Note that the range is [-1,1] not [0,1] so if your current noise is [0, 1], you might need to do noise(...) * 0.5 + 0.5 to correct that. Choose the 2F version if you have a lot of octaves, or the 2S version if you have one octave or are doing ridged noise.


问:
Notify transmission is complete over 20 bytes onCharactersitcChanged BLE
I'm trying to fetch data from a Bluetooth LE device that sends data exceeding the 20 bytes which seems to be the limit on how much data can be received at once when onCharacteristicChanged is called.

So if the device sends 80 bytes of data upon request then onCharacteristicChanged is called four times.

My question is, is there a way to tell when all the bytes have been received so I can request for more data immediately?

EDIT

Here is my code

```<code>private final BluetoothGattCallback mGattCallback =
            new BluetoothGattCallback() {
                @Override
                public void onConnectionStateChange(BluetoothGatt gatt, int status,
                                                    int newState) {
                    String intentAction;
                    Log.d(TAG,"state:"+newState+" status:"+status+" xxx");
                    if (newState == BluetoothProfile.STATE_CONNECTED) {

                        mBluetoothGatt.requestMtu(517);

                        intentAction = ACTION_GATT_CONNECTED;
                        initState = INIT_STATE.CONNECTED;
                        //broadcastUpdate(intentAction);
                        Log.i(TAG, "Connected to GATT server. xxx");
                        Log.i(TAG, "Attempting to start service discovery xxx:" +
                                mBluetoothGatt.discoverServices());
                        Log.d(TAG,"xxx "+mBluetoothGatt.getDevice().getAddress());

                        gattConnected = true;
                        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
                            mBluetoothGatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH);
                        }

                    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {

                        Log.i(TAG, "Disconnected from GATT server. xxx "+mBluetoothGatt.getDevice().getAddress());
                        mBluetoothGatt.close();
                        deviceList.remove(0);
                        if (deviceList.size() > 0) {

                            connectToDevice(0);
                        }
                    }
                }

                @Override
                // New services discovered
                public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                    if (status == BluetoothGatt.GATT_SUCCESS) {
                        //broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
                        boolean foundMatch = false;
                        services = mBluetoothGatt.getServices();
                        for (BluetoothGattService service : services) {
                            Log.d(TAG,"Service UUID xxx:"+service.getUuid());
                            if (service.getUuid().equals(SERVICE_UUID)) {
                                foundMatch = true;
                                //*
                                mService = service;
                                mWriteCharacteristic = service.getCharacteristic(WRITE_UUID);
                                mReadCharacteristic = service.getCharacteristic(READ_UUID);
                                mCreditCharacteristic = service.getCharacteristic(WRITE_UUID_2);
                                setCharacteristicNotification(mReadCharacteristic,true);

                                newData = true;
//There is a delay for this write because a mode request is sent first from onDescriptorWrite
                                Thread t = new Thread(new Runnable() {
                                    @Override
                                    public void run() {

                                        try {
                                            Thread.sleep(150);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                        byte[] infoRequest = {0x00, 0x02, 0x04, 0x00};
                                        write(infoRequest);
                                    }
                                });
                                t.start();
                                break;
                            }
                        }

                    } else {
                        Log.w(TAG, "onServicesDiscovered received: xxx " + status);
                    }
                }
                @Override
                public void onCharacteristicChanged(BluetoothGatt gatt,
                                                    BluetoothGattCharacteristic characteristic) {
                    //Log.d(TAG,"Charac changed..... xxx");

                    byte[] data = characteristic.getValue();
                    int dataSize = data.length;

                    System.arraycopy(data,0,rawBytes,bufferIndex,dataSize);
                    bufferIndex+=dataSize;
// The only way I can tell all the data has been received right now is to check the chunk size.
                    if (dataSize != 20) {
                        Log.d(TAG,"new data xxx");
                        newData = false;
                        bufferIndex = 0;

                        processData();
                    }
                }

                @Override
                public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
                    if (status == BluetoothGatt.GATT_SUCCESS) {
                        //if (descriptor.getCharacteristic().getUuid().equals(UUID_TARGET_CHARACTERISTIC)) {
                            Log.d(TAG, "Successfully subscribed xxx");
                        //}
                        // first thing I send is mode select request.
                        byte[] infoRequest = {0x06};
                        writeChangeMode(infoRequest);

                    } else {
                        Log.e(TAG, "Error subscribing");
                    }
                }

                @Override
                public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
                    if (status == BluetoothGatt.GATT_SUCCESS) {
                        //Write operation successful - process with next chunk!
                        Log.d(TAG,"Write successful xxx");
                    }
                }
                @Override
                public void onMtuChanged(BluetoothGatt gatt, int mtu, int status)                   {
                   super.onMtuChanged(gatt, mtu, status);
                   if ( status == BluetoothGatt.GATT_SUCCESS )
                      {
                          Log.d("TAG","call onMtuChanged "+status);
                      }
                }
            };

</code>```

答:
Use https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#requestMtu(int) to attempt to increase the MTU. The notification maximum size is MTU - 3.

There is no procedure defined in the Bluetooth standard to "tell when all bytes have been received" nor "request more data". That is application specific.

Body:
I'm trying to fetch data from a Bluetooth LE device that sends data exceeding the 20 bytes which seems to be the limit on how much data can be received at once when onCharacteristicChanged is called.

So if the device sends 80 bytes of data upon request then onCharacteristicChanged is called four times.

My question is, is there a way to tell when all the bytes have been received so I can request for more data immediately?

EDIT

Here is my code

private final BluetoothGattCallback mGattCallback =
            new BluetoothGattCallback() {
                @Override
                public void onConnectionStateChange(BluetoothGatt gatt, int status,
                                                    int newState) {
                    String intentAction;
                    Log.d(TAG,"state:"+newState+" status:"+status+" xxx");
                    if (newState == BluetoothProfile.STATE_CONNECTED) {

                        mBluetoothGatt.requestMtu(517);

                        intentAction = ACTION_GATT_CONNECTED;
                        initState = INIT_STATE.CONNECTED;
                        //broadcastUpdate(intentAction);
                        Log.i(TAG, "Connected to GATT server. xxx");
                        Log.i(TAG, "Attempting to start service discovery xxx:" +
                                mBluetoothGatt.discoverServices());
                        Log.d(TAG,"xxx "+mBluetoothGatt.getDevice().getAddress());

                        gattConnected = true;
                        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
                            mBluetoothGatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH);
                        }

                    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {

                        Log.i(TAG, "Disconnected from GATT server. xxx "+mBluetoothGatt.getDevice().getAddress());
                        mBluetoothGatt.close();
                        deviceList.remove(0);
                        if (deviceList.size() > 0) {

                            connectToDevice(0);
                        }
                    }
                }

                @Override
                // New services discovered
                public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                    if (status == BluetoothGatt.GATT_SUCCESS) {
                        //broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
                        boolean foundMatch = false;
                        services = mBluetoothGatt.getServices();
                        for (BluetoothGattService service : services) {
                            Log.d(TAG,"Service UUID xxx:"+service.getUuid());
                            if (service.getUuid().equals(SERVICE_UUID)) {
                                foundMatch = true;
                                //*
                                mService = service;
                                mWriteCharacteristic = service.getCharacteristic(WRITE_UUID);
                                mReadCharacteristic = service.getCharacteristic(READ_UUID);
                                mCreditCharacteristic = service.getCharacteristic(WRITE_UUID_2);
                                setCharacteristicNotification(mReadCharacteristic,true);

                                newData = true;
//There is a delay for this write because a mode request is sent first from onDescriptorWrite
                                Thread t = new Thread(new Runnable() {
                                    @Override
                                    public void run() {

                                        try {
                                            Thread.sleep(150);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                        byte[] infoRequest = {0x00, 0x02, 0x04, 0x00};
                                        write(infoRequest);
                                    }
                                });
                                t.start();
                                break;
                            }
                        }

                    } else {
                        Log.w(TAG, "onServicesDiscovered received: xxx " + status);
                    }
                }
                @Override
                public void onCharacteristicChanged(BluetoothGatt gatt,
                                                    BluetoothGattCharacteristic characteristic) {
                    //Log.d(TAG,"Charac changed..... xxx");

                    byte[] data = characteristic.getValue();
                    int dataSize = data.length;

                    System.arraycopy(data,0,rawBytes,bufferIndex,dataSize);
                    bufferIndex+=dataSize;
// The only way I can tell all the data has been received right now is to check the chunk size.
                    if (dataSize != 20) {
                        Log.d(TAG,"new data xxx");
                        newData = false;
                        bufferIndex = 0;

                        processData();
                    }
                }

                @Override
                public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
                    if (status == BluetoothGatt.GATT_SUCCESS) {
                        //if (descriptor.getCharacteristic().getUuid().equals(UUID_TARGET_CHARACTERISTIC)) {
                            Log.d(TAG, "Successfully subscribed xxx");
                        //}
                        // first thing I send is mode select request.
                        byte[] infoRequest = {0x06};
                        writeChangeMode(infoRequest);

                    } else {
                        Log.e(TAG, "Error subscribing");
                    }
                }

                @Override
                public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
                    if (status == BluetoothGatt.GATT_SUCCESS) {
                        //Write operation successful - process with next chunk!
                        Log.d(TAG,"Write successful xxx");
                    }
                }
                @Override
                public void onMtuChanged(BluetoothGatt gatt, int mtu, int status)                   {
                   super.onMtuChanged(gatt, mtu, status);
                   if ( status == BluetoothGatt.GATT_SUCCESS )
                      {
                          Log.d("TAG","call onMtuChanged "+status);
                      }
                }
            };


问:
How to pass data from one path to another in Spring
I have a list of locations that I send as a JSON to one path:

```<code>@RestController
public class Controller {

    List<GeoLoc> list = new ArrayList<GeoLoc>();
    @RequestMapping(
            value = "/myjson/{arraySize}")
    @ResponseBody
    public List<GeoLoc> createJSON(@PathVariable("arraySize") int arraySize)
</code>```

So on the path localhost:8080/myjson/somenumber I will have a list of JSONs.

But then, I would like to get that data from other method and path so that instead of JSON structure like this: {ID:1, town: "New York"} I got something like 1, New York. Basically plain String with comas, but I want that to be under other path, for example /myStrings. How could I make that request to read data from one path, change it and put into the another path? The @GetMapping changes my localhost:8080/myjson instead of just reading.

Thanks in advance.

答:
Assuming that the other method belongs to the same controller, you can just call locally the 'createJSON()' method and apply the transformations you need.

In case the other method belongs to a different controller, I think you could @Autowire the respective controller.

Body:
I have a list of locations that I send as a JSON to one path:

@RestController
public class Controller {

    List<GeoLoc> list = new ArrayList<GeoLoc>();
    @RequestMapping(
            value = "/myjson/{arraySize}")
    @ResponseBody
    public List<GeoLoc> createJSON(@PathVariable("arraySize") int arraySize)

So on the path localhost:8080/myjson/somenumber I will have a list of JSONs.

But then, I would like to get that data from other method and path so that instead of JSON structure like this: {ID:1, town: "New York"} I got something like 1, New York. Basically plain String with comas, but I want that to be under other path, for example /myStrings. How could I make that request to read data from one path, change it and put into the another path? The @GetMapping changes my localhost:8080/myjson instead of just reading.

Thanks in advance.


问:
UICollectionView Doesn't Respond Until Scrolling Completely Stops
I have a standard, working uicollectionview and my issue is when I scroll vertically, the uicollectionview doesn't respond to any subsequent touch (i.e. stop scroll) until after the scroll comes to a complete halt.

I was able to pin the issue down to the willDisplayCell delegate method where I'm animating each displaying cell with a bubble effect. I'm curious if there is anything within this I can be advised on where I'd still be able to retain the animation while responding to touches appropriately?

When I comment out the delegate method entirely, the responsiveness to touch and scroll work perfectly.

Here is my code in the willDisplayCell delegate method:

```<code>func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    cell.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
    DispatchQueue.main.async {
        let delay = 0.035
        UIView.animate(withDuration: 1, delay: delay, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.8, options: .curveEaseOut, animations: {
            cell.transform = CGAffineTransform(scaleX: 1, y: 1)
            self.view.layoutIfNeeded()
        }, completion: nil)
    }
}
</code>```

答:
Played around with your code and it seems that the problem originates from the fact that you're animating the cell itself, but if you animate the cell content instead, then the collection view is responsive while scrolling and at the same time keeping the bubble animation.

For example put all cell content inside one container view inside the cell, and animate that container view instead of animating the cell itself.

```<code>final class Cell: UICollectionViewCell {

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundView = UIView()
        backgroundView?.backgroundColor = .green
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
</code>```

```<code>func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    guard let cell = cell as? Cell else { return }
    cell.backgroundView?.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
    DispatchQueue.main.async {
        let delay = 0.035
        UIView.animate(withDuration: 1, delay: delay, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.8, options: .curveEaseOut, animations: {
            // you should reset the transform to CGAffineTransform.identity instead of CGAffineTransform(scaleX: 1, y: 1).
            cell.backgroundView?.transform = CGAffineTransform.identity
            // Not sure why you call layoutIfNeeded() here?, but without it the animation is much smoother.
            //self.view.layoutIfNeeded()
        }, completion: nil)
    }
}
</code>```

Body:
I have a standard, working uicollectionview and my issue is when I scroll vertically, the uicollectionview doesn't respond to any subsequent touch (i.e. stop scroll) until after the scroll comes to a complete halt.

I was able to pin the issue down to the willDisplayCell delegate method where I'm animating each displaying cell with a bubble effect. I'm curious if there is anything within this I can be advised on where I'd still be able to retain the animation while responding to touches appropriately?

When I comment out the delegate method entirely, the responsiveness to touch and scroll work perfectly.

Here is my code in the willDisplayCell delegate method:

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    cell.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
    DispatchQueue.main.async {
        let delay = 0.035
        UIView.animate(withDuration: 1, delay: delay, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.8, options: .curveEaseOut, animations: {
            cell.transform = CGAffineTransform(scaleX: 1, y: 1)
            self.view.layoutIfNeeded()
        }, completion: nil)
    }
}

Body:
Played around with your code and it seems that the problem originates from the fact that you're animating the cell itself, but if you animate the cell content instead, then the collection view is responsive while scrolling and at the same time keeping the bubble animation.

For example put all cell content inside one container view inside the cell, and animate that container view instead of animating the cell itself.

final class Cell: UICollectionViewCell {

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundView = UIView()
        backgroundView?.backgroundColor = .green
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    guard let cell = cell as? Cell else { return }
    cell.backgroundView?.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
    DispatchQueue.main.async {
        let delay = 0.035
        UIView.animate(withDuration: 1, delay: delay, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.8, options: .curveEaseOut, animations: {
            // you should reset the transform to CGAffineTransform.identity instead of CGAffineTransform(scaleX: 1, y: 1).
            cell.backgroundView?.transform = CGAffineTransform.identity
            // Not sure why you call layoutIfNeeded() here?, but without it the animation is much smoother.
            //self.view.layoutIfNeeded()
        }, completion: nil)
    }
}


问:
Alfred Workflow Bash Script Fails
I have created a script to automatically switch my Spotify UI from a light-theme to a dark-theme using Spicetify. The code for this script can is found here,

```<code>cd /Users/MY_ID/spicetify_data;

FILE=/Users/MY_ID/spicetify_data/nord.ini

if test -f "$FILE";
  then
    #We are in light mode, so switch us into dark mode.
    mv config.ini default.ini;
    mv nord.ini config.ini;
  else
    #We are in dark mode, so switch us into light mode.
    mv config.ini nord.ini;
    mv default.ini config.ini;
fi

spicetify update restart;
</code>```

Note: this is in a file called replace.sh

I have attempted creating many different styles of Alfred workflow to get this command to work. I have had success if I set up an Alfred workflow to run this as a Terminal Command, but this will open up many instances of the terminal, which is something I want to avoid. So Alfred says that to prevent this, I should create a Run Script action, but when I attempt this, nothing happens, and the UI theme does not change (even though it does if I use the Terminal Command setting.

Does anyone know what I could do to try and fix this workflow and allow this script to execute from just a Run Script action?

答:
You might want to invest in environment variables for workflows and not hardcoding paths in them, see official documentation for an example.

Basically you click your workflows env vars

and then you setup your PATH as you'd like

In your example, it would be something like /usr/local/Cellar/spicetify-cli/0.9.5/bin

This makes your workflow a bit more generic and share-able.

Title: Alfred Workflow Bash Script Fails

Body:
I have created a script to automatically switch my Spotify UI from a light-theme to a dark-theme using Spicetify. The code for this script can is found here,

cd /Users/MY_ID/spicetify_data;

FILE=/Users/MY_ID/spicetify_data/nord.ini

if test -f "$FILE";
  then
    #We are in light mode, so switch us into dark mode.
    mv config.ini default.ini;
    mv nord.ini config.ini;
  else
    #We are in dark mode, so switch us into light mode.
    mv config.ini nord.ini;
    mv default.ini config.ini;
fi

spicetify update restart;

Note: this is in a file called replace.sh

I have attempted creating many different styles of Alfred workflow to get this command to work. I have had success if I set up an Alfred workflow to run this as a Terminal Command, but this will open up many instances of the terminal, which is something I want to avoid. So Alfred says that to prevent this, I should create a Run Script action, but when I attempt this, nothing happens, and the UI theme does not change (even though it does if I use the Terminal Command setting.

Does anyone know what I could do to try and fix this workflow and allow this script to execute from just a Run Script action?


问:
Perl array vs list
I have two data structures in Perl:

An array:

```<code>my @array2 = ( "1", "2", "3");

for $elem (@array2) {
    print $elem."\n";
}
</code>```

Giving me the following output:

```<code>1
2
3
</code>```

And a list:

```<code>my @array = [ "1", "2", "3"];

for $elem (@array) {
    print $elem."\n";
}
</code>```

Giving the following output:

```<code>ARRAY(0x9c90818)
</code>```

Obviously, I'd like to iterate over the elements in both cases, but why does the second solution give me only the reference to this array?

答:
The square brackets are used to create an anonymous array. When evaluated, it returns a reference to this array, not the actual array values.

Parentheses have no such hidden property, but simply override precedence inside expressions, much like in math. For example:

```<code>my @array = 1,2,3;
</code>```

Is actually evaluated like this:

```<code>my @array = 1;
2,3; # causes the warning "Useless use of constant in void context"
</code>```

because the = operator has higher precedence than the commas. So to get around that, we use parentheses when assigning arrays, like so:

```<code>my @array = (1,2,3);
</code>```

Your example:

```<code>my @array = [1,2,3];
</code>```

is somewhat like saying this:

```<code>my @tmp = (1,2,3);
my @array = \@tmp;
</code>```

Where the \ is used to create a reference to the @tmp array.

Title: Perl array vs list

Body:
I have two data structures in Perl:

An array:

my @array2 = ( "1", "2", "3");

for $elem (@array2) {
    print $elem."\n";
}

Giving me the following output:

1
2
3

And a list:

my @array = [ "1", "2", "3"];

for $elem (@array) {
    print $elem."\n";
}

Giving the following output:

ARRAY(0x9c90818)

Obviously, I'd like to iterate over the elements in both cases, but why does the second solution give me only the reference to this array?

Body:
The square brackets are used to create an anonymous array. When evaluated, it returns a reference to this array, not the actual array values.

Parentheses have no such hidden property, but simply override precedence inside expressions, much like in math. For example:

my @array = 1,2,3;

Is actually evaluated like this:

my @array = 1;
2,3; # causes the warning "Useless use of constant in void context"

because the = operator has higher precedence than the commas. So to get around that, we use parentheses when assigning arrays, like so:

my @array = (1,2,3);

Your example:

my @array = [1,2,3];

is somewhat like saying this:

my @tmp = (1,2,3);
my @array = \@tmp;

Where the \ is used to create a reference to the @tmp array.


问:
Random number generation in multiple objects of the same class
In this example code, I am creating 100 objects in a list with random x values, but the problem is that all of the created objects have the same x value. I tried searching web for solutions for this but I couldn't find any.</p>

```<code>import random
list = []
class object:
    x = random.randint(1,1000)

for i in range(1,101):
    list.append(object())

for i in range(1,100):
    print(list[i].x)
</code>```

答:
Read up on Class and Instance Variables in the Python Docs to get clarification on your specific confusion.

Generally speaking, instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class:

class Dog:

    kind = 'canine'         # class variable shared by all instances

    def __init__(self, name):
        self.name = name    # instance variable unique to each instance

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind                  # shared by all dogs 'canine'
>>> e.kind                  # shared by all dogs 'canine'
>>> d.name                  # unique to d 'Fido'
>>> e.name                  # unique to e 'Buddy' ```
</code>```

What you are looking for, as @rassar suggested, is:

class Obj:
    def __init__(self):
        self.x = random.randint(1,1000)

a = Obj()
b = Obj()
c = Obj()

print(a.x, b.x, c.x)
```

Body:
In this example code, I am creating 100 objects in a list with random x values, but the problem is that all of the created objects have the same x value. I tried searching web for solutions for this but I couldn't find any.

import random
list = []
class object:
    x = random.randint(1,1000)

for i in range(1,101):
    list.append(object())

for i in range(1,100):
    print(list[i].x)

Body:
Read up on Class and Instance Variables in the Python Docs to get clarification on your specific confusion.

Generally speaking, instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class:

class Dog:

    kind = 'canine'         # class variable shared by all instances

    def __init__(self, name):
        self.name = name    # instance variable unique to each instance

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind                  # shared by all dogs 'canine'
>>> e.kind                  # shared by all dogs 'canine'
>>> d.name                  # unique to d 'Fido'
>>> e.name                  # unique to e 'Buddy' ```

What you are looking for, as @rassar suggested, is:

class Obj:
    def __init__(self):
        self.x = random.randint(1,1000)

a = Obj()
b = Obj()
c = Obj()

print(a.x, b.x, c.x)


问:
What is the syntax for using the restrict keyword for a 2d array function parameter?
I have an array declared in my main function:
float A[n][n];

My goal is to pass it to a function with the restrict keyword:
void func(int n, float restrict A[][n])

I tried the syntax above, but I am not getting the optimization in running time that I am expecting. I have also seen this syntax for 1d arrays:
void func(int n, float A[restrict])

答:
The pointer can be restrict. All below forms are equivalent:</p>

```<code>void func(int n, float A[restrict n][n]);
void func(int n, float A[restrict][n]);
void func(int n, float (* restrict A)[n]);
</code>```

Body:
The pointer can be restrict. All below forms are equivalent:

void func(int n, float A[restrict n][n]);
void func(int n, float A[restrict][n]);
void func(int n, float (* restrict A)[n]);


问:
deft mode terribly slow
I just started using emacs24 (the one that comes with Ubuntu) in order to use deft mode to mimic the behavior of notational velocity on the Mac. My ~/.emacs-d/init.el looks like this:

```<code>(add-to-list 'load-path "~/.emacs.d")
(require 'deft)
(setq deft-directory "~/Notes")
(setq deft-use-filename-as-title t)
</code>```

in order to load my folder with txt files. I have a few thousand text files in the folder with file names that include CJK characters. Now, running deft mode is now /extremely/ slow, it's impossible to even type to search among the files. After typing a word I have to wait for several minutes before it shows up on the screen and searches through the notes. Even turning emacs off takes a long time. My computer is a Lenovo W540 64-bit i7-4800MQ CPU @ 2.70GHz × 8 and 23.2 GiB memory (it tells me). I'm running Ubuntu 14.04. What might be wrong with my emacs?

I'm new to emacs and frankly I don't even understand what I just wrote above, I'm just trying to piece the setup I want together from tutorials I find online, so forgive any stupidities that might have slipped into my question. Thanks in advance!

答:
As of version 0.9, a variable deft-file-limit was added, setting the "maximum number of files to list in the Deft browser."

So to replicate trmdttr's configuration answer for 30 files, you'd add this to your configuration:

```<code>(setq deft-file-limit 30)
</code>```

Title: deft mode terribly slow

Body:
I just started using emacs24 (the one that comes with Ubuntu) in order to use deft mode to mimic the behavior of notational velocity on the Mac. My ~/.emacs-d/init.el looks like this:

(add-to-list 'load-path "~/.emacs.d")
(require 'deft)
(setq deft-directory "~/Notes")
(setq deft-use-filename-as-title t)

in order to load my folder with txt files. I have a few thousand text files in the folder with file names that include CJK characters. Now, running deft mode is now /extremely/ slow, it's impossible to even type to search among the files. After typing a word I have to wait for several minutes before it shows up on the screen and searches through the notes. Even turning emacs off takes a long time. My computer is a Lenovo W540 64-bit i7-4800MQ CPU @ 2.70GHz × 8 and 23.2 GiB memory (it tells me). I'm running Ubuntu 14.04. What might be wrong with my emacs?

I'm new to emacs and frankly I don't even understand what I just wrote above, I'm just trying to piece the setup I want together from tutorials I find online, so forgive any stupidities that might have slipped into my question. Thanks in advance!

Body:
As of version 0.9, a variable deft-file-limit was added, setting the "maximum number of files to list in the Deft browser."

So to replicate trmdttr's configuration answer for 30 files, you'd add this to your configuration:

(setq deft-file-limit 30)


问:
Java IO with UTF characters
I have a weird problem with files.

I intend to modify the timing of an .srt file, but writing the new file seems to be a weird task.

Here's a sample code I wrote:

```<code>import java.io.*;
import java.nio.charset.Charset;

public class ReaderWriter {
    public static void main(String[] args) throws IOException {
        InputStream inputStream = new FileInputStream("D:\\E\\Movies\\English\\1960's\\TheApartment1960.srt");
        Reader reader = new InputStreamReader(inputStream,
                Charset.forName("UTF-8"));
        OutputStream outputStream = new FileOutputStream("output.srt");
        Writer writer = new OutputStreamWriter(outputStream,
                Charset.forName("UTF-8"));

        int data = reader.read();
        while (data != -1) {
            char theChar = (char) data;
            writer.write(theChar);
            data = reader.read();
        }
        reader.close();
        writer.close();
    }
}
</code>```

This is an image from the original file:

However, the resulted file seems like:

I searched a lot for a solution but in vain. Any help, please.

答:
First a few points:

There is nothing wrong with your Java code. If I use it to read an input file containing Arabic text encoded in UTF-8 it creates the output file encoded in UTF-8 with no problems.

I don't think there is a font issue. Since you can successfully display the content of the input file there is no reason you cannot also successfully display the content of a valid output file.

Those black diamonds with question marks in the output file are replacement characters which are "used to replace an incoming character whose value is unknown or unrepresentable in Unicode". This indicates that the input file you are reading is not UTF-8 encoded, even though the code explicitly states that it is. I can reproduce similar results to yours if the input file is UTF-16 encoded, but specified as UTF-8 in the code.

Alternatively, if the input file truly is UTF-8 encoded, specify it as UTF-16 in the code. For example, here is a valid UTF-8 input file with some Arabic text where the code (incorrectly) stated Reader reader = new InputStreamReader(inputStream, Charset.forName("UTF-16"));:

يونكود في النظم القائمة وفيما يخص التطبيقات الحاسوبية، الخطوط، تصميم النصوص والحوسبة متعددة اللغات.

And here is the output file, containing the replacement characters because the input stream of the UTF-8 file was incorrectly processed as UTF-16:

���⃙臙訠���ꟙ蓙苘Ꟙꛙ藘ꤠ���諘께딠�����ꟙ蓘귘Ꟙ동裘꣙諘꧘谠����꫘뗙藙諙蔠���⃙裘ꟙ蓘귙裘돘꣘ꤠ���⃘ꟙ蓙蓘뫘Ꟙꨮ�

Given all that, simply ensuring that the encoding of the input file is specified correctly in the InputStreamReader() constructor should solve your problem. To verify this, just create another input file and save it with UTF-8 character encoding, then run your code. If it works then you know that the problem was the that the encoding of input file was not UTF-8.

Title: Java IO with UTF characters

Body:
I have a weird problem with files.

I intend to modify the timing of an .srt file, but writing the new file seems to be a weird task.

Here's a sample code I wrote:

import java.io.*;
import java.nio.charset.Charset;

public class ReaderWriter {
    public static void main(String[] args) throws IOException {
        InputStream inputStream = new FileInputStream("D:\\E\\Movies\\English\\1960's\\TheApartment1960.srt");
        Reader reader = new InputStreamReader(inputStream,
                Charset.forName("UTF-8"));
        OutputStream outputStream = new FileOutputStream("output.srt");
        Writer writer = new OutputStreamWriter(outputStream,
                Charset.forName("UTF-8"));

        int data = reader.read();
        while (data != -1) {
            char theChar = (char) data;
            writer.write(theChar);
            data = reader.read();
        }
        reader.close();
        writer.close();
    }
}

This is an image from the original file:

However, the resulted file seems like:

I searched a lot for a solution but in vain. Any help, please.


问:
GroupBy aggregation based on condition and year wise sum using pandas
I have a data frame as shown below

```<code>ID    Sector  Plot  Tenancy_Start_Date      Rental
1     SE1     A     2018-08-14              100
1     SE1     A     2019-08-18              200
2     SE1     B     2017-08-12              150
3     SE1     A     2020-02-12              300
5     SE2     A     2017-08-13              400
5     SE2     A     2019-08-12              300
6     SE2     B     2019-08-11              150
5     SE2     A     2020-01-10              300
7     SE2     B     2019-08-11              500
</code>```

From the above I would like to prepare below data frame as Sector and Plot aggregation level.

Expected Output:

```<code>Sector  Plot       Total_Rental   Rental_2017  Rental_2018  Rental_2019    Rental_2020
SE1     A          600            0            100          200            300
SE1     B          150            150          0            0              0
SE2     A          1000           400          0            300            300
SE2     B          650            0            0            650            0
</code>```

答:
You can do (df being your input dataframe):

#in case if it's not already a datetime:
df["Tenancy_Start_Date"]=pd.to_datetime(df["Tenancy_Start_Date"])

df2=df.pivot_table(index=["Sector", "Plot"], columns=df["Tenancy_Start_Date"].dt.year, values="Rental", aggfunc=sum).fillna(0)

df2.columns=[f"Rental_{col}" for col in df2.columns]

df2["Total_Rental"]=df2.sum(axis=1)

df2=df2.reset_index(drop=False)
```

<p>Outputs:</p>

<pre class="lang-py prettyprint-override"><code>  Sector Plot  ...  Rental_2020  Total_Rental
0    SE1    A  ...        300.0         600.0
1    SE1    B  ...          0.0         150.0
2    SE2    A  ...        300.0        1000.0
3    SE2    B  ...          0.0         650.0
</code>```

Body:
I have a data frame as shown below

ID    Sector  Plot  Tenancy_Start_Date      Rental
1     SE1     A     2018-08-14              100
1     SE1     A     2019-08-18              200
2     SE1     B     2017-08-12              150
3     SE1     A     2020-02-12              300
5     SE2     A     2017-08-13              400
5     SE2     A     2019-08-12              300
6     SE2     B     2019-08-11              150
5     SE2     A     2020-01-10              300
7     SE2     B     2019-08-11              500

From the above I would like to prepare below data frame as Sector and Plot aggregation level.

Expected Output:

Sector  Plot       Total_Rental   Rental_2017  Rental_2018  Rental_2019    Rental_2020
SE1     A          600            0            100          200            300
SE1     B          150            150          0            0              0
SE2     A          1000           400          0            300            300
SE2     B          650            0            0            650            0

Body:
You can do (df being your input dataframe):

#in case if it's not already a datetime:
df["Tenancy_Start_Date"]=pd.to_datetime(df["Tenancy_Start_Date"])

df2=df.pivot_table(index=["Sector", "Plot"], columns=df["Tenancy_Start_Date"].dt.year, values="Rental", aggfunc=sum).fillna(0)

df2.columns=[f"Rental_{col}" for col in df2.columns]

df2["Total_Rental"]=df2.sum(axis=1)

df2=df2.reset_index(drop=False)

Outputs:

  Sector Plot  ...  Rental_2020  Total_Rental
0    SE1    A  ...        300.0         600.0
1    SE1    B  ...          0.0         150.0
2    SE2    A  ...        300.0        1000.0
3    SE2    B  ...          0.0         650.0


问:
How to catch a value and tell the user to input again?
I'm trying to create a game character, and the user is asked to input a number between 0-18. I input 19 to see if the code will tell me to try again, but it just ignores it and then prints out the character. It also does the same thing for the magic amount. The user should enter between 0 & 50, but if I enter a number higher than 50, it will also still print it. I want the code to tell me the input was wrong and try again. Is there a way I could ask the user to try again without using an exception?</p>

```<code>public class Character {

    private String name;
    private int strength;

    public Character() {
        name = "TBD";
        strength = 15;
    }

    public Character(String name, int strength) {
        this.name = name;
        this.strength = strength;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getStrength() {
        return strength;
    }

    public void setStrength(int strength) {
        int count = 1;
        while (true) {
            if (strength >= 0 && strength <= 18) {
                System.out.println("Value is out of range 0-18");
                System.out.println("Please try again");
                break;
            }
            else {
                this.strength = strength;
                count = 0;
            }
        }
    }

    public String toString() {
        return "Name: " + name + ", Strength: " + strength;
    }
}
</code>```

```<code>public class Human extends Character {

    private String name;
    private int strength;
    private String weapon;
    private int magicAmount;

    public Human(String name, int strength, String weapon, int magicAmount) {
        this.name = name;
        this.strength = strength;
        this.weapon = weapon;
        this.magicAmount = magicAmount;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getStrength() {
        return strength;
    }

    public void setStrength(int strength) {
        this.strength = strength;
    }

    public String getWeapon() {
        return weapon;
    }

    public void setWeapon(String weapon) {
        this.weapon = weapon;
    }

    public int getMagicAmount() {
        return magicAmount;
    }

    public void setMagicAmount(int magicAmount) {
        int count = 1;
        while (count != 0) {
            if ((magicAmount >= 0 && magicAmount <= 50)) {
                System.out.println("Value is out of range 0-50");
                System.out.println("Please try again");
                break;
            }
            else {
                this.magicAmount = magicAmount;
                count = 0;
            }
        }
    }

    public String toString() {
        return "Human [Name: " + name + ", Strength: " + strength + ", Weapon: "
                + weapon + ", Magic Amount: " + magicAmount + "]";
    }
}

</code>```

```<code>    ArrayList<Character> characters = new ArrayList<Character>();

    String keepLooping = "y";

    do {
        System.out.println("Which character would you like to create (Human, Robot, or Animal): ");
        String choice = input.nextLine();

        if (choice.equalsIgnoreCase("Human")) {

            System.out.println("Enter a name for the Human: ");
            String name = input.next();

            System.out.println("Enter the amount of stength for Human (0-18): ");
            int strength = input.nextInt();

            input.nextLine();
            System.out.println("Enter a weapon for Human (Sword or Dagger): ");
            String weapon = input.nextLine();

            System.out.println("Enter the magic amount for your selected weapon (0-50): ");
            int magicAmount = input.nextInt();

            Human charH = new Human(name, strength, weapon, magicAmount);
            characters.add(charH);
        }

        input.nextLine();
        System.out.println("Would you like to create more characters - y or n");
        keepLooping = input.nextLine();
    }

    while (keepLooping.equalsIgnoreCase("y"));

    for (int i = 0; i < characters.size(); i++) {
        Character c = characters.get(i);
        System.out.println(c);
    }
}
</code>```

```<code>
</code>```

答:
You should do validation on the user input, for example (strength):

```<code>Integer strength = null;
while (strength == null) {
    System.out.println("Enter the amount of stength for Human (0-18): ");
    strength = input.nextInt();

    if (strength < 0 || strength > 18) {
        strength = null;
        System.out.println("Invalid strength, please try again");
    }
}
</code>```

The other issue is that you have your validation login in setStrength, but that is never called, as you set the strength in the constructor. So a fix would be:

```<code>public Character(String name, int strength) {
    setName(name);
    setStrength(strength);
}
</code>```

Body:
I'm trying to create a game character, and the user is asked to input a number between 0-18. I input 19 to see if the code will tell me to try again, but it just ignores it and then prints out the character. It also does the same thing for the magic amount. The user should enter between 0 & 50, but if I enter a number higher than 50, it will also still print it. I want the code to tell me the input was wrong and try again. Is there a way I could ask the user to try again without using an exception?

public class Character {

    private String name;
    private int strength;

    public Character() {
        name = "TBD";
        strength = 15;
    }

    public Character(String name, int strength) {
        this.name = name;
        this.strength = strength;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getStrength() {
        return strength;
    }

    public void setStrength(int strength) {
        int count = 1;
        while (true) {
            if (strength >= 0 && strength <= 18) {
                System.out.println("Value is out of range 0-18");
                System.out.println("Please try again");
                break;
            }
            else {
                this.strength = strength;
                count = 0;
            }
        }
    }

    public String toString() {
        return "Name: " + name + ", Strength: " + strength;
    }
}

public class Human extends Character {

    private String name;
    private int strength;
    private String weapon;
    private int magicAmount;

    public Human(String name, int strength, String weapon, int magicAmount) {
        this.name = name;
        this.strength = strength;
        this.weapon = weapon;
        this.magicAmount = magicAmount;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getStrength() {
        return strength;
    }

    public void setStrength(int strength) {
        this.strength = strength;
    }

    public String getWeapon() {
        return weapon;
    }

    public void setWeapon(String weapon) {
        this.weapon = weapon;
    }

    public int getMagicAmount() {
        return magicAmount;
    }

    public void setMagicAmount(int magicAmount) {
        int count = 1;
        while (count != 0) {
            if ((magicAmount >= 0 && magicAmount <= 50)) {
                System.out.println("Value is out of range 0-50");
                System.out.println("Please try again");
                break;
            }
            else {
                this.magicAmount = magicAmount;
                count = 0;
            }
        }
    }

    public String toString() {
        return "Human [Name: " + name + ", Strength: " + strength + ", Weapon: "
                + weapon + ", Magic Amount: " + magicAmount + "]";
    }
}

    ArrayList<Character> characters = new ArrayList<Character>();

    String keepLooping = "y";

    do {
        System.out.println("Which character would you like to create (Human, Robot, or Animal): ");
        String choice = input.nextLine();

        if (choice.equalsIgnoreCase("Human")) {

            System.out.println("Enter a name for the Human: ");
            String name = input.next();

            System.out.println("Enter the amount of stength for Human (0-18): ");
            int strength = input.nextInt();

            input.nextLine();
            System.out.println("Enter a weapon for Human (Sword or Dagger): ");
            String weapon = input.nextLine();

            System.out.println("Enter the magic amount for your selected weapon (0-50): ");
            int magicAmount = input.nextInt();

            Human charH = new Human(name, strength, weapon, magicAmount);
            characters.add(charH);
        }

        input.nextLine();
        System.out.println("Would you like to create more characters - y or n");
        keepLooping = input.nextLine();
    }

    while (keepLooping.equalsIgnoreCase("y"));

    for (int i = 0; i < characters.size(); i++) {
        Character c = characters.get(i);
        System.out.println(c);
    }
}

Body:
You should do validation on the user input, for example (strength):

Integer strength = null;
while (strength == null) {
    System.out.println("Enter the amount of stength for Human (0-18): ");
    strength = input.nextInt();

    if (strength < 0 || strength > 18) {
        strength = null;
        System.out.println("Invalid strength, please try again");
    }
}

The other issue is that you have your validation login in setStrength, but that is never called, as you set the strength in the constructor. So a fix would be:

public Character(String name, int strength) {
    setName(name);
    setStrength(strength);
}


问:
Javascript changing function trouble
The code below is how it was originally

```<code>   function getRandomEmail() {
        const randomNumber = Math.floor(Math.random() * 200000)+1;
        return `User${randomNumber}@example.com`
    }
</code>```

Instead of a random number generated and inserted I am trying to have an list of words added infront of the @example.com

like so

```<code>function getRandomEmail() {
var emailname = "testing testing2 testing3".split(" ");
return `User$(Math.floor(Math.random() * emailname.split)+ @example.com`
</code>```

The output I'm getting now while running the script is

BAD_EMAIL: that email is invalid

did I miss anything ???

答:
I think the following is good as far my knowledge goes. Is it correct ? Did I miss anything ?

edit: doesn't function as expected. the same 'word' from the array gets used multiple times and the array is never emptied.

function getRandomEmail() {
        var emailname = "test1 test2 test3".split(" ");
        const randomElement = emailname[Math.floor(Math.random() * emailname.length)];
        const index = emailname.indexOf(randomElement);
          if (index > -1){ emailname.splice(index, 1);}
          console.log(emailname);
          if (emailname && emailname.length > 0) {
       console.log('emailname is not empty.');
       return `${randomElement}@example.com`;
    }else{
       console.log('emailname is empty.');
    }
        return ("no mail available");
    }

     console.log(getRandomEmail());```

Title: Javascript changing function trouble

Body:
The code below is how it was originally

   function getRandomEmail() {
        const randomNumber = Math.floor(Math.random() * 200000)+1;
        return `User${randomNumber}@example.com`
    }

Instead of a random number generated and inserted I am trying to have an list of words added infront of the @example.com

like so

function getRandomEmail() {
var emailname = "testing testing2 testing3".split(" ");
return `User$(Math.floor(Math.random() * emailname.split)+ @example.com`

The output I'm getting now while running the script is

BAD_EMAIL: that email is invalid

did I miss anything ???


问:
Can I rely on an unescaped ampersand displaying correctly in a textarea?
I've just notice a routine in our code that doesn't properly escape an ampersand in a textarea:

```<code><textarea>Arts & Crafts</textarea>
</code>```

What surprises me is that this works in every browser I check. Is there an unwritten rule about ampersands inside textareas? If so, is it a rule I can depend on? Or is this just a convenience that browsers provide to make sure your faulty page renders and there are no guarantees whatsoever?

答:
Most browsers will try to fix errors made in the page. The ampersand cannot mean anything else than an ampersand, so it is shown as such. Alternatives would be to skip the ampersand, or not to render the page at all, but all vendors have thought this fallback to be the most logical one.

It will give you problems when the text is for example <textarea>Use è to show an è</textarea>, because this will render è as an è too. So in this case the ampersand must be escaped.

It is however one of the very few errors that are solved the same way in any browser. It is best not to make any error. That will give you the greatest chance on succes. ;)

Body:
I've just notice a routine in our code that doesn't properly escape an ampersand in a textarea:

<textarea>Arts & Crafts</textarea>

What surprises me is that this works in every browser I check. Is there an unwritten rule about ampersands inside textareas? If so, is it a rule I can depend on? Or is this just a convenience that browsers provide to make sure your faulty page renders and there are no guarantees whatsoever?

Body:
Most browsers will try to fix errors made in the page. The ampersand cannot mean anything else than an ampersand, so it is shown as such. Alternatives would be to skip the ampersand, or not to render the page at all, but all vendors have thought this fallback to be the most logical one.

It will give you problems when the text is for example <textarea>Use &egrave; to show an è</textarea>, because this will render &egrave; as an è too. So in this case the ampersand must be escaped.

It is however one of the very few errors that are solved the same way in any browser. It is best not to make any error. That will give you the greatest chance on succes. ;)


问:
How do I remove duplicate words in a string in JavaScript?
I've been trying to remove duplicate words from a string, and it's not working.

I have the current string:

```<code>const categories = 'mexican, restaurant, mexican, food, restaurant'
</code>```

and I want this outcome:

```<code>const x = 'mexican restaurant food'
</code>```

I have tried the following:

```<code>const x = categories.replace(/,/g, '');

    const uniqueList = x
      .split()
      .filter((currentItem, i, allItems) => {
        return i === allItems.indexOf(currentItem);
      })
      .join();
</code>```

Which is giving me:

```<code>uniqueList = 'chinese restaurant chinese food restaurant'
</code>```

What is wrong with the code above?

答:
In String.prototype.split(separator) method, which is used by you, if separator is missed will be returned array with one element - source string. So in your code should be .split(' ') instead of .split().
But better use .split(', ') without const x = categories.replace(/,/g, '');. And even you can .split(/\s*,\s*/), in this way you don't have to care about spaces.
Join by default use ',' as separator. So you should write .join(' ').

Body:
I've been trying to remove duplicate words from a string, and it's not working.

I have the current string:

const categories = 'mexican, restaurant, mexican, food, restaurant'

and I want this outcome:

const x = 'mexican restaurant food'

I have tried the following:

const x = categories.replace(/,/g, '');

    const uniqueList = x
      .split()
      .filter((currentItem, i, allItems) => {
        return i === allItems.indexOf(currentItem);
      })
      .join();

Which is giving me:

uniqueList = 'chinese restaurant chinese food restaurant'

What is wrong with the code above?


答:
I like using Set for this kind of purposes. Read in the documentation:

The Set object lets you store unique values of any type, whether primitive values or object references.

This can work for you:

const categories = 'mexican, restaurant, mexican, food, restaurant'.split(', ');

const unique = Array.from(new Set(categories));

console.log(unique);

console.log(unique.join(' '));```

I hope that helps!

Title: How do I remove duplicate words in a string in JavaScript?

Body:
I like using Set for this kind of purposes. Read in the documentation:

The Set object lets you store unique values of any type, whether primitive values or object references.

This can work for you:

const categories = 'mexican, restaurant, mexican, food, restaurant'.split(', ');

const unique = Array.from(new Set(categories));

console.log(unique);

console.log(unique.join(' '));

I hope that helps!


问:
How to add to a Current Value method for a calculator
I am creating a memory calculator. In my code, I have a current value method and need it to return a new value when the operator either decides to add, subtract, multiply, etc... I am having trouble with figuring out how to change the current value field. When i chose to add a number to the current value, the value stays the same as before, 0.

FIRST CLASS

```<code>import java.util.Scanner;

public class MemoryCalculator {
private double currentValue;

    public static int displayMenu() {
        Scanner input = new Scanner(System.in);

        System.out.println("Menu");
        System.out.println("1. Add ");
        System.out.println("2. Subtract ");
        System.out.println("3. Multiply ");
        System.out.println("4. Divide ");
        System.out.println("5. Clear ");
        System.out.println("6. End");
        System.out.println("Please choose which math operation to perform, or press 6 to quit.");

        int selection = input.nextInt();

        return selection;

    }
    public static double getOperand(String prompt) {
        Scanner input = new Scanner(System.in);
        System.out.println(prompt);

        double operand = input.nextDouble();

        return operand;

    }
    public double getCurrentValue() {
        this.currentValue = currentValue;
        return currentValue;

    }
    public void add(double operand2) {
        this.currentValue = getCurrentValue() + operand2;
        getCurrentValue();

    }
    public void subtract(double operand2) {

    }
    public void multiply(double operand2) {

    }
    public void divide(double operand2) {

    }
    public void clear() {

    }

}
</code>```

SECOND CLASS DRIVER CLASS

```<code>public class MemoryCalculatorDriver {

public static void main(String[] args) {
    double operand2 = 0;

    MemoryCalculator CalcObj = new MemoryCalculator();

    System.out.println(CalcObj.getCurrentValue());
    int selection = CalcObj.displayMenu();

    if(selection == 1) {
        System.out.println(CalcObj.getOperand("What would you like the second number to be"));

        CalcObj.add(operand2);

        System.out.println(CalcObj.getCurrentValue());

    }else if (selection == 2) {
        System.out.println(CalcObj.getOperand("What would you like the second number to be"));

        CalcObj.subtract(operand2);

        System.out.println(CalcObj.getCurrentValue());

    }else if (selection == 3) {
        System.out.println(CalcObj.getOperand("What would you like the second number to be"));

        CalcObj.multiply(operand2);

        System.out.println(CalcObj.getCurrentValue());

    }else if (selection == 4) {
        System.out.println(CalcObj.getOperand("What would you like the second number to be"));

        CalcObj.divide(operand2);

        System.out.println(CalcObj.getCurrentValue());

    }else if (selection == 5) {
        CalcObj.clear();

        System.out.println(CalcObj.getCurrentValue());

    }else if (selection == 6) {
        System.out.println("Goodbye");
    }

}

}
</code>```

I am able to get the selection input from the user, and I can get the first number from the user. When I chose option 1 "add", the user can input the number but, the number was not added the the current value.

答:
You returns value by this method public static double getOperand(String prompt) but where you used returned value?

It must be like this:

```<code>if(selection == 1) {
        operand2 = CalcObj.getOperand("What would you like the second number to be"));
        CalcObj.add(operand2);
        System.out.println(CalcObj.getCurrentValue());

        // your code like this...
}
</code>```

Body:
I am creating a memory calculator. In my code, I have a current value method and need it to return a new value when the operator either decides to add, subtract, multiply, etc... I am having trouble with figuring out how to change the current value field. When i chose to add a number to the current value, the value stays the same as before, 0.

FIRST CLASS

import java.util.Scanner;

public class MemoryCalculator {
private double currentValue;

    public static int displayMenu() {
        Scanner input = new Scanner(System.in);

        System.out.println("Menu");
        System.out.println("1. Add ");
        System.out.println("2. Subtract ");
        System.out.println("3. Multiply ");
        System.out.println("4. Divide ");
        System.out.println("5. Clear ");
        System.out.println("6. End");
        System.out.println("Please choose which math operation to perform, or press 6 to quit.");

        int selection = input.nextInt();

        return selection;

    }
    public static double getOperand(String prompt) {
        Scanner input = new Scanner(System.in);
        System.out.println(prompt);

        double operand = input.nextDouble();

        return operand;

    }
    public double getCurrentValue() {
        this.currentValue = currentValue;
        return currentValue;

    }
    public void add(double operand2) {
        this.currentValue = getCurrentValue() + operand2;
        getCurrentValue();

    }
    public void subtract(double operand2) {

    }
    public void multiply(double operand2) {

    }
    public void divide(double operand2) {

    }
    public void clear() {

    }

}

SECOND CLASS DRIVER CLASS

public class MemoryCalculatorDriver {

public static void main(String[] args) {
    double operand2 = 0;

    MemoryCalculator CalcObj = new MemoryCalculator();

    System.out.println(CalcObj.getCurrentValue());
    int selection = CalcObj.displayMenu();

    if(selection == 1) {
        System.out.println(CalcObj.getOperand("What would you like the second number to be"));

        CalcObj.add(operand2);

        System.out.println(CalcObj.getCurrentValue());

    }else if (selection == 2) {
        System.out.println(CalcObj.getOperand("What would you like the second number to be"));

        CalcObj.subtract(operand2);

        System.out.println(CalcObj.getCurrentValue());

    }else if (selection == 3) {
        System.out.println(CalcObj.getOperand("What would you like the second number to be"));

        CalcObj.multiply(operand2);

        System.out.println(CalcObj.getCurrentValue());

    }else if (selection == 4) {
        System.out.println(CalcObj.getOperand("What would you like the second number to be"));

        CalcObj.divide(operand2);

        System.out.println(CalcObj.getCurrentValue());

    }else if (selection == 5) {
        CalcObj.clear();

        System.out.println(CalcObj.getCurrentValue());

    }else if (selection == 6) {
        System.out.println("Goodbye");
    }

}

}

I am able to get the selection input from the user, and I can get the first number from the user. When I chose option 1 "add", the user can input the number but, the number was not added the the current value.

Body:
You returns value by this method public static double getOperand(String prompt) but where you used returned value?

It must be like this:

if(selection == 1) {
        operand2 = CalcObj.getOperand("What would you like the second number to be"));
        CalcObj.add(operand2);
        System.out.println(CalcObj.getCurrentValue());

        // your code like this...
}